How to Mock an Object Used in a Context Manager with unittest.mock
When testing code that uses a with statement, it can be challenging to mock the underlying object. Let's consider the following example:
def testme(filepath): with open(filepath) as f: return f.read()
To test this function with unittest.mock, we need to mock the open function. Here's how:
Python 3:
Python 2:
Example:
<code class="python">from unittest.mock import patch, mock_open @patch("builtins.open", new_callable=mock_open, read_data="data") def test_patch(mock_file): assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open")</code>
Remember, in Python 3, patch will pass the mocked object as an argument to your test function, while in Python 2, you must assert on the mocked file explicitly.
The above is the detailed content of How to Mock Objects Used in Context Managers with unittest.mock?. For more information, please follow other related articles on the PHP Chinese website!