The problem here is that a()
is using an unpatched version of random.choice
.
Compare functions a
and b
:
import random
from random import choice
def a():
return choice([1, 2, 3])
def b():
return random.choice([1, 2, 3])
def choice1000(values):
return 1000
import unittest.mock as mock
with mock.patch('random.choice', choice1000):
print('a', a())
print('b', b())
It prints e.g.:
a 3
b 1000
Why?
This line is the problem:
from random import choice
It imported random
and than stored random.choice
into a new variable named choice
.
Later, mock.patch
patched the original random.choice
, but not the local choice
.
Can I patch the local one? Yes:
with mock.patch('__main__.choice', choice1000):
print('a', a())
print('b', b())
Now it prints e.g.
a 1000
b 1
(I used '__main__'
because I put this code into the top-level file - it may be something else in your case)
So what to do?
Either patch everything, or take a different approach. For example, patch a()
instead of choice()
.
Alternative Solution
In this case, where you want to test behaviour of random
functions, it may be better to use a seed
def a():
return random.choice([1, 2, 3, 1000])
def test1(self):
random.seed(0)
self.assertEqual(a(), 1000)
You can't know beforehand what random values will be generated for a certain seed, but you can be sure that they will always be the same. Which is exactly what you need in tests.
In the last example above, I tested a()
after random.seed(0)
once and it returned 1000, so I can be sure it will do so every time:
>>> import random
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
>>> random.seed(0)
>>> print (random.choice([1, 2, 3, 1000]))
1000
mockobj
is just a class that I created, I have added it to the code so you can just run it to reproduce the problem.