Unable to mock open, even when using the example from the documentation

坚强是说给别人听的谎言 提交于 2021-01-03 10:36:50

问题


I've copied and pasted the following code directly from the Python mock docs:

from unittest.mock import patch, mock_open

with patch('__main__.open', mock_open(read_data='bibble')) as m:
    with open('foo') as h:
        result = h.read()

m.assert_called_once_with('foo')
assert result == 'bibble'

When I run this I get the following error:

AttributeError: <module '__main__' from 'path/to/file'> does not have the attribute 'open'

Given that this is the example given in the documentation, I'm not sure where else to turn. I'm running Python 3.4.5.


回答1:


I figured it out.

open is a builtin, so I needed to patch builtins.open, not __main__.open.

Skipped over this info in the docs.




回答2:


Well, __main__ is the module name given by default when you run a script.

Paste the code in a python file and call it.



来源:https://stackoverflow.com/questions/39155048/unable-to-mock-open-even-when-using-the-example-from-the-documentation

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