Typing Stubs for the Mock Library

5.2.0.20260408 · active · verified Thu Apr 09

This package provides high-quality type stubs for the `mock` library (and by extension, `unittest.mock` from the standard library), enabling static type checkers like `mypy` to understand and validate usage of mock objects. Part of the `typeshed` project, it is actively maintained with a continuous release cadence reflecting updates to the stubs. The current version is 5.2.0.20260408.

Warnings

Install

Imports

Quickstart

This example demonstrates how `types-mock`, when used with `mypy`, provides type-checking for `unittest.mock.Mock` and `MagicMock` objects. By using `spec=MyService`, `mypy` ensures that the mock adheres to the `MyService` interface, catching potential type errors that might otherwise go unnoticed during testing setup.

import sys
from unittest.mock import Mock, MagicMock

# Define a simple service with type hints
class MyService:
    def fetch_data(self, url: str) -> dict:
        return {"status": "ok", "url": url, "data": "real content"}

def process_data(service: MyService, target_url: str) -> str:
    data = service.fetch_data(target_url)
    if data and data.get("status") == "ok":
        return f"Successfully processed data from {data.get('url')}"
    return "Failed to process data"

# --- Usage with types-mock (implicitly through mypy) ---

# 1. Mocking a method explicitly typed
mock_service_typed: MyService = Mock(spec=MyService) # Use spec for stricter type checking
mock_service_typed.fetch_data.return_value = {"status": "ok", "url": "mocked.com", "data": "mocked content"}

print(f"Typed Mock Result: {process_data(mock_service_typed, 'http://example.com')}")

# mypy would catch this if uncommented because 123 is not a string for url:
# print(process_data(mock_service_typed, 123))

# 2. MagicMock is also typed
magic_mock_example: MagicMock = MagicMock()
magic_mock_example.__len__.return_value = 5
print(f"MagicMock length: {len(magic_mock_example)}")

# To see types-mock in action, save this as `app.py`, then run:
# pip install mypy
# mypy app.py

view raw JSON →