pytest-mock-guidelisted
Install: claude install-skill aiskillstore/marketplace
# pytest-mock Usage Guide
pytest-mock is a pytest plugin providing a `mocker` fixture as a thin wrapper around Python's `unittest.mock` patching API. It automatically undoes all mocking at the end of each test.
## The mocker Fixture
The `mocker` fixture is the main interface. Request it in your test function:
```python
def test_example(mocker):
# All mocks are automatically cleaned up after this test
mock_func = mocker.patch("module.function")
```
### Available Fixture Scopes
| Fixture | Scope | Use Case |
|---------|-------|----------|
| `mocker` | function | Default, per-test mocking |
| `class_mocker` | class | Share mocks across test class |
| `module_mocker` | module | Share mocks across test module |
| `package_mocker` | package | Share mocks across package |
| `session_mocker` | session | Share mocks across entire session |
## Patching Methods
### mocker.patch(target, ...)
Patch a module-level object by its dotted path:
```python
def test_patch(mocker):
# Patch os.remove function
mock_remove = mocker.patch("os.remove")
mock_remove.return_value = None
os.remove("file.txt")
mock_remove.assert_called_once_with("file.txt")
```
### mocker.patch.object(target, attribute, ...)
Patch an attribute on an object directly:
```python
def test_patch_object(mocker):
import os
mock_remove = mocker.patch.object(os, "remove")
os.remove("file.txt")
mock_remove.assert_called_once_with("file.txt")
```
### mocker.patch.dict(in_dict