Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a local variable of a function in python

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
like image 527
user1559873 Avatar asked Sep 21 '13 09:09

user1559873


1 Answers

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.

like image 102
fishoverflow Avatar answered Nov 08 '22 17:11

fishoverflow