【发布时间】:2022-01-02 02:12:44
【问题描述】:
我有一个模块设置大致如下:
# foo.py
def generate_things_based_on_other_things():
# some nasty things here
# bar.py
from foo import generate_things_based_on_other_things as generate
def coo():
generate()
# conftest.py
import pytest
@pytest.fixture(autouse=True)
def patch_generate(monkeypatch):
def mock_generate():
print("hello!")
monkeypatch.setattr("app.bar.generate", mock_generate)
# test_bar.py
from bar import coo
def test_coo():
coo()
根据this answer,我确保对函数的实际导入实例进行猴子补丁。任何其他路径都会引发 "does not exist on module" 错误。
然而,当我运行测试时,我遇到了一个错误,因为原始函数 generate 正在被调用,尽管它已被猴子补丁。
我不明白为什么这个补丁也不会像我期望的那样坚持下去。
我希望这个测试能打印出“hello!”。
【问题讨论】:
标签: python pytest monkeypatching