Skip to content

Commit

Permalink
fix: critical bug with return_less_if_necessary
Browse files Browse the repository at this point in the history
Setting return_less_if_necessary to True
should not change the output if there are
enough words to generate. However, when this
was the case, the function would previously
would return ALL words that matched the
filter, ignoring the `amount` param.
  • Loading branch information
mrmaxguns committed Apr 10, 2024
1 parent d22b07b commit 7741fd2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
6 changes: 6 additions & 0 deletions tests/test_random_word.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,12 @@ def test_random_words_not_enough_with_return_less_if_necessary(self):
]
)

def test_random_words_enough_with_return_less_if_necessary(self):
"""Test to see if setting return_less_if_necessary doesn't do anything if there are enough words."""
data_1 = self.rw.random_words(5, starts_with="mo", return_less_if_necessary=True)
data_2 = self.rw.random_words(5, starts_with="mo", return_less_if_necessary=False)
assert len(data_1) == len(data_2) == 5

def test_word(self):
"""Test the word method"""
data = self.rw.word()
Expand Down
17 changes: 9 additions & 8 deletions wonderwords/random_word.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,14 +391,15 @@ def random_words(
exclude_with_spaces=exclude_with_spaces,
)

if not return_less_if_necessary and len(choose_from) < amount:
raise NoWordsToChoseFrom(
"There aren't enough words to choose from. Cannot generate "
f"{str(amount)} word(s)"
)
elif return_less_if_necessary:
random.shuffle(choose_from)
return choose_from
if len(choose_from) < amount:
if return_less_if_necessary:
random.shuffle(choose_from)
return choose_from
else:
raise NoWordsToChoseFrom(
"There aren't enough words to choose from. Cannot generate "
f"{str(amount)} word(s)"
)

words = []
for _ in range(amount):
Expand Down

0 comments on commit 7741fd2

Please sign in to comment.