Skip to content

prefer-autospec-for-callable-mock

Prefer autospec for specced function mocks called with explicit keywords.

Why

Mock, MagicMock and AsyncMock with spec or spec_set allow incompatible arguments during invocation. Tests that assert only results or call counts can therefore accept a misspelled keyword or stale call shape.

Fix

Use create_autospec(function, spec_set=True), preserving configured results. An async function produces an awaitable mock whose signature is checked when awaited. Retain a reasoned local exception for a deliberately permissive double.

Examples

Before — flagged A function spec leaves invocation permissive
tests/test_delivery.py
from unittest.mock import Mock
def send(*, recipient: str) -> None:
pass
def test_send():
double = Mock(spec=send)
double(recipient="sample")
After — preferred Autospec checks the function call shape
tests/test_delivery.py
from unittest.mock import create_autospec
def send(*, recipient: str) -> None:
pass
def test_send():
double = create_autospec(send, spec_set=True)
double(recipient="sample")