Mocking Open with With Statements in Python
When testing code that uses the open() function with a with statement, it becomes necessary to mock the open call to assert expected behavior. Here's how to do it using the Mock framework in Python:
Python 3
<code class="python">from unittest.mock import patch, mock_open with patch("builtins.open", mock_open(read_data="data")): mock_file = open("path/to/open") assert mock_file.read() == "data" mock_file.assert_called_with("path/to/open")</code>
Alternatively, you can use patch as a decorator with the new_callable argument set to mock_open:
<code class="python">@patch("builtins.open", new_callable=mock_open, read_data="data") def test_patch(mock_file): open("path/to/open") assert mock_file.read() == "data" mock_file.assert_called_with("path/to/open")</code>
Python 2
The above is the detailed content of How to Mock the Open Function with With Statements in Python Unit Tests?. For more information, please follow other related articles on the PHP Chinese website!