|
1 | 1 | import json |
2 | 2 | import sys |
3 | 3 | from typing import List, Any, Mapping |
| 4 | +from unittest import mock |
4 | 5 | import pytest |
5 | 6 |
|
6 | 7 | import sentry_sdk |
@@ -337,5 +338,43 @@ def test_metrics_no_sample_rate(sentry_init, capture_envelopes): |
337 | 338 |
|
338 | 339 | assert len(metrics) == 1 |
339 | 340 |
|
340 | | - # Should not have sample_rate attribute when not provided |
341 | 341 | assert "sentry.client_sample_rate" not in metrics[0]["attributes"] |
| 342 | + |
| 343 | + |
| 344 | +@pytest.mark.parametrize("sample_rand", (0.0, 0.25, 0.5, 0.75)) |
| 345 | +@pytest.mark.parametrize("sample_rate", (0.0, 0.25, 0.5, 0.75, 1.0)) |
| 346 | +def test_metrics_sampling_decision( |
| 347 | + sentry_init, capture_envelopes, sample_rate, sample_rand, monkeypatch |
| 348 | +): |
| 349 | + sentry_init(traces_sample_rate=1.0) |
| 350 | + envelopes = capture_envelopes() |
| 351 | + client = sentry_sdk.get_client() |
| 352 | + |
| 353 | + lost_event_calls = [] |
| 354 | + |
| 355 | + def record_lost_event(reason, data_category, quantity): |
| 356 | + lost_event_calls.append((reason, data_category, quantity)) |
| 357 | + |
| 358 | + monkeypatch.setattr(client.transport, "record_lost_event", record_lost_event) |
| 359 | + |
| 360 | + with mock.patch( |
| 361 | + "sentry_sdk.tracing_utils.Random.randrange", |
| 362 | + return_value=int(sample_rand * 1000000), |
| 363 | + ): |
| 364 | + with sentry_sdk.start_transaction() as transaction: |
| 365 | + sentry_sdk.metrics.count("test.counter", 1, sample_rate=sample_rate) |
| 366 | + |
| 367 | + get_client().flush() |
| 368 | + metrics = envelopes_to_metrics(envelopes) |
| 369 | + |
| 370 | + should_be_sampled = sample_rand < sample_rate and sample_rate > 0.0 |
| 371 | + assert len(metrics) == int(should_be_sampled) |
| 372 | + |
| 373 | + if sample_rate <= 0.0: |
| 374 | + assert len(lost_event_calls) == 1 |
| 375 | + assert lost_event_calls[0] == ("invalid_sample_rate", "trace_metric", 1) |
| 376 | + elif not should_be_sampled: |
| 377 | + assert len(lost_event_calls) == 1 |
| 378 | + assert lost_event_calls[0] == ("sample_rate", "trace_metric", 1) |
| 379 | + else: |
| 380 | + assert len(lost_event_calls) == 0 |
0 commit comments