Skip to content

Commit

Permalink
Allow for random sampling from empty lists
Browse files Browse the repository at this point in the history
  • Loading branch information
DRMacIver committed Oct 10, 2023
1 parent 5278b7c commit b8e011a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
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 b8e011a

Please sign in to comment.