[Django]-Django mock patch doesn't work as I expect

12👍

The link

http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch

helped me understand better how to go about patching function calls in python.

8👍

Patch only mocks out the object in the location that you have patched it. A quick bit of example code should help explain what is going on.

from mock import Mock, patch
import unittest

from patch_code import anotherfunc, thefunc

print 'Function imported', thefunc

class SomeTest(unittest.TestCase):

    @patch('patch_code.thefunc', Mock())
    def test_method(self):
        anotherfunc()
        print 'Inside test method', thefunc


if __name__ == '__main__':
    unittest.main()

And the code under test is just two functions:

def thefunc():
    pass

def anotherfunc():
    print 'Inside code under test', thefunc

Running that test gives the following output

Function imported <function thefunc at 0xb740e614>
Inside code under test <Mock id='3071597132'>
Inside test method <function thefunc at 0xb740e614>

You can clearly see that the only place that patch has mocked ‘thefunc’ is in the code under test.

If you want to test the function get_redis without causing any side effects then you should mock out account.util.redis.StrictRedis and assert that it was called with the correct arguments.

If you want to test functions that use get_redis then you should mock out get_redis and, import the function that is using get_redis, and call that function in your test.

3👍

Instead of importing get_redis, try import util and call util.get_redis().

Leave a comment