Meaning
Replaces a class or object with a mock during testing, allowing you to control its behavior and isolate the unit under test. The autospec argument ensures the mock mimics the original's signature, preventing accidental misuse.
Primary Function
Testing / Mocking
Communicative Purpose
Substitute a dependency with a controllable mock so tests run quickly and deterministically without side effects.
Pattern
@patch(; , autospec=;)
Core Structure
@patch(; , autospec=;)
Função primária
Testing / Mocking
Propósito comunicativo
Substitute a dependency with a controllable mock so tests run quickly and deterministically without side effects.
Situações de gatilho
Testing a function that instantiates or calls SomeClass; needing to simulate return values or side effects; avoiding external resources like databases or network calls.
Contextos
Python unit‑test suites using unittest or pytest, especially when applying the unittest.mock.patch decorator.
Padrão
@patch(; , autospec=;)
Estrutura central
@patch(; , autospec=;)
Slots de substituição
target: str (e.g. 'module.SomeClass'), autospec_value: bool (True|False)
Colocados típicos
- unittest.TestCase
- pytest
- MagicMock
- side_effect
- return_value
Substituições comuns
- Using patch as a context manager: with patch('module.SomeClass') as mock:
Erros comuns
Forgetting autospec leading to loose mocks; patching the wrong import path; leaving a patch active across multiple tests causing interference.
Similar / contraste
@mock.patch (alias); unittest.mock.create_autospec; pytest's monkeypatch fixture.
Interferências
Coming from Java: may confuse with @InjectMocks/@Mock; from JavaScript: mixing with sinon.stub.
Família do chunk
- unittest.mock
- MagicMock
- mock.call
- mock.assert_called_with
Nuance
autospec=True can fail if the class uses dynamic attributes via __getattr__; patch only works on objects importable by name; patching built‑ins requires a different target syntax.
Efeito pragmático
Makes unit tests deterministic and fast by eliminating external dependencies.
Dica de memória
Think 'patch the class, lock its spec'.
Nota
autospec enforces the mock’s signature and attribute spec, which prevents accidental attribute access; however, it can fail if the target uses __getattr__ or __getattribute__ dynamically, in which case autospec=False or a manually crafted spec may be needed.
Upgrade path
Using patch as a context manager for finer‑grained control: with patch('module.SomeClass') as mock:
Log in to save chunks.