Thin-wrapper around the mock package for easier use with pytest
npx @tessl/cli install tessl/pypi-pytest-mock@3.14.0A pytest plugin that provides comprehensive mocking capabilities through the mocker fixture. It serves as a thin wrapper around Python's unittest.mock module, offering automatic cleanup and enhanced pytest integration with better error reporting.
pip install pytest-mockimport pytest_mock
from pytest_mock import MockerFixture, PytestMockWarningFor type annotations:
from pytest_mock import MockType, AsyncMockTypedef test_unix_fs(mocker):
# Patch a function/method
mocker.patch('os.remove')
# Call your code that uses os.remove
UnixFS.rm('file')
# Assert the mock was called correctly
os.remove.assert_called_once_with('file')
def test_with_spy(mocker):
# Create a spy that calls the original method
spy = mocker.spy(UnixFS, 'rm')
# Call the method - it runs normally
UnixFS.rm('file') # Actually removes the file
# But you can still assert on the call
spy.assert_called_once_with('file')
def test_with_stub(mocker):
# Create a stub for testing callbacks
callback = mocker.stub()
# Use the stub in your code
process_data(data, callback=callback)
# Assert it was called
callback.assert_called()pytest-mock integrates seamlessly with pytest's fixture system and provides:
The plugin registers with pytest and provides fixtures at different scopes, ensuring mocks are properly managed throughout the test lifecycle.
Essential mocking functionality including patching functions/methods, creating mocks, and managing mock lifecycle. This covers the primary use cases for test mocking.
def patch(self, target: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def patch.object(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def patch.context_manager(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def patch.multiple(self, target: object, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> Dict[str, MockType]: ...
def patch.dict(self, in_dict: Union[Mapping, str], values=(), clear=False, **kwargs) -> Any: ...Creating different types of mock objects and managing their lifecycle, including specialized utilities like spies and stubs for advanced testing scenarios.
def create_autospec(self, spec, spec_set=False, instance=False, **kwargs) -> MockType: ...
def spy(self, obj: object, name: str) -> MockType: ...
def stub(self, name=None) -> unittest.mock.MagicMock: ...
def async_stub(self, name=None) -> AsyncMockType: ...
def resetall(self, *, return_value=False, side_effect=False) -> None: ...
def stopall(self) -> None: ...
def stop(self, mock: unittest.mock.MagicMock) -> None: ...Multiple pytest fixtures providing MockerFixture instances at different scopes, allowing flexible mock management across various test organization patterns.
@pytest.fixture
def mocker(pytestconfig) -> MockerFixture: ...
@pytest.fixture(scope="class")
def class_mocker(pytestconfig) -> MockerFixture: ...
@pytest.fixture(scope="module")
def module_mocker(pytestconfig) -> MockerFixture: ...
@pytest.fixture(scope="package")
def package_mocker(pytestconfig) -> MockerFixture: ...
@pytest.fixture(scope="session")
def session_mocker(pytestconfig) -> MockerFixture: ...# Type aliases for mock objects
MockType = Union[
unittest.mock.MagicMock,
unittest.mock.AsyncMock,
unittest.mock.NonCallableMagicMock
]
AsyncMockType = unittest.mock.AsyncMock
# Main fixture class
class MockerFixture:
"""
Fixture providing mock functionality with automatic cleanup.
"""
# Patching interface
patch: '_Patcher' # Provides patch(), patch.object(), patch.multiple(), patch.dict()
# Mock creation aliases
Mock: Type[unittest.mock.Mock]
MagicMock: Type[unittest.mock.MagicMock]
NonCallableMock: Type[unittest.mock.NonCallableMock]
NonCallableMagicMock: Type[unittest.mock.NonCallableMagicMock]
PropertyMock: Type[unittest.mock.PropertyMock]
AsyncMock: Type[unittest.mock.AsyncMock] # Python 3.8+
# Mock utilities
call: unittest.mock._Call
ANY: unittest.mock._AnyComparer
DEFAULT: unittest.mock._SentinelObject
sentinel: unittest.mock._SentinelObject
mock_open: Callable
seal: Callable # If available
# Methods
def create_autospec(self, spec, spec_set=False, instance=False, **kwargs) -> MockType: ...
def spy(self, obj: object, name: str) -> MockType: ...
def stub(self, name=None) -> unittest.mock.MagicMock: ...
def async_stub(self, name=None) -> AsyncMockType: ...
def resetall(self, *, return_value=False, side_effect=False) -> None: ...
def stopall(self) -> None: ...
def stop(self, mock: unittest.mock.MagicMock) -> None: ...
class _Patcher:
"""Internal patching interface - use via mocker.patch"""
def __call__(self, target: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def object(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def context_manager(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
def multiple(self, target: object, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> Dict[str, MockType]: ...
def dict(self, in_dict: Union[Mapping, str], values=(), clear=False, **kwargs) -> Any: ...
# Warning class
class PytestMockWarning(UserWarning):
"""
Base class for all warnings emitted by pytest-mock.
This warning is emitted when:
- Using mocks returned by pytest-mock as context managers (usually unnecessary)
- Potential misuse of mocking patterns that could lead to issues
The most common warning is when using mock objects as context managers:
'Mocks returned by pytest-mock do not need to be used as context managers.
The mocker fixture automatically undoes mocking at the end of a test.'
This can be safely ignored if you're intentionally mocking a context manager.
"""
# Backward compatibility alias
MockFixture = MockerFixture # Deprecated alias for MockerFixture
# Configuration
pytest-mock provides configuration options that can be set in pytest.ini, pyproject.toml, tox.ini, or setup.cfg files.
## Configuration Options
```python { .api }
# pytest.ini configuration options
[tool.pytest.ini_options]
mock_traceback_monkeypatch = true # Enable enhanced assertion reporting
mock_use_standalone_module = false # Use standalone mock module instead of unittest.mockmock_traceback_monkeypatch (default: True):
--tb=native or set to false to use standard mock error messagesmock_use_standalone_module (default: False):
mock module from PyPI instead of unittest.mockmock package separately: pip install mockUsage in pytest.ini:
[tool:pytest]
mock_traceback_monkeypatch = true
mock_use_standalone_module = falseUsage in pyproject.toml:
[tool.pytest.ini_options]
mock_traceback_monkeypatch = true
mock_use_standalone_module = falsedef pytest_addoption(parser) -> None: """ Pytest hook that adds configuration options for pytest-mock.
Adds ini options:
- mock_traceback_monkeypatch: Enable enhanced assertion reporting (default: True)
- mock_use_standalone_module: Use standalone mock module instead of unittest.mock (default: False)
"""def pytest_configure(config) -> None: """ Pytest hook that configures pytest-mock based on settings.
Wraps mock assertion methods for better error reporting when
mock_traceback_monkeypatch is enabled.
"""