Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest-mock - Mock a function from a module

Tags:

python

pytest

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 my engine.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 to engine.py?

like image 973
An Nguyen Avatar asked Dec 17 '25 14:12

An Nguyen


1 Answers

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.

like image 180
An Nguyen Avatar answered Dec 19 '25 03:12

An Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!