在 conftest (在autouse灯具中):
monkeypatch.setattr('collector.util.download_data', lambda url:"Winning" )
在 collector / util.py :
中def download_data(url):
assert False
在 the_caller.py :
中from collector.util import download_data
def some_function():
download_data("blah")
当我调用some_function()时,我得到断言。但是,如果我将 the_caller.py 更改为:
import collector
def some_function():
collector.util.download_data("blah")
然后我得到了#34; Winning"。
为什么这会有不同的表现,我如何制作monkeypatch 适用于两种情况?
答案 0 :(得分:6)
一般来说,问题似乎与导入如何在python中工作有关。我不确定是否有好的解决方案。
到目前为止,我发现的最佳解决方法如下:
monkeypatch.setattr('collector.util.download_data.func_code', replacement_function.func_code )
这适用于两种导入类型。 一个限制是,这不适用于闭包。
可以通过以下方式将此功能添加到框架中:
from _pytest.monkeypatch import monkeypatch
monkeypatch.setcode = lambda self, func_str, replacement_func : \
monkeypatch.setattr( self, func_str + ".func_code", replacement_func.func_code )
参考:https://mail.python.org/pipermail/pytest-dev/2013-October/002386.html