Mock (unittest.mock backport)

5.2.0 · active · verified Sun Mar 29

The `mock` library is the official backport of the `unittest.mock` module, providing powerful tools for testing in Python. It enables developers to replace parts of their system under test with mock objects, allowing for isolated and predictable testing without relying on actual implementations or external dependencies. While `unittest.mock` has been part of Python's standard library since version 3.3, the `mock` package on PyPI historically provided these functionalities for older Python versions and sometimes offered newer features or bug fixes that were later integrated into the standard library. The current version is 5.2.0, with ongoing maintenance.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to mock an external dependency (HTTP request via `requests.get`) using `mock.patch` as a decorator. It shows how to configure the mock's return value and assert that it was called correctly.

from mock import patch, Mock
import requests

def fetch_data(url):
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

# Mocking requests.get using patch as a decorator
@patch('requests.get')
def test_fetch_data_success(mock_get):
    # Configure the mock response
    mock_response = Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {'key': 'mocked_value'}
    mock_get.return_value = mock_response

    data = fetch_data('http://example.com/api/data')

    mock_get.assert_called_once_with('http://example.com/api/data')
    assert data == {'key': 'mocked_value'}

# To run the test (e.g., with pytest, or manually calling):
# print('Running test_fetch_data_success...')
# test_fetch_data_success() # Call the decorated function
# print('Test passed.')

view raw JSON →