pytest-mock

3.15.1 · active · verified Sat Mar 28

pytest-mock is a pytest plugin that provides a `mocker` fixture, acting as a thin wrapper around Python's `unittest.mock` library. It simplifies the process of creating and managing mock objects in pytest tests by automatically cleaning up mocks after each test. The library is actively maintained, with frequent updates to support new Python and pytest versions, currently at version 3.15.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using the `mocker` fixture to patch `os.path.exists` and `builtins.open` to simulate file system interactions without touching actual files. The first test verifies behavior when a file exists, and the second when it doesn't. `mocker.patch` automatically handles cleanup after each test.

import os

class MyService:
    def read_config(self, filename):
        if not os.path.exists(filename):
            return {}
        with open(filename, 'r') as f:
            return {'data': f.read()}

def test_read_config_file_exists(mocker):
    mock_exists = mocker.patch('os.path.exists', return_value=True)
    mock_open = mocker.patch('builtins.open', mocker.mock_open(read_data='key: value'))

    service = MyService()
    result = service.read_config('config.txt')

    mock_exists.assert_called_once_with('config.txt')
    mock_open.assert_called_once_with('config.txt', 'r')
    assert result == {'data': 'key: value'}

def test_read_config_file_not_exists(mocker):
    mocker.patch('os.path.exists', return_value=False)
    mocker.patch('builtins.open', side_effect=FileNotFoundError)

    service = MyService()
    result = service.read_config('non_existent.txt')

    assert result == {}

view raw JSON →