python - How do I patch or modify a list inside of a function when running a unit test? -


i think should have easy answer , i'm relatively new python, gentle.

if have function:

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

i want create test modifies fruits list. i'm can't figure out how that. want this, 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 kiwi") 

any appreciated. thanks

one way test function seed random module, rather try modify list, same "random" result every time:

>>> _ in range(5):     random.seed(0)     random_fruit()   'i coconut' 'i coconut' 'i coconut' 'i coconut' 'i coconut' 

alternatively, make list argument (note use of none mutable default argument - see this question):

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

which run like:

>>> random_fruit() 'i coconut' >>> random_fruit(['kiwi']) 'i kiwi' 

note there no point having argument test_random_fruit if overwrite it:

def test_random_fruit(self, fruits_list):                           # ^ pass argument     fruits_list = ['kiwi']               # ^ overwrite     ... 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -