[英]mock file open in python
I'm trying to mock file open, and all of the examples show that I need to 我正在尝试模拟文件打开,所有示例都显示我需要
@patch('open', create=True)
but I keep getting 但我一直在
Need a valid target to patch. You supplied: 'open'
I know patch needs the full dotted path of open
, but I have no idea what it is. 我知道补丁需要
open
的完整虚线路径 ,但我不知道它是什么。 As a matter of fact, I'm not even sure that's the problem. 事实上,我甚至不确定这是什么问题。
You need to include a module name; 您需要包含模块名称; if you are testing in a script, the name of the module is
__main__
: 如果您在脚本中进行测试,则模块的名称为
__main__
:
@patch('__main__.open')
otherwise use the name of the module that contains the code you are testing: 否则使用包含您正在测试的代码的模块的名称:
@patch('module_under_test.open')
so that any code that uses the open()
built-in will find the patched global instead. 所以任何使用
open()
内置的代码都会找到修补的全局代码。
Note that the mock
module comes with a mock_open()
utility that'll let you build a suitable open()
call with file data: 请注意,
mock
模块附带了一个mock_open()
实用程序 ,它允许您使用文件数据构建合适的open()
调用:
@patch('__main__.open', mock_open(read_data='foo\nbar\nbaz\n'))
在Python 3中你应该使用:
@mock.patch("builtins.open", create=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.