问题描述
我正在尝试模拟打开文件,所有示例都表明我需要
I'm trying to mock file open, and all of the examples show that I need to
@patch('open', create=True)
但我不断得到
Need a valid target to patch. You supplied: 'open'
我知道补丁需要 open
的全点划线路径,但我不知道它是什么.事实上,我什至不确定那是问题所在.
I know patch needs the full dotted path of open
, but I have no idea what it is. As a matter of fact, I'm not even sure that's the problem.
推荐答案
您需要添加模块名称;如果在脚本中进行测试,则模块的名称为__main__
:
You need to include a module name; if you are testing in a script, the name of the module is __main__
:
@patch('__main__.open')
否则,请使用包含要测试的代码的模块的名称:
otherwise use the name of the module that contains the code you are testing:
@patch('module_under_test.open')
,以便任何使用内置open()
的代码都将找到修补的全局代码.
so that any code that uses the open()
built-in will find the patched global instead.
请注意,mock
模块随附 实用程序,可让您使用文件数据构建合适的open()
调用:
Note that the mock
module comes with a mock_open()
utility that'll let you build a suitable open()
call with file data:
@patch('__main__.open', mock_open(read_data='foo\nbar\nbaz\n'))
这篇关于在python中打开模拟文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!