with patch('module.submodule.ClassName', autospec=True) as MockClass:
Testing Patterns

Meaning

Temporarily replaces a specified attribute with a mock object for the duration of the with block, automatically restoring the original attribute afterward. Used in unit tests to isolate the code under test from its dependencies.

Primary Function

Testing / Mocking

Communicative Purpose

Isolate unit under test by substituting dependencies with controllable mocks

Pattern

with patch(target, autospec=True) as mock_var:

Core Structure

with patch(..., autospec=True) as ...:

Função primária

Testing / Mocking

Propósito comunicativo

Isolate unit under test by substituting dependencies with controllable mocks

Situações de gatilho

Writing unit tests that need to mock external services, classes, or functions; simulating error conditions; verifying interactions with dependencies

Contextos

Python testing frameworks (unittest, pytest) using unittest.mock; test suites for libraries and applications

Padrão

with patch(target, autospec=True) as mock_var:

Estrutura central

with patch(..., autospec=True) as ...:

Slots de substituição

target: str (module path to callable/class), mock_var: identifier for the mock

Colocados típicos

  • assert_called_with
  • return_value
  • side_effect
  • patch.object
  • pytest fixtures

Substituições comuns

  • patch.object
  • patch.dict
  • using new=...
  • using autospec=False

Erros comuns

Forgetting to stop a patch when not using a context manager → state leaks into other tests causing false passes or failures; Omitting autospec=True → mock accepts any attribute call without validation, hiding interface mismatches; Patching the wrong import path (e.g. the module where the class is defined instead of where it is used) → original unpatched object is called and test is not actually isolated

Similar / contraste

unittest.mock.MagicMock (direct instantiation), pytest.monkeypatch (functional alternative), dependency injection via constructor

Interferências

Coming from Java: may expect @Mock annotations; need to adapt to Python's context-manager style patch

Família do chunk

  • unittest.mock
  • mocking
  • test doubles
  • dependency injection

Nuance

patch only works for attributes importable via the module system; must be applied before code under test runs; autospec ensures the mock matches the spec of the original; if target is a class, the mock returns a MagicMock instance; patch does not affect builtins unless create=True is used

Efeito pragmático

Isolates unit under test, prevents side effects, enables deterministic and fast tests

Dica de memória

Patch it, mock it, then let it go

Nota

Remember to stop the patch if not using a context manager; using autospec=True ensures the mock matches the original object's spec, preventing overly permissive mocks that can hide bugs.

Upgrade path

use pytest's monkeypatch fixture or apply patch as a decorator (@patch)

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: Context manager usage of unittest.mock.patch with autospec=TruePrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Medium-term

Log in to save chunks.