Meaning
Temporarily replaces a target function or object with a mock within a context block, restoring the original on exit. Addresses the pain of unrepeatable or side-effect-laden tests that depend on external systems or shared state. Reached for when a unit under test calls a dependency that must be controlled or verified in isolation.
Primary Function
Test isolation
Communicative Purpose
Ensures test isolation by temporarily replacing dependencies with controllable mock objects that are automatically restored after the block.
Pattern
with patch('module.function') as alias:
Core Structure
with patch(...) as ...:
Função primária
Test isolation
Propósito comunicativo
Ensures test isolation by temporarily replacing dependencies with controllable mock objects that are automatically restored after the block.
Situações de gatilho
Unit testing: isolating a function from its database or API dependency; Legacy code: intercepting calls to global state or external services; CI pipelines: verifying interaction counts and argument values without real side effects
Contextos
Found inside unit test functions or test methods, typically within a unittest.TestCase subclass or a plain test function using the unittest.mock module.
Padrão
with patch('module.function') as alias:
Estrutura central
with patch(...) as ...:
Slots de substituição
target: str (dotted module path), alias: str (valid identifier)
Colocados típicos
- unittest mock assert_called assert_called_once return_value side_effect patch.object patch.dict
Substituições comuns
- patch.object(MyClass
- 'method') patch.dict('os.environ'
- {...}) patch('other_module.other_func') using a different alias like 'm'
Erros comuns
Patching where the object is defined instead of where it is looked up — the local reference still points to the original so the mock is never invoked; Forgetting the 'as alias' clause — makes it impossible to assert on the mock later; Using patch as a context manager and also calling stop() manually — double-stops and raises RuntimeError; Passing a relative import path instead of the fully qualified dotted path — raises AttributeError at patch time
Similar / contraste
Similar: patch.object, patch.dict, patch.multiple; Contrasting: manual monkey‑patching without cleanup, using unittest.mock.patch as a decorator instead of a context manager
Interferências
Coming from JavaScript: may try to reassign module.exports directly instead of using patch — Python requires patching the reference in the importing module's namespace, not the source; Coming from Ruby: may expect monkey-patching to persist across tests — Python's patch context manager automatically restores the original on exit
Família do chunk
- unittest.mock.patch context manager
Nuance
Do not use patch when you can inject a dependency via constructor or function argument — dependency injection is cleaner and more explicit. The mock is created and applied at the moment the with-block is entered, not at function definition time. If the target attribute does not exist at patch time, patch will create it and then delete it on exit, which can mask bugs if you patch the wrong path.
Efeito pragmático
Marks a block of code as a test isolation zone, signalling to readers that the enclosed code relies on a fake dependency and that interactions with it will be verified.
Dica de memória
Patch it, use it, then it’s gone.
Nota
The string argument to patch() must be the import path as it appears in the code under test, not necessarily the actual file where the function is defined.
Upgrade path
Start with ad‑hoc monkey‑patching → use patch as a decorator → adopt patch as a context manager → advance to patch.object, patch.dict, and patch.multiple for more complex scenarios.
Log in to save chunks.