pytest-mock
A pytest plugin that provides a `mocker` fixture wrapping Python's `unittest.mock`, with automatic teardown between tests.
Repository Health
Technical Analysis
pytest-mock is a thin wrapper around Python’s built-in unittest.mock module, exposed as a pytest fixture (mocker) so tests can patch, mock, and spy on objects using pytest’s fixture-injection style instead of @patch decorators or manual mock.patch context managers. Because the fixture is scoped to each test, every patch it creates is automatically undone at teardown, eliminating a common class of test-pollution bugs caused by forgotten .stop() calls or leaked patches.
Beyond basic patching, it adds ergonomics on top of the standard library — mocker.spy() to wrap a real function while still recording calls and return values, mocker.stub() for standalone mock objects, and async-aware mocking that mirrors unittest.mock.AsyncMock — making it one of the most widely installed pytest plugins for projects that need mocking beyond pytest’s built-in monkeypatch.
What You Get
- A
mockerfixture providingmocker.patch,mocker.patch.object,mocker.patch.dict,mocker.Mock, andmocker.MagicMock, all automatically undone at test teardown mocker.spy(obj, 'method')to wrap a real method so it still executes normally while recording call args, return values, and exceptions for assertionsmocker.stub()for creating standalone mock/stub objects without needing to patch an existing attribute- First-class async support mirroring
unittest.mock.AsyncMockfor mocking coroutine functions - An
mocker.resetall()helper and configurable strictness options (e.g.PYTEST_MOCK_STRICT_ASSERT) for stricter call-assertion behavior across a test suite
Common Use Cases
- Replacing
@mock.patchdecorators and their nesting/ordering headaches with a single injectedmockerfixture across a test file - Spying on a real method to verify it was called with expected arguments while still letting it execute its real logic
- Mocking async functions and coroutines in
pytest-asyncio-based test suites without manually constructingAsyncMockobjects - Ensuring test isolation in large suites by relying on automatic patch teardown instead of manually managing
mock.patchlifecycles
Under The Hood
Architecture - src/pytest_mock/plugin.py (~740 lines) implements MockerFixture, a class that wraps unittest.mock’s public API (patch, patch.object, patch.dict, Mock, MagicMock, AsyncMock) while internally tracking every patcher object it starts in a list so pytest’s fixture-finalizer mechanism can stop them all after each test, guaranteeing teardown even if a test fails midway. A _util.py module isolates version-detection helpers (e.g. locating whichever mock backend — stdlib unittest.mock — is in use) behind small utility functions, and a SpyType/PytestMockWarning set of classes provide typed annotations for mocker.spy() results and plugin-specific warnings.
Tech Stack - Pure Python (3.9+ per type hints using collections.abc generics), depending only on pytest itself and the standard library unittest.mock — no third-party mocking backend is required. Uses pyproject.toml for packaging, mypy.ini for strict static typing, and tox.ini to test across multiple Python and pytest versions.
Code Quality - tests/test_pytest_mock.py is a substantial (1400+ line) suite exercising nearly every fixture method, edge cases around async mocking, spy return/exception recording, and teardown ordering, run across the supported Python/pytest matrix via tox. The project has 42 tagged releases and steady commit activity from a broad pytest-dev contributor base, reflecting long-term stewardship under the pytest organization.
API Design - The mocker fixture is deliberately designed to feel like unittest.mock’s own API surface (same method names: patch, patch.object, Mock, MagicMock) so developers already familiar with the standard library incur essentially no new learning curve, while gaining automatic teardown and pytest-native fixture composition (e.g. combining mocker with other fixtures) for free.
Used by 16 apps in this directory
Flagsmith
Ab Testing Experimentation · Developer Tools · Devops
Open-source feature flagging, remote config, and A/B/multivariate testing platform for web, mobile, and server-side apps — self-host or use the hosted SaaS.
highlight.io
Analytics · Developer Tools · Monitoring
Open-source full-stack monitoring that unifies session replay, error tracking, logging, and distributed tracing so you can stop context-switching between tools.
Keep
Automation · Devops · Monitoring
The open-source AIOps and alert management platform that unifies 130+ monitoring tools into a single pane of glass with AI-powered correlation, deduplication, and workflow automation.
knowhere
AI Development · AI Memory · Developer Tools
Transform messy, unstructured documents into persistent, navigable memory that AI agents can actually use.
Label Studio
AI Development · Data Engineering
Label Studio is an open-source, multi-type data labeling platform that lets teams annotate images, text, audio, video, and time series data with a configurable XML-based UI and export annotations in formats ready for any ML framework.
LanceDB
AI Development · Databases
Open-source, embedded vector database built on the Lance columnar format for fast multimodal search across billions of vectors, backed by Y Combinator (W23).
WrenAI
AI Agents · Analytics · Data Engineering
Open-source GenBI engine that lets AI agents turn natural-language questions into governed SQL, charts, and shareable dashboards across 20+ data sources — no vendor lock-in, no black-box prompts.