The Python Oracle

How do I mock an open used in a with statement (using the Mock framework in Python)?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Question
00:22 Accepted answer (Score 156)
01:02 Answer 2 (Score 399)
02:35 Answer 3 (Score 86)
03:33 Answer 4 (Score 17)
04:11 Thank you

--

Full question
https://stackoverflow.com/questions/1289...

Question links:
[unittest.mock]: https://docs.python.org/3/library/unitte...

Accepted answer links:
http://www.voidspace.org.uk/python/mock/...

Answer 2 links:
[builtins.open]: https://docs.python.org/3/library/builti...
[mock_open]: https://docs.python.org/3/library/unitte...
[mock]: https://docs.python.org/3/library/unitte...
[patch]: https://docs.python.org/3/library/unitte...
[context manager]: https://docs.python.org/3/reference/data...
[patch]: https://docs.python.org/3/library/unitte...

Answer 3 links:
[mock_open]: http://www.voidspace.org.uk/python/mock/...

Answer 4 links:
[mock_open]: https://docs.python.org/3.3/library/unit...
[already given on this page]: https://stackoverflow.com/a/19146253/552...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mocking #withstatement

#avk47