Back To Blog Posts
Mocking Module Level Functions In Python Unit Tests
If you write a lot of unit tests in python, especially on complex pieces of software, no doubt you have come across python’s mock module. As of writing this, I just noticed that it has now been pulled into the python standard library unittest module
It is easy to use mock to mock class-level instance methods:
class ClassA(object):
def hello(self):
return "Hello"
And now in some unit test
class Test(TestCase):
@mock.patch('classA.hello', mock.Mock(return_value="world"))
def test_class(self):
cls = ClassA()
cls.hello()
That was easy enough, but mocking module level functions is actually not as easy. Lets say I have some module called name_utis.py
that’s sole job is to concatenate first name and last name:
// name_utils.py
def make_whole_name(first, last):
return "{} {}"format(first, last)
And lets say this function is called by some other class:
class ClassB(object):
def __init__(self, first, last):
self.first = first
self.last = last
def get_name(self):
return make_whole_name(self.first, self.last)
My goal is to mock make_whole_name
, not get_name
. This can be done by using the following
class Test(TestCase):
@mock.patch('path.to.make_whole_name.make_whole_name')
def test_class(self, first_name, last_name):
dhs.first_name = 'joseph'
dhs.last_name = 'misiti'
cls = ClassB('hello','world')
self.assertEquals(cls.get_name(), 'joseph misiti')