|
2 | 2 | import weakref |
3 | 3 | import gc |
4 | 4 | import pytest |
| 5 | +import random |
5 | 6 |
|
6 | 7 | from sentry_sdk import ( |
7 | 8 | capture_message, |
@@ -142,6 +143,61 @@ def test_continue_from_headers(sentry_init, capture_envelopes, sampled, sample_r |
142 | 143 | assert message_payload["message"] == "hello" |
143 | 144 |
|
144 | 145 |
|
| 146 | +@pytest.mark.parametrize("sample_rate", [0.5, 1.0]) |
| 147 | +def test_dynamic_sampling_head_sdk_creates_dsc( |
| 148 | + sentry_init, capture_envelopes, sample_rate, monkeypatch |
| 149 | +): |
| 150 | + sentry_init(traces_sample_rate=sample_rate, release="foo") |
| 151 | + envelopes = capture_envelopes() |
| 152 | + |
| 153 | + # make sure transaction is sampled for both cases |
| 154 | + monkeypatch.setattr(random, "random", lambda: 0.1) |
| 155 | + |
| 156 | + transaction = Transaction.continue_from_headers({}, name="Head SDK tx") |
| 157 | + |
| 158 | + # will create empty mutable baggage |
| 159 | + baggage = transaction._baggage |
| 160 | + assert baggage |
| 161 | + assert baggage.mutable |
| 162 | + assert baggage.sentry_items == {} |
| 163 | + assert baggage.third_party_items == "" |
| 164 | + |
| 165 | + with start_transaction(transaction): |
| 166 | + with start_span(op="foo", description="foodesc"): |
| 167 | + pass |
| 168 | + |
| 169 | + # finish will create a new baggage entry |
| 170 | + baggage = transaction._baggage |
| 171 | + trace_id = transaction.trace_id |
| 172 | + |
| 173 | + assert baggage |
| 174 | + assert not baggage.mutable |
| 175 | + assert baggage.third_party_items == "" |
| 176 | + assert baggage.sentry_items == { |
| 177 | + "environment": "production", |
| 178 | + "release": "foo", |
| 179 | + "sample_rate": str(sample_rate), |
| 180 | + "transaction": "Head SDK tx", |
| 181 | + "trace_id": trace_id, |
| 182 | + } |
| 183 | + |
| 184 | + expected_baggage = ( |
| 185 | + "sentry-environment=production,sentry-release=foo,sentry-sample_rate=%s,sentry-transaction=Head%%20SDK%%20tx,sentry-trace_id=%s" |
| 186 | + % (sample_rate, trace_id) |
| 187 | + ) |
| 188 | + assert sorted(baggage.serialize().split(",")) == sorted(expected_baggage.split(",")) |
| 189 | + |
| 190 | + (envelope,) = envelopes |
| 191 | + assert envelope.headers["trace"] == baggage.dynamic_sampling_context() |
| 192 | + assert envelope.headers["trace"] == { |
| 193 | + "environment": "production", |
| 194 | + "release": "foo", |
| 195 | + "sample_rate": str(sample_rate), |
| 196 | + "transaction": "Head SDK tx", |
| 197 | + "trace_id": trace_id, |
| 198 | + } |
| 199 | + |
| 200 | + |
145 | 201 | @pytest.mark.parametrize( |
146 | 202 | "args,expected_refcount", |
147 | 203 | [({"traces_sample_rate": 1.0}, 100), ({"traces_sample_rate": 0.0}, 0)], |
|
0 commit comments