Mocking open raises AttributeError
See original GitHub issueI am trying to translate mock_open
unittest’s example but I get an AttributeError
:
def test_open(mocker):
with mocker.patch('__main__.open', mocker.mock_open(read_data='bibble')) as m:
with open('foo') as h:
result = h.read()
m.assert_called_once_with('foo')
assert result == 'bibble'
Output:
def test_open(mocker):
open_mock = mocker.mock_open(read_data='bibble')
> with mocker.patch('builtins.open', open_mock) as m:
E AttributeError: __enter__
NOTE: pytest-mock==1.10.0
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:5 (2 by maintainers)
Top Results From Across the Web
python - Mock for context-manager fails with AttributeError: __ ...
For those really interested, I am trying to mock example 6 opened_w_error() in PEP 343 which deals with opening files and catching errors....
Read more >Why does mocking 'open' and returning a FileNotFoundError ...
Testing by mocking open with a FileNotFoundError raises AttributeError: ... I've mocked the open command in so.main . test_so_main.py has two tests: One...
Read more >unittest.mock — mock object library — Python 3.11.1 ...
Accessing any attribute not in this list will raise an AttributeError . If spec is an object (rather than a list of strings)...
Read more >unittest.mock — OpenMC Documentation
_mock_methods or name in _all_magics: raise AttributeError("Mock object has no ... A helper function to create a mock to replace the use of...
Read more >Mocking with Python! - Santex Group
If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging....
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
The purpose of the
mocker
fixture is to not use it as a context manager, otherwise you might as well usemock.patch
directly. 😉Try this:
See Note about usage as context manager in the README for more information.
I’m closing this but feel free to follow up with more questions. 👍
I had to change
'__main__.open'
with'builtins.open'
.