python - py.test 的 monkeypatch.setattr(...) 在某些情况下不起作用

标签 python python-2.7 pytest monkeypatching

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/

相关文章:

python - 为什么我的当前目录没有出现在 Windows 上使用 pytest 的路径中?

python - 将 "unknown format"字符串转换为日期时间对象?

python - 什么是快速算法,可以找到一条最短路径遍历带权无向图的每个节点至少一次?

Python while语句错误

python - 如何在 python 中将对象作为命令行参数传递?

python - 如果测试覆盖率低于 x%,是否有标准方法使 pytest 失败

python - pytest - 获取fixture参数的值

python - 从嵌套字典中递归删除 None 值或 None 键

python - 从 url 获取产品代码,我需要正则表达式吗?

python - 使用 Pandas 组合列