Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions hypothesis/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
RELEASE_TYPE: patch

This patch fixes a bug where :func:`~hypothesis.strategies.decimals` with the
``places`` argument could generate values outside the ``min_value`` and
``max_value`` bounds, when those bounds had more fractional digits than
``places`` (:issue:`4651`).
7 changes: 5 additions & 2 deletions hypothesis/src/hypothesis/strategies/_internal/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1840,10 +1840,13 @@ def int_to_decimal(val):

factor = Decimal(10) ** -places
min_num, max_num = None, None
# Work out the integer bounds exactly: limited-precision division can
# round when the bounds have more than `places` fractional digits,
# which would make ceil/floor over- or undershoot the true bound.
if min_value is not None:
min_num = ceil(ctx(min_value).divide(min_value, factor))
min_num = ceil(Fraction(min_value) / Fraction(factor))
if max_value is not None:
max_num = floor(ctx(max_value).divide(max_value, factor))
max_num = floor(Fraction(max_value) / Fraction(factor))
if min_num is not None and max_num is not None and min_num > max_num:
raise InvalidArgument(
f"There are no decimals with {places} places between "
Expand Down
23 changes: 20 additions & 3 deletions hypothesis/tests/cover/test_numerics.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ def test_fuzz_fractions_bounds(data):
@given(data())
def test_fuzz_decimals_bounds(data):
places = data.draw(none() | integers(0, 20), label="places")
finite_decs = (
decimals(allow_nan=False, allow_infinity=False, places=places) | none()
)
# Note that the bounds are *not* restricted to `places` digits, so they may
# have more fractional digits than the values we generate (see issue #4651).
finite_decs = decimals(allow_nan=False, allow_infinity=False) | none()
low, high = data.draw(tuples(finite_decs, finite_decs), label="low, high")
if low is not None and high is not None and low > high:
low, high = high, low
Expand Down Expand Up @@ -160,6 +160,23 @@ def test_issue_725_regression(x):
pass


@given(
decimals(
min_value=decimal.Decimal(f"0.{'0' * 63}1"),
max_value=decimal.Decimal(f"{'9' * 64}.{'9' * 64}"),
places=2,
)
)
def test_issue_4651_regression(x):
# Bounds with more fractional digits than `places` must not push the
# integer bounds out of range via rounding in the conversion.
assert (
decimal.Decimal(f"0.{'0' * 63}1")
<= x
<= decimal.Decimal(f"{'9' * 64}.{'9' * 64}")
)


@given(decimals(min_value="0.1", max_value="0.3"))
def test_issue_739_regression(x):
pass
Expand Down
Loading