1

I think this should have an easy answer and I'm relatively new to Python, so be gentle.

If I have this function:

def random_fruit():
    fruits = ['apple','banana','coconut']
    return "I like " + random.choice(fruits)

I want to create a test that modifies the fruits list. But I'm can't figure out how to do that. So I want to do something like this, which obviously does not work.

class TestFruit(unittest.TestCase):
    @mock.patch('fruits')
    def test_random_fruit(self, fruits_list):
       fruits_list = ['kiwi']
       self.assertEqual(random_fruit(), u"I like kiwi")

Any help would be appreciated. Thanks

Andrew Keym
  • 225
  • 1
  • 8
  • What is the purpose of this test? I mean, the actual test you are running - I hope its not this – Burhan Khalid Jun 10 '14 at 10:48
  • The purpose was that I was trying to not get a random choice of items. I just wanted to get one back. @jonrsharpe gave a good answer to solve that. – Andrew Keym Jun 10 '14 at 11:14

1 Answers1

4

One way to test the function would be to seed the random module, rather than try to modify the list, so you get the same "random" result every time:

>>> for _ in range(5):
    random.seed(0)
    random_fruit()


'I like coconut'
'I like coconut'
'I like coconut'
'I like coconut'
'I like coconut'

Alternatively, make the list an argument (note use of None for a mutable default argument - see this question):

def random_fruit(fruits=None):
    if fruits is None:
        fruits = ['apple','banana','coconut']
    return "I like " + random.choice(fruits)

Which would run like:

>>> random_fruit()
'I like coconut'
>>> random_fruit(['kiwi'])
'I like kiwi'

Note that there is no point having an argument to test_random_fruit if you immediately overwrite it:

def test_random_fruit(self, fruits_list):
                          # ^ pass argument
    fruits_list = ['kiwi']
              # ^ overwrite it
    ...
Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437