|
| 1 | +import random |
| 2 | + |
| 3 | +from sentry_sdk import Hub, start_transaction |
| 4 | +from sentry_sdk.transport import Transport |
| 5 | + |
| 6 | + |
| 7 | +class HealthyTestTransport(Transport): |
| 8 | + def _send_event(self, event): |
| 9 | + pass |
| 10 | + |
| 11 | + def _send_envelope(self, envelope): |
| 12 | + pass |
| 13 | + |
| 14 | + def is_healthy(self): |
| 15 | + return True |
| 16 | + |
| 17 | + |
| 18 | +class UnhealthyTestTransport(HealthyTestTransport): |
| 19 | + def is_healthy(self): |
| 20 | + return False |
| 21 | + |
| 22 | + |
| 23 | +def test_no_monitor_if_disabled(sentry_init): |
| 24 | + sentry_init(transport=HealthyTestTransport()) |
| 25 | + assert Hub.current.client.monitor is None |
| 26 | + |
| 27 | + |
| 28 | +def test_monitor_if_enabled(sentry_init): |
| 29 | + sentry_init( |
| 30 | + transport=HealthyTestTransport(), |
| 31 | + _experiments={"enable_backpressure_handling": True}, |
| 32 | + ) |
| 33 | + |
| 34 | + monitor = Hub.current.client.monitor |
| 35 | + assert monitor is not None |
| 36 | + assert monitor._thread is None |
| 37 | + |
| 38 | + assert monitor.is_healthy() is True |
| 39 | + assert monitor.downsample_factor == 1 |
| 40 | + assert monitor._thread is not None |
| 41 | + assert monitor._thread.name == "sentry.monitor" |
| 42 | + |
| 43 | + |
| 44 | +def test_monitor_unhealthy(sentry_init): |
| 45 | + sentry_init( |
| 46 | + transport=UnhealthyTestTransport(), |
| 47 | + _experiments={"enable_backpressure_handling": True}, |
| 48 | + ) |
| 49 | + |
| 50 | + monitor = Hub.current.client.monitor |
| 51 | + monitor.interval = 0.1 |
| 52 | + |
| 53 | + assert monitor.is_healthy() is True |
| 54 | + monitor.run() |
| 55 | + assert monitor.is_healthy() is False |
| 56 | + assert monitor.downsample_factor == 2 |
| 57 | + monitor.run() |
| 58 | + assert monitor.downsample_factor == 4 |
| 59 | + |
| 60 | + |
| 61 | +def test_transaction_uses_downsampled_rate( |
| 62 | + sentry_init, capture_client_reports, monkeypatch |
| 63 | +): |
| 64 | + sentry_init( |
| 65 | + traces_sample_rate=1.0, |
| 66 | + transport=UnhealthyTestTransport(), |
| 67 | + _experiments={"enable_backpressure_handling": True}, |
| 68 | + ) |
| 69 | + |
| 70 | + reports = capture_client_reports() |
| 71 | + |
| 72 | + monitor = Hub.current.client.monitor |
| 73 | + monitor.interval = 0.1 |
| 74 | + |
| 75 | + # make sure rng doesn't sample |
| 76 | + monkeypatch.setattr(random, "random", lambda: 0.9) |
| 77 | + |
| 78 | + assert monitor.is_healthy() is True |
| 79 | + monitor.run() |
| 80 | + assert monitor.is_healthy() is False |
| 81 | + assert monitor.downsample_factor == 2 |
| 82 | + |
| 83 | + with start_transaction(name="foobar") as transaction: |
| 84 | + assert transaction.sampled is False |
| 85 | + assert transaction.sample_rate == 0.5 |
| 86 | + |
| 87 | + assert reports == [("backpressure", "transaction")] |
0 commit comments