Meaning
Temporarily replaces a function or object with a mock during a with block, allowing you to isolate code under test and verify interactions.
Primary Function
Test mocking
Communicative Purpose
To isolate the unit under test by substituting dependencies with controllable mock objects.
Pattern
with mock.patch(';') as ;:
Core Structure
with mock.patch(';') as ;:
Função primária
Test mocking
Propósito comunicativo
To isolate the unit under test by substituting dependencies with controllable mock objects.
Situações de gatilho
When unit testing a function that calls an external API, when testing code that depends on a complex object, when you need to assert that a function was called with specific arguments.
Contextos
Python unit testing frameworks (unittest, pytest), test suites, any code using unittest.mock.
Padrão
with mock.patch(';') as ;:
Estrutura central
with mock.patch(';') as ;:
Slots de substituição
target: str, mock_var: identifier
Colocados típicos
- assert_called_with
- assert_called_once
- return_value
- side_effect
- patch.object
- pytest.fixture
Substituições comuns
- patch as decorator
- patch.object
- MagicMock directly
Erros comuns
forgetting to stop patch, patching wrong import path, using mock outside with block
Similar / contraste
patch.object (patches attribute), MagicMock direct instantiation
Interferências
Coming from Java: may confuse with Mockito annotations; in Python you manage scope with with or decorator
Família do chunk
- unittest.mock.patch
- unittest.mock.patch.object
- unittest.mock.MagicMock
- pytest.fixture
Nuance
Mock active only inside block; original restored after; patch where used, not where defined
Efeito pragmático
Makes tests isolated and deterministic by eliminating external dependencies
Dica de memória
Think 'with mock.patch as m:' as a temporary fake you can poke and check
Nota
The mock is active only inside the with block; the original object is restored automatically after exiting the block. Apply the patch where the object is used, not where it is defined.
Upgrade path
@mock.patch('module.func') def test_foo(mock_func): ...
Log in to save chunks.