gpt4 book ai didi

python - 如何在pytest中monkeypatch动态类属性

转载 作者:行者123 更新时间:2023-12-01 04:49:36 26 4
gpt4 key购买 nike

我使用 Pytest,我想测试一个具有由函数设置的动态属性的类

这是一个例子

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

我认为 python 在之前“编译”了该类,然后运行 ​​Monkeypatch。

有没有办法用monkeypatched函数“重新加载”类?

最佳答案

我不这么认为...但为什么不对 Cls.cls_attr 进行 Monkeypatch 呢?

预计到达时间:也许您想使用 mock 来代替 Monkeypatch。 。有一个pytest-mock也可能对它有用的插件。

关于python - 如何在pytest中monkeypatch动态类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28741384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com