|
| 1 | +import sys |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from sentry_sdk.integrations.sys_exit import SysExitIntegration |
| 6 | + |
| 7 | + |
| 8 | +@pytest.mark.parametrize( |
| 9 | + ("integration_params", "exit_status", "should_capture"), |
| 10 | + ( |
| 11 | + ({}, 0, False), |
| 12 | + ({}, 1, True), |
| 13 | + ({}, None, False), |
| 14 | + ({}, "unsuccessful exit", True), |
| 15 | + ({"capture_successful_exits": False}, 0, False), |
| 16 | + ({"capture_successful_exits": False}, 1, True), |
| 17 | + ({"capture_successful_exits": False}, None, False), |
| 18 | + ({"capture_successful_exits": False}, "unsuccessful exit", True), |
| 19 | + ({"capture_successful_exits": True}, 0, True), |
| 20 | + ({"capture_successful_exits": True}, 1, True), |
| 21 | + ({"capture_successful_exits": True}, None, True), |
| 22 | + ({"capture_successful_exits": True}, "unsuccessful exit", True), |
| 23 | + ), |
| 24 | +) |
| 25 | +def test_sys_exit( |
| 26 | + sentry_init, capture_events, integration_params, exit_status, should_capture |
| 27 | +): |
| 28 | + sentry_init(integrations=[SysExitIntegration(**integration_params)]) |
| 29 | + |
| 30 | + events = capture_events() |
| 31 | + |
| 32 | + # Manually catch the sys.exit rather than using pytest.raises because IDE does not recognize that pytest.raises |
| 33 | + # will catch SystemExit. |
| 34 | + try: |
| 35 | + sys.exit(exit_status) |
| 36 | + except SystemExit: |
| 37 | + ... |
| 38 | + else: |
| 39 | + pytest.fail("Patched sys.exit did not raise SystemExit") |
| 40 | + |
| 41 | + if should_capture: |
| 42 | + (event,) = events |
| 43 | + (exception_value,) = event["exception"]["values"] |
| 44 | + |
| 45 | + assert exception_value["type"] == "SystemExit" |
| 46 | + assert exception_value["value"] == ( |
| 47 | + str(exit_status) if exit_status is not None else "" |
| 48 | + ) |
| 49 | + else: |
| 50 | + assert len(events) == 0 |
| 51 | + |
| 52 | + |
| 53 | +def test_sys_exit_integration_not_auto_enabled(sentry_init, capture_events): |
| 54 | + sentry_init() # No SysExitIntegration |
| 55 | + |
| 56 | + events = capture_events() |
| 57 | + |
| 58 | + # Manually catch the sys.exit rather than using pytest.raises because IDE does not recognize that pytest.raises |
| 59 | + # will catch SystemExit. |
| 60 | + try: |
| 61 | + sys.exit(1) |
| 62 | + except SystemExit: |
| 63 | + ... |
| 64 | + else: |
| 65 | + pytest.fail( |
| 66 | + "sys.exit should not be patched, but it must have been because it did not raise SystemExit" |
| 67 | + ) |
| 68 | + |
| 69 | + assert ( |
| 70 | + len(events) == 0 |
| 71 | + ), "No events should have been captured because sys.exit should not have been patched" |
0 commit comments