Home  >  Article  >  Backend Development  >  How to Mock Objects Used in Context Managers with unittest.mock?

How to Mock Objects Used in Context Managers with unittest.mock?

DDD
DDDOriginal
2024-10-20 16:27:29461browse

How to Mock Objects Used in Context Managers with unittest.mock?

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:

  1. Patch builtins.open and use mock_open from unittest.mock.
  2. Use patch as a context manager or decorator. In both cases, pass mock_open with the desired read data and verify that the mocked file is called with the expected arguments.

Python 2:

  1. Patch __builtin__.open instead of builtins.open.
  2. Use mock as a context manager and pass mock_open as before.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn