File tree 2 files changed +31
-4
lines changed
2 files changed +31
-4
lines changed Original file line number Diff line number Diff line change 6
6
import uuid
7
7
from collections .abc import Mapping
8
8
from datetime import datetime , timedelta , timezone
9
+ from decimal import ROUND_DOWN , Context , Decimal
9
10
from functools import wraps
10
11
from random import Random
11
12
from urllib .parse import quote , unquote
@@ -699,8 +700,6 @@ def _generate_sample_rand(
699
700
700
701
The pseudorandom number generator is seeded with the trace ID.
701
702
"""
702
- import decimal
703
-
704
703
lower , upper = interval
705
704
if not lower < upper : # using `if lower >= upper` would handle NaNs incorrectly
706
705
raise ValueError ("Invalid interval: lower must be less than upper" )
@@ -711,8 +710,10 @@ def _generate_sample_rand(
711
710
sample_rand = rng .uniform (lower , upper )
712
711
713
712
# Round down to exactly six decimal-digit precision.
714
- return decimal .Decimal (sample_rand ).quantize (
715
- decimal .Decimal ("0.000001" ), rounding = decimal .ROUND_DOWN
713
+ # Setting the context is needed to avoid an InvalidOperation exception
714
+ # in case the user has changed the default precision.
715
+ return Decimal (sample_rand ).quantize (
716
+ Decimal ("0.000001" ), rounding = ROUND_DOWN , context = Context (prec = 6 )
716
717
)
717
718
718
719
Original file line number Diff line number Diff line change
1
+ import decimal
1
2
from unittest import mock
2
3
3
4
import pytest
@@ -53,3 +54,28 @@ def test_transaction_uses_incoming_sample_rand(
53
54
# Transaction event captured if sample_rand < sample_rate, indicating that
54
55
# sample_rand is used to make the sampling decision.
55
56
assert len (events ) == int (sample_rand < sample_rate )
57
+
58
+
59
+ def test_decimal_context (sentry_init , capture_events ):
60
+ """
61
+ Ensure that having a decimal context with a precision below 6
62
+ does not cause an InvalidOperation exception.
63
+ """
64
+ sentry_init (traces_sample_rate = 1.0 )
65
+ events = capture_events ()
66
+
67
+ old_prec = decimal .getcontext ().prec
68
+ decimal .getcontext ().prec = 2
69
+
70
+ try :
71
+ with mock .patch (
72
+ "sentry_sdk.tracing_utils.Random.uniform" , return_value = 0.123456789
73
+ ):
74
+ with sentry_sdk .start_transaction () as transaction :
75
+ assert (
76
+ transaction .get_baggage ().sentry_items ["sample_rand" ] == "0.123456"
77
+ )
78
+ finally :
79
+ decimal .getcontext ().prec = old_prec
80
+
81
+ assert len (events ) == 1
You can’t perform that action at this time.
0 commit comments