def test_mocker_fixture(mocker_fixture): assert my_module.my_func() == 123
Testing Patterns

Meaning

A pytest test function that receives the mocker fixture from the pytest-mock plugin, enabling patching and stubbing of dependencies within the test scope. It addresses the need to isolate units under test by replacing external calls with controlled substitutes. This pattern is reached for whenever a test requires mocking module-level objects, API calls, or other dependencies that make tests fragile or slow.

Primary Function

Testing

Communicative Purpose

Enables isolated unit testing by injecting a mocking fixture that can patch and stub dependencies

Pattern

def test_name(mocker): mocker.patch(target, return_value=value) assert module.function() == expected

Core Structure

def test_...(mocker): ... assert ... == ...

Função primária

Testing

Propósito comunicativo

Enables isolated unit testing by injecting a mocking fixture that can patch and stub dependencies

Situações de gatilho

Unit testing: isolating a function that calls an external API or database; Legacy code: testing modules with hard-coded dependencies that cannot be injected; CI/CD: ensuring fast test suites by replacing slow I/O with instant mock returns

Contextos

pytest, pytest-mock plugin, Python unit testing, test-driven development, CI/CD pipelines

Padrão

def test_name(mocker): mocker.patch(target, return_value=value) assert module.function() == expected

Estrutura central

def test_...(mocker): ... assert ... == ...

Slots de substituição

test_name: str starting with test_, mocker: pytest-mock fixture, target: dotted path to object being patched, value: return value for mock, module: Python module object, function: callable under test, expected: expected return value

Colocados típicos

  • mocker.patch
  • mocker.patch.object
  • mocker.patch.multiple
  • mocker.spy
  • pytest.raises
  • capsys
  • tmp_path
  • @pytest.fixture

Substituições comuns

  • monkeypatch (pytest built-in
  • simpler but lacks spy and stop() features)
  • unittest.mock.patch (stdlib
  • more verbose decorator/context manager usage)
  • unittest.TestCase.mock (class-based
  • requires self.setUp cleanup)

Erros comuns

Forgetting to install pytest-mock plugin → fixture not found error at collection time; Patching at the wrong path (where defined vs where used) → mock not applied, real function executes; Not setting return_value on mock → mock returns a MagicMock object instead of the expected value, causing assertion failures; Placing mocker.patch after the function call → mock is never active during execution

Similar / contraste

monkeypatch (pytest built-in fixture, simpler API but no spy or call tracking), unittest.mock (stdlib, requires manual cleanup and more boilerplate), @patch decorator (class-style, applies to entire test function scope)

Interferências

Coming from JavaScript/Jest: expect jest.fn() pattern → pytest-mock uses mocker.patch() with Python dotted-path strings instead of module factory functions; Coming from unittest: self.setUp()/self.tearDown() patching → pytest-mock auto-cleans patches at test teardown, no manual stop() needed; Coming from Ruby/RSpec: allow().to_receive → pytest-mock uses mocker.patch with return_value, not message expectation syntax

Família do chunk

  • pytest fixtures
  • pytest-mock
  • unittest.mock
  • monkeypatch
  • pytest.raises

Nuance

1. When NOT to use: for pure functions with no external dependencies, plain assertions suffice and mocking adds unnecessary complexity. 2. The mocker fixture auto-reverses all patches at test teardown, preventing state leakage between tests. 3. mocker.patch target must reference the object where it is looked up (import site), not where it is originally defined — patching the definition site silently fails.

Efeito pragmático

Prevents flaky tests caused by real network or database calls, enables testing error paths and edge cases that are difficult or impossible to reproduce with live dependencies

Dica de memória

Like a stunt double standing in for the real actor — the mocker fixture swaps in a controlled replacement so the scene plays out exactly as scripted, then cleans up after itself.

Nota

The mocker fixture requires the pytest-mock plugin (pip install pytest-mock). It wraps unittest.mock with a pytest-friendly interface and automatic cleanup.

Upgrade path

mocker.patch.object for method-level patching, mocker.patch.multiple for batch patching, mocker.spy for call tracking without replacing behavior

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: routinePrioridade de aquisição: Active recallPrioridade de output: OutputTag de espaçamento: Short-term

Log in to save chunks.