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

Python 3 Patch builtins.open and use mock_open, which is part of the mock framework. patch used as a context manager returns the object used to replace the patched one: from unittest.mock import patch, mock_open with patch(“builtins.open”, mock_open(read_data=”data”)) as mock_file: assert open(“path/to/open”).read() == “data” mock_file.assert_called_with(“path/to/open”) If you want to use patch as a decorator, using mock_open()‘s … Read more