我正在尝试使用 pytest
测试一些代码,并且需要更改某个模块中的函数。我的一个导入也导入了该函数,但是当我使用 monkeypatch
更改方法时,此操作失败。这是我所拥有的:
util.py
def foo():
raise ConnectionError # simulate an error
return 'bar'
something.py
from proj import util
need_this = util.foo()
print(need_this)
test_this.py
import pytest
@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')
import proj.something
这会引发ConnectionError
。如果我改变
test_this.py
import pytest
@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')
def test_test():
import proj.something
然后它会导入,monkeypatch
按预期工作。我读过this并尝试从中对我的测试进行建模,但是除非我在测试内部导入,否则这是行不通的。如果只是测试文件中的正常导入,为什么 Monkeypatch 不执行任何操作?
最佳答案
这是因为 fixture 应用于测试函数而不是整个代码。 autouse=True
属性只是说它应该在每个测试中使用
关于python - Monkeypatching 不进行类导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992496/