Thin-wrapper around the mock package for easier use with pytest
npx @tessl/cli install tessl/pypi-pytest-mock@3.14.00
# pytest-mock
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: pytest-mock
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install pytest-mock`
10
11
## Core Imports
12
13
```python
14
import pytest_mock
15
from pytest_mock import MockerFixture, PytestMockWarning
16
```
17
18
For type annotations:
19
20
```python
21
from pytest_mock import MockType, AsyncMockType
22
```
23
24
## Basic Usage
25
26
```python
27
def test_unix_fs(mocker):
28
# Patch a function/method
29
mocker.patch('os.remove')
30
31
# Call your code that uses os.remove
32
UnixFS.rm('file')
33
34
# Assert the mock was called correctly
35
os.remove.assert_called_once_with('file')
36
37
def test_with_spy(mocker):
38
# Create a spy that calls the original method
39
spy = mocker.spy(UnixFS, 'rm')
40
41
# Call the method - it runs normally
42
UnixFS.rm('file') # Actually removes the file
43
44
# But you can still assert on the call
45
spy.assert_called_once_with('file')
46
47
def test_with_stub(mocker):
48
# Create a stub for testing callbacks
49
callback = mocker.stub()
50
51
# Use the stub in your code
52
process_data(data, callback=callback)
53
54
# Assert it was called
55
callback.assert_called()
56
```
57
58
## Architecture
59
60
pytest-mock integrates seamlessly with pytest's fixture system and provides:
61
62
- **MockerFixture**: Main interface providing all mocking functionality
63
- **Automatic Cleanup**: All mocks are automatically stopped after each test
64
- **Enhanced Assertions**: Better error messages using pytest's introspection
65
- **Multiple Scopes**: Support for function, class, module, package, and session scopes
66
- **Type Safety**: Full type annotations for better IDE support
67
68
The plugin registers with pytest and provides fixtures at different scopes, ensuring mocks are properly managed throughout the test lifecycle.
69
70
## Capabilities
71
72
### Core Mocking Operations
73
74
Essential mocking functionality including patching functions/methods, creating mocks, and managing mock lifecycle. This covers the primary use cases for test mocking.
75
76
```python { .api }
77
def patch(self, target: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
78
def patch.object(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
79
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: ...
80
def patch.multiple(self, target: object, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> Dict[str, MockType]: ...
81
def patch.dict(self, in_dict: Union[Mapping, str], values=(), clear=False, **kwargs) -> Any: ...
82
```
83
84
[Core Mocking Operations](./core-mocking.md)
85
86
### Mock Creation and Management
87
88
Creating different types of mock objects and managing their lifecycle, including specialized utilities like spies and stubs for advanced testing scenarios.
89
90
```python { .api }
91
def create_autospec(self, spec, spec_set=False, instance=False, **kwargs) -> MockType: ...
92
def spy(self, obj: object, name: str) -> MockType: ...
93
def stub(self, name=None) -> unittest.mock.MagicMock: ...
94
def async_stub(self, name=None) -> AsyncMockType: ...
95
def resetall(self, *, return_value=False, side_effect=False) -> None: ...
96
def stopall(self) -> None: ...
97
def stop(self, mock: unittest.mock.MagicMock) -> None: ...
98
```
99
100
[Mock Creation and Management](./mock-creation.md)
101
102
### Pytest Fixtures
103
104
Multiple pytest fixtures providing MockerFixture instances at different scopes, allowing flexible mock management across various test organization patterns.
105
106
```python { .api }
107
@pytest.fixture
108
def mocker(pytestconfig) -> MockerFixture: ...
109
110
@pytest.fixture(scope="class")
111
def class_mocker(pytestconfig) -> MockerFixture: ...
112
113
@pytest.fixture(scope="module")
114
def module_mocker(pytestconfig) -> MockerFixture: ...
115
116
@pytest.fixture(scope="package")
117
def package_mocker(pytestconfig) -> MockerFixture: ...
118
119
@pytest.fixture(scope="session")
120
def session_mocker(pytestconfig) -> MockerFixture: ...
121
```
122
123
[Pytest Fixtures](./fixtures.md)
124
125
## Types
126
127
```python { .api }
128
# Type aliases for mock objects
129
MockType = Union[
130
unittest.mock.MagicMock,
131
unittest.mock.AsyncMock,
132
unittest.mock.NonCallableMagicMock
133
]
134
135
AsyncMockType = unittest.mock.AsyncMock
136
137
# Main fixture class
138
class MockerFixture:
139
"""
140
Fixture providing mock functionality with automatic cleanup.
141
"""
142
143
# Patching interface
144
patch: '_Patcher' # Provides patch(), patch.object(), patch.multiple(), patch.dict()
145
146
# Mock creation aliases
147
Mock: Type[unittest.mock.Mock]
148
MagicMock: Type[unittest.mock.MagicMock]
149
NonCallableMock: Type[unittest.mock.NonCallableMock]
150
NonCallableMagicMock: Type[unittest.mock.NonCallableMagicMock]
151
PropertyMock: Type[unittest.mock.PropertyMock]
152
AsyncMock: Type[unittest.mock.AsyncMock] # Python 3.8+
153
154
# Mock utilities
155
call: unittest.mock._Call
156
ANY: unittest.mock._AnyComparer
157
DEFAULT: unittest.mock._SentinelObject
158
sentinel: unittest.mock._SentinelObject
159
mock_open: Callable
160
seal: Callable # If available
161
162
# Methods
163
def create_autospec(self, spec, spec_set=False, instance=False, **kwargs) -> MockType: ...
164
def spy(self, obj: object, name: str) -> MockType: ...
165
def stub(self, name=None) -> unittest.mock.MagicMock: ...
166
def async_stub(self, name=None) -> AsyncMockType: ...
167
def resetall(self, *, return_value=False, side_effect=False) -> None: ...
168
def stopall(self) -> None: ...
169
def stop(self, mock: unittest.mock.MagicMock) -> None: ...
170
171
class _Patcher:
172
"""Internal patching interface - use via mocker.patch"""
173
def __call__(self, target: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
174
def object(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
175
def context_manager(self, target: object, attribute: str, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> MockType: ...
176
def multiple(self, target: object, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) -> Dict[str, MockType]: ...
177
def dict(self, in_dict: Union[Mapping, str], values=(), clear=False, **kwargs) -> Any: ...
178
179
# Warning class
180
class PytestMockWarning(UserWarning):
181
"""
182
Base class for all warnings emitted by pytest-mock.
183
184
This warning is emitted when:
185
- Using mocks returned by pytest-mock as context managers (usually unnecessary)
186
- Potential misuse of mocking patterns that could lead to issues
187
188
The most common warning is when using mock objects as context managers:
189
'Mocks returned by pytest-mock do not need to be used as context managers.
190
The mocker fixture automatically undoes mocking at the end of a test.'
191
192
This can be safely ignored if you're intentionally mocking a context manager.
193
"""
194
195
# Backward compatibility alias
196
MockFixture = MockerFixture # Deprecated alias for MockerFixture
197
198
# Configuration
199
200
pytest-mock provides configuration options that can be set in pytest.ini, pyproject.toml, tox.ini, or setup.cfg files.
201
202
## Configuration Options
203
204
```python { .api }
205
# pytest.ini configuration options
206
[tool.pytest.ini_options]
207
mock_traceback_monkeypatch = true # Enable enhanced assertion reporting
208
mock_use_standalone_module = false # Use standalone mock module instead of unittest.mock
209
```
210
211
**mock_traceback_monkeypatch** (default: True):
212
- Enhances mock assertion error messages with detailed parameter introspection
213
- Shows differences between expected and actual call arguments
214
- Disable with `--tb=native` or set to `false` to use standard mock error messages
215
216
**mock_use_standalone_module** (default: False):
217
- Forces use of the standalone `mock` module from PyPI instead of `unittest.mock`
218
- Useful for compatibility with older Python versions or specific mock features
219
- Requires installing the `mock` package separately: `pip install mock`
220
221
Usage in pytest.ini:
222
```ini
223
[tool:pytest]
224
mock_traceback_monkeypatch = true
225
mock_use_standalone_module = false
226
```
227
228
Usage in pyproject.toml:
229
```toml
230
[tool.pytest.ini_options]
231
mock_traceback_monkeypatch = true
232
mock_use_standalone_module = false
233
```
234
235
# Plugin hooks
236
def pytest_addoption(parser) -> None:
237
"""
238
Pytest hook that adds configuration options for pytest-mock.
239
240
Adds ini options:
241
- mock_traceback_monkeypatch: Enable enhanced assertion reporting (default: True)
242
- mock_use_standalone_module: Use standalone mock module instead of unittest.mock (default: False)
243
"""
244
245
def pytest_configure(config) -> None:
246
"""
247
Pytest hook that configures pytest-mock based on settings.
248
249
Wraps mock assertion methods for better error reporting when
250
mock_traceback_monkeypatch is enabled.
251
"""
252
```