pytest-mock

A pytest plugin that provides a `mocker` fixture wrapping Python's `unittest.mock`, with automatic teardown between tests.

Library
PyPI
v3.17.0
2,040 stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
87 /100 Excellent
Development Activity 96
Maintenance 84
Community 68
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
83 /100 Excellent
Architecture 82
Code Quality 88
Innovation 70
Learning Curve 90

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 mocker fixture providing mocker.patch, mocker.patch.object, mocker.patch.dict, mocker.Mock, and mocker.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 assertions
  • mocker.stub() for creating standalone mock/stub objects without needing to patch an existing attribute
  • First-class async support mirroring unittest.mock.AsyncMock for 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.patch decorators and their nesting/ordering headaches with a single injected mocker fixture 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 constructing AsyncMock objects
  • Ensuring test isolation in large suites by relying on automatic patch teardown instead of manually managing mock.patch lifecycles

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

Python
63%
BSD 3

Flagsmith

Ab Testing Experimentation · Developer Tools · Devops

6,613

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.

View details
90
Repo Health
82
Technical
63
Dependency
Built with
Python 63%
TypeScript 32%
Updated 5 days ago
TypeScript
71%
Other

highlight.io

Analytics · Developer Tools · Monitoring

9,384

Open-source full-stack monitoring that unifies session replay, error tracking, logging, and distributed tracing so you can stop context-switching between tools.

View details
76
Repo Health
78
Technical
65
Dependency
Built with
TypeScript 71%
Go 16%
Updated 6 days ago
Python
64%
Other

Keep

Automation · Devops · Monitoring

12,433

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.

View details
88
Repo Health
79
Technical
66
Dependency
Built with
Python 64%
TypeScript 36%
Updated 1 weeks ago
Python
94%
Apache 2.0

knowhere

AI Development · AI Memory · Developer Tools

3,755

Transform messy, unstructured documents into persistent, navigable memory that AI agents can actually use.

View details
83
Repo Health
75
Technical
66
Dependency
Built with
Python 94%
Updated 5 days ago
TypeScript
39%
Apache 2.0

Label Studio

AI Development · Data Engineering

28,540

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.

View details
93
Repo Health
87
Technical
64
Dependency
Built with
TypeScript 39%
JavaScript 27%
Python 25%
Updated 6 days ago
Rust
43%
Apache 2.0

LanceDB

AI Development · Databases

11,757

Open-source, embedded vector database built on the Lance columnar format for fast multimodal search across billions of vectors, backed by Y Combinator (W23).

View details
90
Repo Health
86
Technical
72
Dependency
Built with
Rust 43%
Python 27%
HTML 21%
Updated 5 days ago
Python
66%
Apache 2.0

WrenAI

AI Agents · Analytics · Data Engineering

17,958

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.

View details
91
Repo Health
91
Technical
68
Dependency
Built with
Python 66%
Rust 31%
Updated 6 days ago

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers