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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With