Skip to content

Python · testing

mock-without-spec

python:mock-without-spec

Mock built without `spec=`/`autospec=` — it accepts any attribute and cannot rot loudly.

Code
SARJ040
Default
error
Fix
none
Languages
python

Why

An unrestricted mock keeps accepting calls after the real collaborator's interface changes.

Fix

Pass `spec=`, `spec_set=`, or `autospec=True`, or use a small fake implementing the real contract.

Before / after

Executed by this rule’s unit tests.

Before

Mock accepts any attribute

tests/test_service.py · focus
from unittest.mock import Mock

def test_service():
    client = Mock()
    assert client

After

Mock follows the collaborator contract

tests/test_service.py · focus
from unittest.mock import Mock

def test_service():
    client = Mock(spec=Client)
    assert client

Limits

  • Only test files and statically resolved `unittest.mock` or pytest-mock constructors are analyzed.
  • Mocks used only for their built-in assertion API are excluded.