Registry / testing / mock

mock

JSON →
library5.2.0pypypi✓ verified 52d ago

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.

testing
pip install mock
Install & Compatibility
Where this runs
tested against v5.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.925 runs
installs and imports cleanly · install 0.0s · import 0.345s · 18MB
glibc
py 3.103.925 runs
installs and imports cleanly · install 1.5s · import 0.288s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Mock
from mock import Mock
from unittest.mock import Mock
Use 'from mock import ...' when using the PyPI backport. For Python 3.3+, it's generally preferred to use the built-in 'unittest.mock' instead.
patch
from mock import patch
from unittest.mock import patch
Use 'from mock import ...' when using the PyPI backport. For Python 3.3+, it's generally preferred to use the built-in 'unittest.mock' instead.
MagicMock
from mock import MagicMock
from unittest.mock import MagicMock
Use 'from mock import ...' when using the PyPI backport. For Python 3.3+, it's generally preferred to use the built-in 'unittest.mock' instead.

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.')
Debug
Known issues
breakingThe `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 ...`).
affects: <3.3 (requires PyPI 'mock'), >=3.3 (has built-in 'unittest.mock')
gotchaWhen 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`.
affects: All versions
gotchaMocks 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.
affects: All versions
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.
affects: All versions
gotchaCalling `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.
affects: All versions
breakingA `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`.
affects: All versions
breakingA `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>`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'mock'
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`.
AttributeError: Mock object has no attribute 'some_method'
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.
TypeError: 'MagicMock' object is not callable
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()`).
Mock does not appear to be called / original function is executed
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'`.
Upgrade
Version history
5.2.0latest on PyPI
Audit
Dependencies

No dependency data recorded yet.

Agent activity
14 hits · last 30 days
node
4
seranking-bot
4
ahrefsbot
2
Amazon
1
bingbot
1
Resources