python - Monkeypatching 不进行类导入

标签 python pytest monkeypatching

我正在尝试使用 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/

相关文章:

python - 在 ipython 图形窗口中放大后,Matplotlib 轴刻度格式发生变化

python - pytest 需要 Python '>=3.5' 但运行的 Python 是 2.7.10

python - 无法在 Python 单元测试中猴子修补模块变量

python - 如果在 Ruby 和 Python 中都允许猴子修补,为什么在 Ruby 中争议更大?

python - 密码破解程序

python - 如何在 Python 中抑制 SyntaxWarning?

python - 根据 tensorflow 中的两列对张量进行排序

python - py.test Remote 有问题

python - pytest django 从 yaml 文件加载数据库数据

java - 如何向标准java类添加方法