Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest-mock not patching imported function in class module [duplicate]

The pytest-mock patching does not work as expected. My code:

utils.py:

def my_func():
    return 42

classes.py:

from utils import my_func

class MyClass:
    def class_method(self):
        return my_func()

test_classes.py:

import pytest
from classes import MyClass

def test_myclass(mocker):
    mocker.patch("utils.my_func", return_value=21)
    assert MyClass().class_method() == 21

This fails, the return is 42 instead of 21.

like image 813
felice Avatar asked Sep 01 '26 02:09

felice


1 Answers

The solution is to change the patching within the test. Instead of

mocker.patch("utils.my_func", return_value=21)

write

mocker.patch("classes.my_func", return_value=21)

because of this line in classes.py: from .utils import my_func.

like image 164
felice Avatar answered Sep 04 '26 00:09

felice



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!