pythondjangomockingpatch

patch function with same name as module python django mock


|-- my_module
|   |-- __init__.py
|   |-- function.py
`-- test.py

in function.py:

import other_function

def function():
    doStuff()
    other_function()
    return

in __init__.py

from .function import function

in my test.py

from django.test import TestCase
from mock import patch
from my_module import function

class Test(TestCase):

    @patch('my_module.function.other_function')
    def function_test(self, mock_other_function):
         function()

When I run this I got a AttributeError:

<@task: my_module.function.function of project:0x7fed6b4fc198> does not have the attribute 'other_function'

Which means that I am trying to patch the function "function" instead of the module "function". I don't know how to make it understand that I want to patch the module.

I would also like to avoid renaming my module or function.

Any ideas?

[Edit] You can find an example at https://github.com/vthorey/example_mock run

python manage.py test

Solution

  • 7 years later I faced the same issue and found a thread that proposes a solution here:

    How to mock a function called in a function inside a module with the same name?