Mock (unittest.mock backport)
raw JSON → 5.2.0 verified Tue May 12 auth: no python install: verified quickstart: stale
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.
pip install mock Common errors
error ModuleNotFoundError: No module named 'mock' ↓
cause This error occurs when trying to import the `mock` library directly on Python versions 3.3 and newer, where mocking functionality is integrated into the standard library as `unittest.mock`. Conversely, it can also happen if `from unittest.mock import X` is used on Python versions older than 3.3 without the `mock` backport installed.
fix
For Python 3.3 and newer, use
from unittest.mock import Mock (or patch, MagicMock, etc.). For Python versions older than 3.3 (e.g., 2.7, 3.2), install the backport (pip install mock) and then use from mock import Mock. error AttributeError: Mock object has no attribute 'some_method' ↓
cause This `AttributeError` typically arises when a mock object is created with `spec=True` or `autospec=True`, and the test attempts to access a method or attribute (including typos in assertion methods) that does not exist on the *real* object being mocked. It also occurs when patching a class and trying to access instance-specific attributes set in `__init__` without explicitly configuring the mock's `return_value`.
fix
Ensure the mocked method or attribute name exactly matches the real object's API or the correct
mock assertion. If using spec or autospec, either correct the name or, if the attribute is dynamically added or an instance attribute, set it on mock_obj.return_value.attribute = value or disable spec/autospec if strict adherence is not required. error TypeError: 'MagicMock' object is not callable ↓
cause This `TypeError` occurs when you attempt to call a mock object that was created as a `NonCallableMock`, or when a `MagicMock` is used to mock an asynchronous function (`async def`) without being made awaitable, or when you incorrectly call the mocked *class* directly instead of its `return_value` to interact with a mocked instance.
fix
If the original object is callable, ensure the mock is not
NonCallableMock. When mocking an async def function, use unittest.mock.AsyncMock. If patching a class, remember that patch replaces the class itself; to simulate calling an instance, interact with mock_class.return_value (e.g., mock_class.return_value.method()). error Mock does not appear to be called / original function is executed ↓
cause The most common reason for this behavior (which doesn't raise an explicit error but leads to unexpected test failures) is providing an incorrect target string to `mock.patch`. Mocking must occur where the object is *looked up* by the code under test, not necessarily where it is defined. For example, if a module imports `from another_module import some_function`, you must patch `my_module.some_function`, not `another_module.some_function`.
fix
Identify the precise path where the object or function is accessed by the code being tested. Construct the
patch target string using that exact lookup path. For example, if my_app.views imports send_email from my_app.utils, then to mock it within views, the target should be 'my_app.views.send_email'. 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. ↓
fix For Python >= 3.3, use `from unittest.mock import Mock, patch, MagicMock`. If targeting older Python versions or requiring specific features/fixes from the PyPI backport, ensure consistent imports (`from mock import ...`).
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. ↓
fix Always trace the import chain to determine the correct module path. For example, if `my_module.py` imports `requests` as `req`, and `your_app.py` imports `my_module`, you might need to patch `your_app.my_module.req`.
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. ↓
fix Use `Mock(spec=OriginalClass)` or `Mock(spec_set=OriginalClass)` (or `patch.object(..., spec=...)`/`patch.object(..., spec_set=...)`) to make the mock conform to the interface of a real object. This ensures `AttributeError` is raised for non-existent attributes. `MagicMock` is also 'loose' by default in terms of user-defined attributes.
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. ↓
fix Use `MagicMock` when you expect a mock object to behave like a container, context manager, or support other magic methods. Use `Mock` when you need a simpler, more controlled object that doesn't have magic methods pre-configured.
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. ↓
fix To reset `return_value` and `side_effect` on the mock itself, explicitly set them to their default values (e.g., `mock_obj.return_value = Mock()`, `mock_obj.side_effect = None`) or use `mock.reset_mock(return_value=True, side_effect=True)` (Python 3.6+). Alternatively, recreate mocks between tests.
breaking A `ModuleNotFoundError` indicates that a required Python package is not installed in the environment. This often happens for third-party libraries (e.g., `requests`, `numpy`, `pandas`) or custom modules that are not discoverable on the Python path. ↓
fix Ensure all necessary packages are installed using a package manager like `pip` (e.g., `pip install requests`). Verify the correct virtual environment is activated if applicable, or that the package is available on the `PYTHONPATH`.
breaking A `ModuleNotFoundError` indicates that a required Python package is not installed in the execution environment. This often happens if the package was not included in the `requirements.txt` file or if `pip install -r requirements.txt` was not run. ↓
fix Ensure that all necessary third-party packages are listed in your `requirements.txt` file and are installed in the environment using `pip install -r requirements.txt` or `pip install <package-name>`.
Install compatibility verified last tested: 2026-05-12
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.19s 18.0M
3.10 alpine (musl) - - 0.21s 18.0M
3.10 slim (glibc) wheel 1.5s 0.13s 18M
3.10 slim (glibc) - - 0.13s 18M
3.11 alpine (musl) wheel - 0.29s 19.9M
3.11 alpine (musl) - - 0.34s 19.9M
3.11 slim (glibc) wheel 1.6s 0.26s 20M
3.11 slim (glibc) - - 0.25s 20M
3.12 alpine (musl) wheel - 0.49s 11.7M
3.12 alpine (musl) - - 0.55s 11.7M
3.12 slim (glibc) wheel 1.5s 0.48s 12M
3.12 slim (glibc) - - 0.48s 12M
3.13 alpine (musl) wheel - 0.50s 11.5M
3.13 alpine (musl) - - 0.54s 11.4M
3.13 slim (glibc) wheel 1.5s 0.44s 12M
3.13 slim (glibc) - - 0.47s 12M
3.9 alpine (musl) wheel - 0.19s 17.5M
3.9 alpine (musl) - - 0.21s 17.5M
3.9 slim (glibc) wheel 1.7s 0.15s 18M
3.9 slim (glibc) - - 0.16s 18M
Imports
- Mock wrong
from unittest.mock import Mockcorrectfrom mock import Mock - patch wrong
from unittest.mock import patchcorrectfrom mock import patch - MagicMock wrong
from unittest.mock import MagicMockcorrectfrom mock import MagicMock
Quickstart stale last tested: 2026-04-24
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.')