问题
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