Meaning
Creates a strict mock object that enforces the spec of ExternalService, allowing attribute access only on defined attributes and returning a mock instance.
Primary Function
Creates a strict mock that enforces the spec of ExternalService and returns a mock instance.
Communicative Purpose
Express the creation of a strict mock for testing external service interactions while enforcing interface correctness.
Pattern
create_autospec(Class, spec_set=True, instance=True)
Core Structure
create_autospec(spec, spec_set=True, instance=True)
Função primária
Creates a strict mock that enforces the spec of ExternalService and returns a mock instance.
Propósito comunicativo
Express the creation of a strict mock for testing external service interactions while enforcing interface correctness.
Situações de gatilho
When writing unit tests that need to mock an external service or dependency while ensuring the code under test only accesses attributes defined on the spec.
Contextos
Unit testing with Python's unittest.mock, especially when testing code that interacts with external services, APIs, or complex objects where attribute typos should be caught early.
Padrão
create_autospec(Class, spec_set=True, instance=True)
Estrutura central
create_autospec(spec, spec_set=True, instance=True)
Slots de substituição
ExternalService: type or spec; spec_set: bool; instance: bool
Colocados típicos
- unittest.TestCase
- patch
- MagicMock
- assert_called_with
- assert_called_once_with
Substituições comuns
- Using MagicMock without spec_set (less strict
- allows arbitrary attributes)
- using patch.object to replace an attribute with a MagicMock
- using create_autospec with spec_set=False (loose mock that permits attribute typos).
Erros comuns
1. Forgetting to set spec_set=True results in a loose mock that accepts arbitrary attributes, causing false positives (cause: misunderstanding spec enforcement; consequence: tests pass despite interface mismatches). 2. Setting instance=False returns a mock class instead of an instance, leading to AttributeError when code expects an instance (cause: confusing the instance flag; consequence: test failures). 3. Passing a non‑class object as spec raises TypeError (cause: supplying an instance instead of a class; consequence: test setup fails). 4. Omitting the import of create_autospec from unittest.mock triggers NameError (cause: missing import; consequence: runtime error). 5. Over‑constraining with spec_set=True on a large, changing API makes tests brittle (cause: over‑specifying mocks; consequence: tests break on unrelated refactors).
Similar / contraste
MagicMock (less strict, allows arbitrary attributes); patch (context manager/decorator for patching objects); create_autospec with spec_set=False (loose mock that permits attribute typos); autospec decorator (applies autospec to a patched object); PropertyMock (for mocking properties).
Interferências
Coming from JavaScript/Jest: may expect jest.mock to automatically mock all members, whereas Python's create_autospec with spec_set=True enforces attribute existence and raises AttributeError on typos. Coming from Java/Mockito: may expect Mockito's lenient mocks by default, while Python's strict mock requires explicit spec_set=True to obtain similar leniency.
Família do chunk
- unittest.mock
- mocking patterns
- test doubles
Nuance
1. Avoid when you need dynamic attributes or objects with __getattr__ that are not part of the spec, as the strict mock will block them. 2. Performance: spec_set adds attribute‑validation overhead, which is negligible in most tests but measurable in tight loops. 3. Boundary: spec_set=True protects against typos but can break tests if the spec evolves and the mocks are not updated.
Efeito pragmático
Ensures tests fail fast when code accesses non‑existent attributes, catching interface mismatches early and reducing debugging time.
Dica de memória
Like a strict security guard who only lets people through the door if their name is on the guest list.
Upgrade path
Using autospec with the patch decorator for class‑level mocking, or using create_autospec with spec_set=False for more flexible mocks.
Log in to save chunks.