with patch.multiple('my_module', func1=Mock(return_value=1), func2=Mock(side_effect=ValueError())):
Testing Patterns

Meaning

Temporarily replaces multiple attributes in a target module with Mock objects during the execution of the with block. It addresses the pain point of isolating code under test from multiple external dependencies simultaneously, triggering when a test requires overriding several functions or classes in the same module at once.

Primary Function

Mocking

Communicative Purpose

Isolates code under test by replacing multiple module-level dependencies with controlled mock objects.

Pattern

with patch.multiple(module, func1=Mock(return_value=value), func2=Mock(side_effect=exception)):

Core Structure

with patch.multiple(..., ...=Mock(...), ...=Mock(...)):

Função primária

Mocking

Propósito comunicativo

Isolates code under test by replacing multiple module-level dependencies with controlled mock objects.

Situações de gatilho

Unit testing: isolating a function that depends on multiple external services in the same module, Integration testing: overriding several module attributes to test error handling paths

Contextos

Unit test files using the unittest.mock module, typically inside a test method or a pytest fixture.

Padrão

with patch.multiple(module, func1=Mock(return_value=value), func2=Mock(side_effect=exception)):

Estrutura central

with patch.multiple(..., ...=Mock(...), ...=Mock(...)):

Slots de substituição

module: string module path, func1: attribute name to mock, value: any return value, exception: exception class or instance to raise

Colocados típicos

  • unittest
  • Mock
  • patch
  • test case
  • assert
  • assertRaises
  • fixture

Substituições comuns

  • Individual patch decorators: more verbose but easier to read for single patches
  • pytest monkeypatch: avoids unittest.mock dependency but limited to pytest

Erros comuns

Passing the module object instead of its string name: causes AttributeError because patch.multiple expects a string path to resolve -> patching fails at runtime; Forgetting to import Mock: NameError at runtime -> test crashes before executing; Mixing patch and patch.multiple on the same target: later patch overrides earlier -> unpredictable mock state and test flakiness

Similar / contraste

patch.object: patches a single attribute on an object; patch.dict: patches dictionary values; multiple patch blocks: patches multiple targets but with more verbose nesting

Interferências

Coming from JavaScript/Jest: expecting jest.spyOn to automatically restore -> Python's patch.multiple requires a context manager or decorator to guarantee restoration

Família do chunk

  • unittest.mock.patch.multiple pattern

Nuance

Do not use for patching builtins or when order of patching matters; Starting all patches has a small overhead compared to individual patches if only some are needed; All patches are applied and removed atomically within the context

Efeito pragmático

Creates a controlled testing environment where the behavior of dependencies is replaced with predictable responses, signalling a test double setup.

Dica de memória

Like swapping out multiple actors in a play before the scene starts and putting the originals back when the scene ends.

Nota

Verify that the string 'my_module' matches the module where func1 and func2 are imported or accessed in the code under test; mocks are only active within the with block.

Upgrade path

Consider migrating to pytest fixtures or parametrized tests for more reusable and declarative mock setups.

Frequência: MediumFormulaicidade: Semi-fixedTipo de construção: context manager using unittest.mock.patch.multiplePrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Short-term

Log in to save chunks.