I am trying to mock a function regardless of how it is imported in the code.
I can’t find info on how to do it.
Here is an example, the first assert works as expected but the second fails because path:
import mymodule
from mymodule import test1
def test_mock(mocker):
mocker.patch('mymodule.test1', return_value="mocked")
assert mymodule.test1() == "mocked" # works
assert test1() == "mocked" # fails
5
You have to modified the second test as following:
with patch("__main__.test1", return_value="mocked_2"):
assert test1() == "mocked_2"
In the previous code, the instruction:
with patch("__main__.test1", , return_value="mocked_2"):
is used to mock the name test1
in the namespace of the the test file.
I have saved your production code in the file mymodule.py
where it is defined only the function test1()
:
def test1():
return "real test1 function"
My complete test code is saved in the file test_module.py
, and its content is the following:
import unittest
from unittest.mock import patch
import mymodule
from mymodule import test1
class MyTestCase(unittest.TestCase):
def test_mock(self):
# this is your working test
with patch('mymodule.test1', return_value="mocked"):
print("Test 1")
assert mymodule.test1() == "mocked" # works
# THIS IS YOUR SECOND NOT WORKING TEST CHANGED TO WORK
with patch("__main__.test1", return_value="mocked_2"):
print("Test 2")
assert test1() == "mocked_2"
# ... here I have not used MOCKING
print("Test 3")
assert test1() == "real test1 function"
if __name__ == '__main__':
unittest.main()
Below I shows the output of the execution of the method test_mock()
defined in test_module.py
:
Test 1
Test 2
Test 3
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
In the output you can see the printout Test 1
, Test 2
and Test 3
showing the execution of 3 calls of test1()
(with and without mocking).
NOTE: I have not used pytest
; I have used only the module unittest
.