Skip to content

Commit

Permalink
Merge pull request #3766 from HypothesisWorks/DRMacIver/empty-random-…
Browse files Browse the repository at this point in the history
…sample

Fix #3765 (Random.sample errors with empty sequences)
  • Loading branch information
Zac-HD authored Oct 10, 2023
2 parents 5278b7c + 351ea98 commit 8a379f3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
8 changes: 8 additions & 0 deletions hypothesis-python/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
RELEASE_TYPE: patch

When :func:`~hypothesis.strategies.randoms` was called with `use_true_randoms=False`,
calling `sample` on it with an empty sequence and 0 elements would result in an error,
when it should have returned an empty sequence to agree with the normal behaviour of
`random.Random`. This fixes that discrepancy.

Fixes :issue:`3765``
17 changes: 10 additions & 7 deletions hypothesis-python/src/hypothesis/strategies/_internal/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,14 +296,17 @@ def _hypothesis_do_random(self, method, kwargs):
f"Sample size {k} not in expected range 0 <= k <= {len(seq)}"
)

result = self.__data.draw(
lists(
sampled_from(range(len(seq))),
min_size=k,
max_size=k,
unique=True,
if k == 0:
result = []
else:
result = self.__data.draw(
lists(
sampled_from(range(len(seq))),
min_size=k,
max_size=k,
unique=True,
)
)
)

elif method == "getrandbits":
result = self.__data.draw_bits(kwargs["n"])
Expand Down
5 changes: 5 additions & 0 deletions hypothesis-python/tests/cover/test_randoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,3 +381,8 @@ def test_can_sample_from_large_subset(rnd):
ys = rnd.sample(xs, n)
assert set(ys).issubset(set(xs))
assert len(ys) == len(set(ys)) == n


@given(st.randoms(use_true_random=False))
def test_can_draw_empty_from_empty_sequence(rnd):
assert rnd.sample([], 0) == []

0 comments on commit 8a379f3

Please sign in to comment.