@@ -75,11 +75,68 @@ def test_decimal_context(sentry_init, capture_events):
7575 with mock .patch (
7676 "sentry_sdk.tracing_utils.Random.uniform" , return_value = 0.123456789
7777 ):
78- with sentry_sdk .start_transaction () as transaction :
79- assert (
80- transaction .get_baggage ().sentry_items ["sample_rand" ] == "0.123456"
81- )
78+ with sentry_sdk .start_span () as root_span :
79+ assert root_span .get_baggage ().sentry_items ["sample_rand" ] == "0.123456"
8280 finally :
8381 decimal .getcontext ().prec = old_prec
8482
8583 assert len (events ) == 1
84+
85+
86+ @pytest .mark .parametrize (
87+ "incoming_sample_rand,expected_sample_rand" ,
88+ (
89+ ("0.0100015" , "0.010001" ),
90+ ("0.1" , "0.100000" ),
91+ ),
92+ )
93+ def test_sample_rand_precision (
94+ sentry_init , capture_events , incoming_sample_rand , expected_sample_rand
95+ ):
96+ """
97+ Test that incoming sample_rand is correctly interpreted and optionally rounded.
98+
99+ We shouldn't be getting arbitrary precision sample_rand in incoming headers,
100+ but if we do for some reason, check that we have this covered and we round
101+ it correctly.
102+ """
103+ sentry_init (traces_sample_rate = 1.0 )
104+ events = capture_events ()
105+
106+ baggage = f"sentry-sample_rand={ incoming_sample_rand } ,sentry-trace_id=771a43a4192642f0b136d5159a501700" # noqa: E231
107+ sentry_trace = "771a43a4192642f0b136d5159a501700-1234567890abcdef"
108+
109+ with sentry_sdk .continue_trace (
110+ {BAGGAGE_HEADER_NAME : baggage , SENTRY_TRACE_HEADER_NAME : sentry_trace }
111+ ):
112+ with sentry_sdk .start_span () as root_span :
113+ assert (
114+ root_span .get_baggage ().sentry_items ["sample_rand" ]
115+ == expected_sample_rand
116+ )
117+
118+ assert len (events ) == 1
119+
120+
121+ @pytest .mark .parametrize ("incoming" , ((0.0 , "true" ), (1.0 , "false" )))
122+ def test_invalid_sampled_and_sample_rate (sentry_init , incoming ):
123+ """
124+ Test that we don't error out in case we can't generate a sample_rand that
125+ would respect the incoming sampled and sample_rate.
126+ """
127+ sentry_init (traces_sample_rate = 1.0 )
128+
129+ sample_rate , sampled = incoming
130+
131+ baggage = f"sentry-sample_rate={ sample_rate } ,sentry-sampled={ sampled } ,sentry-trace_id=771a43a4192642f0b136d5159a501700" # noqa: E231
132+ sentry_trace = f"771a43a4192642f0b136d5159a501700-1234567890abcdef-{ 1 if sampled == 'true' else 0 } "
133+
134+ with sentry_sdk .continue_trace (
135+ {BAGGAGE_HEADER_NAME : baggage , SENTRY_TRACE_HEADER_NAME : sentry_trace }
136+ ):
137+ with sentry_sdk .start_span ():
138+ pass
139+
140+ # The behavior here is undefined since we got a broken incoming trace,
141+ # so as long as the SDK doesn't produce an error we consider this
142+ # testcase a success.
0 commit comments