I use Pytest and I want to test a class which has a dynamic attribute set by a function
Here is an example
file_1.py
def fn():
return 'foo'
class Cls(object):
cls_attr = fn()
test_file_1.py
import file_1
def test_cl1(monkeypatch):
monkeypatch.setattr('file_1.fn', lambda: 'bar')
assert file_1.fn() == 'bar'
cls = file_1.Cls()
assert cls.cls_attr == 'bar' # <-- fail here
I think that python "compile"s the class before, then monkeypatch is run after.
Is there a way to "reload" the class with the monkeypatched function?