在 conftest 中(在 autouse fixture 中):
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")
然后我得到“Winning”。
Why is this behaving differently, and how can I make the monkeypatch work for both scenarios?
最佳答案
一般来说,问题似乎与导入在 python 中的工作方式有关。我不确定是否有好的解决方案。
到目前为止,我发现的最佳解决方法如下:
monkeypatch.setattr('collector.util.download_data.__code__', replacement_function.__code__)
这适用于两种导入类型。 一个限制是这不适用于闭包。
此功能可以通过以下方式添加到框架中:
from _pytest.monkeypatch import monkeypatch
monkeypatch.setcode = lambda self, func_str, replacement_func: \
monkeypatch.setattr(self, func_str + ".__code__", replacement_func.__code__)
引用:https://mail.python.org/pipermail/pytest-dev/2013-October/002386.html
关于python - py.test 的 monkeypatch.setattr(...) 在某些情况下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403380/