'python mocked function not called
I'm testing python code (A django 3.0.5 project although I don't think it's relevant), but I can't get the functions of my mocked objects to be called. Here is my code:
**myproject.mypackage.myhelpers**
def get_dict():
return dict()
**myproject.mypackage.mythings**
from .myhelpers import get_dict
def use_dict():
the_dict = get_dict()
pass
return
**myproject.tests.test_mythings**
from ..mypackage import mythings
import unittest
import unittest.mock as mock
class MyThingsTests(unittest.TestCase):
@mock.patch('myproject.mypackage.myhelpers')
def test_using_dict(self, mock_myhelpers):
test_dict = {
"hi": "foo",
"there": "bar",
"sir": "foobar"
}
mock_myhelpers.get_dict.return_value = test_dict
mythings.use_dict()
mock_myhelpers.get_dict.assert_called_once()
However in the end the test fails with error:
AssertionError: Expected 'get_dict' to have been called once. Called 0 times
Solution 1:[1]
Solution 1
- replace
myproject.mypackage.myhelperswithmyproject.mypackage.mythings
# @mock.patch('myproject.mypackage.myhelpers')
@mock.patch('myproject.mypackage.mythings.get_dict')
def test_using_dict(self, mock_get_dict):
test_dict = {
"hi": "foo",
"there": "bar",
"sir": "foobar"
}
mock_get_dict.return_value = test_dict
Solution 2
- replace
from .myhelpers import get_dictwithimport .myhelpers as helpers
**myproject.mypackage.mythings**
# from .myhelpers import get_dict
import .myhelpers as helpers
def use_dict():
the_dict = helpers.get_dict()
pass
return
Summary
- solution 1 is better since it won't bother you to update the
importstyle in all your.pyfiles
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ZenG |
