mock file open in python

大城市里の小女人 提交于 2019-12-07 03:33:48

问题


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. As a matter of fact, I'm not even sure that's the problem.


回答1:


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')

so that any code that uses the open() built-in will find the patched global instead.

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'))



回答2:


In Python 3 you should use:

@mock.patch("builtins.open", create=True)


来源:https://stackoverflow.com/questions/38454272/mock-file-open-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!