I am new to mock and unit testing in python. How can I mock the local variable of a function? For example, how do I change age
to 10 instead of 27 while testing?
# data_source.py
def get_name():
age = 27 #real value
return "Alice"
# person.py
from data_source import get_name
class Person(object):
def name(self):
return get_name()
# The unit test
from mock import patch
from person import Person
@patch('person.age')
def test_name(mock_age):
mock_age = 10 # mock value
person = Person()
name = person.name()
assert age == 10
As far as I know, mock
cannot mock a local variable. It can only mock non-local object.
Trying to mock a local variable sounds dubious. Maybe you should try another way. Try making age
a global variable or a class variable. Then you can use mock
to mock the global variable or the class variable.
Such as:
# source file
G_AGE = 27
def get_name():
return "Alice"
# unit test file
...
@patch('XXX.G_AGE')
def test_name(mock_age):
mock_age = 10
....
Just pay attention to patch
usage: mock
may not work as expected if it is not used properly. Refer to Where to patch for further explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With