From 7741fd2e95011253db90597a3b9487e2f79b41aa Mon Sep 17 00:00:00 2001 From: Maxim Rebguns Date: Wed, 10 Apr 2024 18:25:58 -0500 Subject: [PATCH] fix: critical bug with return_less_if_necessary 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. --- tests/test_random_word.py | 6 ++++++ wonderwords/random_word.py | 17 +++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/tests/test_random_word.py b/tests/test_random_word.py index 6b8d769..29d49bb 100644 --- a/tests/test_random_word.py +++ b/tests/test_random_word.py @@ -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() diff --git a/wonderwords/random_word.py b/wonderwords/random_word.py index 133e969..8fcfab0 100644 --- a/wonderwords/random_word.py +++ b/wonderwords/random_word.py @@ -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):