Rolling backport of unittest.mock for all Pythons
npx @tessl/cli install tessl/pypi-mock@5.2.0Mock is a library for testing in Python that allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. This package contains a rolling backport of the standard library unittest.mock code compatible with Python 3.6 and up.
pip install mockimport mockCommon imports for testing:
from mock import Mock, MagicMock, patch, call, ANY, sentinelFor async testing:
from mock import AsyncMockfrom mock import Mock, patch, call
# Create a simple mock object
mock_obj = Mock()
mock_obj.method.return_value = 'test result'
# Call the method and assert
result = mock_obj.method('arg')
assert result == 'test result'
mock_obj.method.assert_called_with('arg')
# Using patch to replace objects temporarily
with patch('module.function') as mock_func:
mock_func.return_value = 42
# Code that calls module.function() will get 42
# Using decorators for patching
@patch('module.function')
def test_something(mock_func):
mock_func.return_value = 'mocked'
# Test code hereThe mock library provides a hierarchical set of mock objects and patching utilities:
This design enables comprehensive test isolation, dependency injection, and behavior verification across synchronous and asynchronous Python code.
Mock object creation and configuration, including callable mocks, non-callable mocks, magic method support, and async/await compatibility.
class Mock: ...
class NonCallableMock: ...
class MagicMock(Mock): ...
class NonCallableMagicMock(NonCallableMock): ...
class AsyncMock(Mock): ...
class ThreadingMock(Mock): ...
class PropertyMock(Mock): ...Temporary replacement of objects with mocks using context managers and decorators, supporting function patching, object attribute patching, and dictionary patching.
def patch(target, **kwargs): ...
def patch.object(target, attribute, **kwargs): ...
def patch.multiple(target, **kwargs): ...
class patch.dict: ...Helper functions for creating specialized mocks and managing mock behavior.
def create_autospec(spec, **kwargs): ...
def mock_open(mock=None, read_data=''): ...
def seal(mock): ...Special matching objects and sentinel values for flexible mock assertions and unique object creation.
class _ANY: ...
class _Call: ...
class _Sentinel: ...
class InvalidSpecError(Exception): ...
DEFAULT: object
sentinel: _Sentinel
ANY: _ANY
call: _Call
FILTER_DIR: bool