Meaning
Patches multiple attributes on a single module simultaneously inside a context manager, allowing each patch to be configured independently—some as default autospecced mocks, others with custom behaviors like side effects. Addresses the pain point of deeply nested with-statements when a unit under test depends on several collaborators in the same module. Reached for when more than one function or object in a module must be replaced for a test.
Primary Function
Test mocking
Communicative Purpose
Enables replacing multiple module-level targets at once while keeping test setup flat and readable.
Pattern
with patch.multiple(module, target_a=DEFAULT, target_b=MagicMock(side_effect=exception)) as mocks:
Core Structure
with patch.multiple(..., ...=DEFAULT, ...=MagicMock(side_effect=...)) as mocks:
Função primária
Test mocking
Propósito comunicativo
Enables replacing multiple module-level targets at once while keeping test setup flat and readable.
Situações de gatilho
Unit testing: a function calls several collaborators in the same module that must all be faked. Integration testing: multiple side-effect-producing functions need different mock behaviors in one test. Legacy code: patching several globals simultaneously to isolate a unit under test.
Contextos
Python unittest.mock, pytest test suites, Django test cases, any codebase using mock.patch for dependency isolation
Padrão
with patch.multiple(module, target_a=DEFAULT, target_b=MagicMock(side_effect=exception)) as mocks:
Estrutura central
with patch.multiple(..., ...=DEFAULT, ...=MagicMock(side_effect=...)) as mocks:
Slots de substituição
module: string dotted path to target module, target_a/target_b: attribute names to patch on module, exception: exception class or callable to raise on call
Colocados típicos
- patch
- patch.object
- patch.dict
- MagicMock
- DEFAULT
- call
- assert_called_once_with
Substituições comuns
- Nested with patch(...) statements — more verbose but allows patching across different modules
- stacked @patch decorators on a test method — declarative but harder to configure per-test
- pytest-mock mocker fixture — cleaner API but pytest-specific
Erros comuns
Forgetting to import DEFAULT from unittest.mock — leads to NameError at runtime. Passing keyword arguments that don't match actual module attributes — patch silently creates new attributes instead of raising, hiding typos. Omitting the 'as mocks' clause — no way to access mock objects for assertions later. Expecting mocks to be a list — it is a dictionary keyed by the keyword argument names, not positional order.
Similar / contraste
patch (single target) — patches one object at a time, requires nesting for multiple targets. patch.object — patches a specific attribute on an already-imported object rather than by module string path. patch.dict — patches dictionary values rather than object attributes.
Interferências
Coming from JavaScript/Jest: may expect jest.fn() chaining syntax — Python's patch.multiple uses keyword arguments, not chained method calls. Coming from Ruby/RSpec: may expect allow().to receive() fluent DSL — Python uses keyword args to patch.multiple instead.
Família do chunk
- patch
- patch.object
- patch.dict
- MagicMock
- DEFAULT
- call
Nuance
1. When NOT to use: if only one target needs patching, prefer plain patch() — patch.multiple adds unnecessary complexity. 2. Performance: each patched target creates a new MagicMock; patching many targets in a hot test loop can slow suite execution. 3. DEFAULT creates autospecced mocks that enforce the real object's signature — stricter than plain MagicMock and can break if the real API changes.
Efeito pragmático
Keeps test setup flat and avoids deeply nested context managers, improving readability and reducing indentation hell in test functions with many mocked dependencies.
Dica de memória
Like hiring a team of stand-in actors at once — each gets their own script (DEFAULT or custom side_effect), and you address them all by name from the 'mocks' roster.
Nota
The DEFAULT sentinel tells patch.multiple to create a default mock (autospecced if create is not True). The returned mocks dictionary maps each keyword argument name to its corresponding mock object for post-call assertions.
Upgrade path
patch.multiple with create=True for patching non-existent attributes, or using pytest-mock's mocker fixture for cleaner multi-patch setup
Log in to save chunks.