Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 827
v.thorey Avatar asked Nov 09 '16 14:11

v.thorey


1 Answers

You could make the module available under a different name in __init__.py:

from . import function as function_module
from .function import function

Then you can do the following in test.py:

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

class Test(TestCase):

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

I do not think this is a particularly elegant solution - the code is not very clear to a casual reader.

like image 74
Henry Heath Avatar answered Nov 14 '22 22:11

Henry Heath