pytest-mock - Mock a function from a module
12,041
I have successfully achieved it by changing mocker.patch('main.utils.string.get_random_string', return_value='123456')
to mocker.patch('engine.get_random_string', return_value='123456')
.
Details can be found here.
Related videos on Youtube
Author by
An Nguyen
Updated on October 23, 2022Comments
-
An Nguyen about 1 year
I have an util in my module
engine.py
, which is imported from another file:from main.utils.string import get_random_string def generate_random_string(): return get_random_string()
In my test file:
def test_generate_random_string(mocker): mocker.patch('main.utils.string.get_random_string', return_value='123456')
However, it's still trying to use the real implementation of
string.get_random_string
instead of the mock that I've created, unless I change myengine.py
to:from main.utils import string def generate_random_string(): return string.get_random_string()
How can I achieve the mocking part without importing the whole
string
module toengine.py
?-
hoefling over 5 yearsYou should mock the function where you use it, not where it is declared. Try
mocker.patch('engine.get_random_string', return_value='123456')
instead. See Where to patch for more details.
-