我的任务本来应该很简单,但它却困扰了我一段时间。我在尝试着patch
导入到当前模块中的对象。
根据答案Python 中的模拟修补 from/import 语句 https://stackoverflow.com/questions/11351382/mock-patching-from-import-statement-in-python
我应该能够patch("__main__.imported_obj")
。但是,这对我不起作用。请参阅我下面的最小重现(我正在通过以下方式运行测试pytest
):
最小重现
这是使用 Python 3.8.6 运行的。
from random import random
from unittest.mock import patch
import pytest
@pytest.fixture
def foo():
with patch("__main__.random"):
return
def test(foo) -> None:
pass
当我使用 PyCharm 运行此代码时,我得到一个AttributeError
:
AttributeError: <module '__main__' from '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/_jb_pytest_runner.py'> does not have the attribute 'random'
此外,当我在之前的行中进入调试器模式时with patch
,我看到了属性__main__
没有定义。我不确定是否需要定义它patch
发挥其魔力。
注意:我知道我可以使用patch.object
这变得容易多了。但是,我正在尝试弄清楚如何使用patch
在这个问题中。
Research
即使使用文档中的示例,也无法模拟打开 https://stackoverflow.com/questions/39155048/unable-to-mock-open-even-when-using-the-example-from-the-documentation
这个问题是相关的,因为它是类似的错误消息和用例。他们的解决方案是使用builtins
代替__main__
,但那是因为他们试图patch
一个内置函数(open
).