[英]How to monkeypatch dynamic class attribute in pytest
I use Pytest and I want to test a class which has a dynamic attribute set by a function 我使用Pytest,我想测试一个具有由函数设置的动态属性的类
Here is an example 这是一个例子
file_1.py file_1.py
def fn():
return 'foo'
class Cls(object):
cls_attr = fn()
test_file_1.py 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. 我认为python是先编译类,然后再运行Monkeypatch。
Is there a way to "reload" the class with the monkeypatched function? 有没有办法用Monkeypatched函数“重新加载”类?
I don't think so... but why not monkeypatch the Cls.cls_attr
instead? 我不这么认为...但是为什么不选择对
Cls.cls_attr
呢?
ETA: Perhaps what you want to use instead of monkeypatch is mock . 预计到达时间:也许您要使用替代monkeypatch的方法是模拟的 。 There is a pytest-mock plugin that may be useful with it too.
有一个pytest-mock插件也可能有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.