pytest-mock

Pytest plugin that provides a mocker fixture wrapping Python's unittest.mock — the same capabilities as mock.patch/MagicMock but as a pytest fixture instead of decorator/context manager. pytest-mock's mocker fixture: creates mocks that are automatically cleaned up after each test (no need for patch.stop()), provides mocker.patch(), mocker.MagicMock(), mocker.spy(), mocker.stub(), and mocker.AsyncMock(). Integrates with pytest's assertion rewriting for clearer assertion failure messages. Preferred over unittest.mock decorators in pytest-based test suites for cleaner test function signatures.

Evaluated Mar 06, 2026 (0d ago) v3.x
Homepage ↗ Repo ↗ Developer Tools python testing mock pytest mocker patch spy unit-testing
⚙ Agent Friendliness
70
/ 100
Can an agent use this?
🔒 Security
97
/ 100
Is it safe for agents?
⚡ Reliability
91
/ 100
Does it work consistently?

Score Breakdown

⚙ Agent Friendliness

MCP Quality
--
Documentation
90
Error Messages
88
Auth Simplicity
100
Rate Limits
100

🔒 Security

TLS Enforcement
100
Auth Strength
100
Scope Granularity
95
Dep. Hygiene
92
Secret Handling
95

Testing library — no production security concerns. Ensure mocked agent credentials use test values, never production API keys. Mock cleanup after each test prevents test credential leakage between tests.

⚡ Reliability

Uptime/SLA
92
Version Stability
90
Breaking Changes
88
Error Recovery
95
AF Security Reliability

Best When

You're writing pytest-based unit tests for Python agent services that need to mock external dependencies (LLM APIs, databases, HTTP clients) — pytest-mock provides cleaner mock lifecycle management than unittest.mock decorators.

Avoid When

You're using unittest.TestCase (pytest-mock's mocker fixture doesn't work directly), you need complex stub behavior (write explicit fakes), or you want no mocking (prefer integration tests).

Use Cases

  • Mock LLM API client in agent unit tests — mocker.patch('myagent.llm_client.call', return_value={'choices': [...]}) isolates agent logic from real API calls in unit tests
  • Spy on agent method calls to verify behavior — mocker.spy(agent_service, 'process_tool_call') then assert agent_service.process_tool_call.call_count == 2 after agent execution
  • Mock async agent functions with AsyncMock — mocker.patch('agent.fetch_data', new_callable=mocker.AsyncMock) for testing async agent code with await calls
  • Patch environment variables for agent configuration tests — mocker.patch.dict(os.environ, {'AGENT_API_KEY': 'test-key', 'AGENT_MODEL': 'test-model'}) for agent config unit tests
  • Create agent test doubles with MagicMock — agent_db = mocker.MagicMock(); agent_db.get_agent.return_value = test_agent; inject into agent service for dependency-isolated testing

Not For

  • Integration tests — mocker is for unit test isolation; use real implementations or Testcontainers for agent integration tests
  • Projects not using pytest — pytest-mock is pytest-specific; use unittest.mock directly for non-pytest test suites
  • Complex test double orchestration — for complex agent service test doubles with behavior verification, consider dedicated mock libraries or hand-written fakes

Interface

REST API
No
GraphQL
No
gRPC
No
MCP Server
No
SDK
Yes
Webhooks
No

Authentication

Methods: none
OAuth: No Scopes: No

Testing library — no auth concepts.

Pricing

Model: open_source
Free tier: Yes
Requires CC: No

pytest-mock is MIT licensed, maintained by Bruno Oliveira. Free for all use.

Agent Metadata

Pagination
none
Idempotent
Full
Retry Guidance
Not documented

Known Gotchas

  • Patch target is where it's used, not where it's defined — mocker.patch('myagent.service.requests.get') patches requests.get in myagent.service module; mocker.patch('requests.get') patches the original but imported references in agent modules are already bound and unaffected
  • MagicMock vs AsyncMock for async functions — mocker.patch() on async functions in Python 3.8+ auto-detects and uses AsyncMock; in older pytest-mock versions, must explicitly use mocker.patch(..., new_callable=mocker.AsyncMock); returning coroutine from MagicMock causes TypeError
  • mocker.spy works differently from mocker.patch — mocker.spy wraps original function (real function still called, but calls tracked); mocker.patch replaces function entirely (original not called); use spy for agent integration tests where real logic must execute but calls need verification
  • return_value vs side_effect for iterative mocking — mock.return_value = x returns same x every call; mock.side_effect = [x, y, z] returns x first call, y second, z third (raises StopIteration after); use side_effect list for agent retry tests that expect different responses per attempt
  • spec= parameter prevents attribute mistakes — mocker.MagicMock(spec=AgentService) creates mock that only allows attributes/methods on AgentService; accessing non-existent agent attributes raises AttributeError instead of silently returning new Mock; use spec= for better agent test safety
  • Reset mock state between parameterized tests — mocker fixture is function-scoped; with mocker.patch on module-level objects, verify mock.call_count and mock.reset_mock() patterns; parametrize with mocker creates fresh mocker per test case

Alternatives

Full Evaluation Report

Detailed scoring breakdown, competitive positioning, security analysis, and improvement recommendations for pytest-mock.

$99

Scores are editorial opinions as of 2026-03-06.

5215
Packages Evaluated
26151
Need Evaluation
173
Need Re-evaluation
Community Powered