Mock (unittest.mock backport)
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
- breaking The `mock` library was merged into the Python standard library as `unittest.mock` starting with Python 3.3. For Python 3.3 and newer, it is generally recommended to use `from unittest.mock import ...` instead of installing and importing the standalone `mock` package.
- gotcha When using `patch`, it is crucial to patch the object where it is *looked up* (i.e., where it is imported by the code under test), not where it is defined. Incorrect patching paths are a very common source of silent test failures.
- gotcha Mocks are 'loose' by default. If you misspell an attribute or method name on a `Mock` object, it will silently create a new mock attribute instead of raising an `AttributeError`. This can lead to tests that pass but don't actually test the intended behavior.
- gotcha `Mock` and `MagicMock` have key differences. `MagicMock` automatically provides implementations for most Python magic methods (e.g., `__len__`, `__str__`, `__enter__`, `__exit__`), whereas `Mock` does not.
- gotcha Calling `mock.reset_mock()` only resets call information (e.g., `called`, `call_args`) and child mocks. It *does not* clear `return_value` or `side_effect` on the mock itself by default.
Install
-
pip install mock
Imports
- Mock
from mock import Mock
- patch
from mock import patch
- MagicMock
from mock import MagicMock
Quickstart
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.')