9
|-- 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
2
  • 1
    Have you got the solution for this ? Commented Feb 10, 2017 at 13:20
  • @HaykDavtyan Nope. You can upvote the question if you want to increase visibility ;) Commented Feb 10, 2017 at 14:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for the feedback, I was using a string. I edited the question!
Can you provide an example that actually runs and hits the error? I used the requests package as other_function and my code ran fine
github.com/vthorey/example_mock you can run python manage.py test to get the error
@v.thorey i'm kinda stuck in a similar situation. I dont have anything inside my init.py file. Does adding -> "from . import function as function_module" fix the issue ? or is there an alternate work around ?
1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.