This is a very stripped back version of what I want to do. It may not seem totally useful, but that is because I have stripped away all elements not pertinent to this question;
dummy.py
from another_mod import some_val
class Dummy:
A_DICT = {
'a': some_val*5,
'b': some_val*10,
}
def some_func(self, x):
return x*Dummy.A_DICT['a']
For testing purposes, I want to modify the value of the import some_val
using mocking. Lets say that the unmocked value for some_val
is 20.
test_dummy.py
import pytest
from dummy import Dummy
def test_some_func(mocker):
mocker.patch('dummy.some_val',10)
d = Dummy()
assert d.some_func(5) == 250
However, this fails, as d.some_func(5)
= 500, which is the result if the mock was not applied.
I have some idea this is because the class variable A_DICT
is probably set before the mock is applied. If this is so, is there anyway to do what I am trying to do? I have used mocking before, and am aware of the difficulties that often arise from mocking stuff from the wrong place. However, this is a specific case that I haven't had to deal with before...
If the example seems useless and contrived, it is, but I was trying to reduce an example just down to this very specific issue.