pytest-mock

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

Library
PyPI
v3.15.1
2,038stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
82/100Excellent
Development Activity84
Maintenance76
Community68
Maturity60
Momentum40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
83/100Excellent
Architecture82
Code Quality88
Innovation70
Learning Curve90

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
100%
Apache 2.0

Agno

Devops · AI Development · Automation

41,774

Build, run, and manage agent platforms with a full production stack — SDK, runtime, and control plane included.

View details
93
Repo Health
87
Technical
67
Dependency
Built with
Python100%
Updated today
Python
49%
Other

Airbyte

Developer Tools · Data Engineering

21,916

Open-source ELT platform with 600+ connectors for moving data from any source to warehouses, lakes, and AI agents.

View details
95
Repo Health
80
Technical
67
Dependency
Built with
Python49%
Kotlin42%
Updated today
Python
90%
Apache 2.0

Apache Airflow

Data Engineering

46,530

Define, schedule, and monitor complex data workflows as Python code — with a powerful UI, 80+ provider integrations, and battle-tested scalability across thousands of production deployments.

View details
96
Repo Health
89
Technical
66
Dependency
Built with
Python90%
Updated today
Python
59%
Apache 2.0

argilla

AI Development · Data Engineering

5,081

Collaborate on high-quality AI training data with a self-hosted annotation platform built for LLMs, NLP, and multimodal models.

View details
65
Repo Health
81
Technical
63
Dependency
Built with
Python59%
Jupyter Notebook21%
Updated 2 days ago
Python
52%
MIT

Auto Company

AI Agents · Automation

2,273

A 24/7 autonomous AI company: 14 expert-persona agents running on Claude Code or Codex CLI that research, decide, code, deploy, and market real products with a single markdown file as their only memory.

View details
41
Repo Health
51
Technical
72
Dependency
Built with
Python52%
TypeScript17%
Shell14%
Updated 3 months ago
Python
68%
Other

AutoGPT

Automation · Productivity · AI Assistants

186,687

Build, deploy, and run autonomous AI agents that automate complex multi-step workflows using a visual block-based graph editor.

View details
93
Repo Health
78
Technical
67
Dependency
Built with
Python68%
TypeScript31%
Updated today
TypeScript
48%
AGPL 3.0

Banana Slides

AI Design Tools · Productivity

15,476

AI-native PPT generator with Vibe editing, multi-LLM support, and fully editable PPTX export

View details
83
Repo Health
82
Technical
71
Dependency
Built with
TypeScript48%
Python47%
Updated 3 days ago
Python
79%
Apache 2.0

changedetection.io

Monitoring

33,241

Self-hosted website change detection with AI-powered smart alerts, browser automation, price tracking, and 85+ notification channels.

View details
90
Repo Health
80
Technical
69
Dependency
Built with
Python79%
Updated 3 days ago
C++
74%
Other

Dragonfly

Databases · Developer Tools · Devops

31,013

A modern Redis and Memcached replacement engineered for multi-core servers — delivering 25x more throughput, better cache hit rates, and up to 80% lower memory consumption with full API compatibility.

View details
90
Repo Health
9
Technical
71
Dependency
Built with
C++74%
Python16%
Updated today

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

Search