|
| 1 | +import pytest |
| 2 | + |
| 3 | +import sentry_sdk |
| 4 | +from sentry_sdk.tracing_utils import Baggage |
| 5 | + |
| 6 | +TEST_TRACE_ID_SAMPLE_RANDS = { |
| 7 | + "00000000000000000000000000000000": 0.8766381713144122, |
| 8 | + "01234567012345670123456701234567": 0.6451742521664413, |
| 9 | + "0123456789abcdef0123456789abcdef": 0.9338861957669223, |
| 10 | +} |
| 11 | +""" |
| 12 | +A dictionary of some trace IDs used in the tests, and their precomputed sample_rand values. |
| 13 | +
|
| 14 | +sample_rand values are pseudo-random numbers, deterministically generated from the trace ID. |
| 15 | +""" |
| 16 | + |
| 17 | + |
| 18 | +@pytest.mark.parametrize( |
| 19 | + ("trace_id", "expected_sample_rand"), |
| 20 | + TEST_TRACE_ID_SAMPLE_RANDS.items(), |
| 21 | +) |
| 22 | +# test 21 linearly spaced sample_rate values from 0.0 to 1.0, inclusive |
| 23 | +@pytest.mark.parametrize("sample_rate", (i / 20 for i in range(21))) |
| 24 | +def test_deterministic_sampled( |
| 25 | + sentry_init, capture_events, sample_rate, trace_id, expected_sample_rand |
| 26 | +): |
| 27 | + """ |
| 28 | + Test that the sample_rand value is deterministic based on the trace ID, and |
| 29 | + that it is used to determine the sampling decision. Also, ensure that the |
| 30 | + transaction's baggage contains the sample_rand value. |
| 31 | + """ |
| 32 | + sentry_init(traces_sample_rate=sample_rate) |
| 33 | + events = capture_events() |
| 34 | + |
| 35 | + with sentry_sdk.start_transaction(trace_id=trace_id) as transaction: |
| 36 | + assert transaction.get_baggage().sentry_items["sample_rand"] == str( |
| 37 | + expected_sample_rand |
| 38 | + ) |
| 39 | + |
| 40 | + # Transaction event captured if sample_rand < sample_rate, indicating that |
| 41 | + # sample_rand is used to make the sampling decision. |
| 42 | + assert len(events) == int(expected_sample_rand < sample_rate) |
| 43 | + |
| 44 | + |
| 45 | +@pytest.mark.parametrize("sample_rand", (0.0, 0.2, 0.4, 0.6, 0.8)) |
| 46 | +@pytest.mark.parametrize("sample_rate", (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)) |
| 47 | +def test_transaction_uses_incoming_sample_rand( |
| 48 | + sentry_init, capture_events, sample_rate, sample_rand |
| 49 | +): |
| 50 | + """ |
| 51 | + Test that the transaction uses the sample_rand value from the incoming baggage. |
| 52 | + """ |
| 53 | + baggage = Baggage(sentry_items={"sample_rand": str(sample_rand)}) |
| 54 | + |
| 55 | + sentry_init(traces_sample_rate=sample_rate) |
| 56 | + events = capture_events() |
| 57 | + |
| 58 | + with sentry_sdk.start_transaction(baggage=baggage) as transaction: |
| 59 | + assert transaction.get_baggage().sentry_items["sample_rand"] == str(sample_rand) |
| 60 | + |
| 61 | + # Transaction event captured if sample_rand < sample_rate, indicating that |
| 62 | + # sample_rand is used to make the sampling decision. |
| 63 | + assert len(events) == int(sample_rand < sample_rate) |
0 commit comments