3

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.

James Kelleher
  • 1,957
  • 3
  • 18
  • 34

2 Answers2

3

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.

James Kelleher
  • 1,957
  • 3
  • 18
  • 34
1

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

Paste the code in a python file and call it.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103