@pytest.fixture
Testing Patterns

Meaning

Declares a function as a pytest fixture that provides setup, teardown, and dependency injection for tests. It addresses the pain point of repetitive test initialization and cleanup code. You reach for it when multiple tests need the same baseline state or resources.

Primary Function

Test setup and teardown

Communicative Purpose

Enables dependency injection and shared setup/teardown logic across multiple test functions.

Pattern

@pytest.fixture(...)

Core Structure

@pytest.fixture

Função primária

Test setup and teardown

Propósito comunicativo

Enables dependency injection and shared setup/teardown logic across multiple test functions.

Situações de gatilho

Database testing: establishing and rolling back a connection for each test. Web testing: initializing a test client with a fresh app context. Integration testing: loading shared configuration or mock data before a test suite runs.

Contextos

pytest, Python testing, continuous integration, automated test suites

Padrão

@pytest.fixture(...)

Estrutura central

@pytest.fixture

Slots de substituição

scope: str in {function, class, module, session}, autouse: bool, params: list, ids: list of str

Colocados típicos

  • def
  • return
  • yield
  • request
  • param

Substituições comuns

  • @pytest.fixture(scope='module')
  • @pytest.fixture(autouse=True)
  • @pytest.fixture(params=[1
  • 2
  • 3])

Erros comuns

Using return instead of yield for teardown (cause: misunderstanding fixture lifecycle; consequence: teardown code never runs). Forgetting to yield in a fixture that has teardown (cause: assuming return works like yield; consequence: cleanup is skipped, leading to state leakage). Setting scope too wide (cause: premature optimization; consequence: tests share state and fail non-deterministically). Overriding fixture names accidentally (cause: naming collision; consequence: wrong fixture is injected, causing confusing test failures).

Similar / contraste

@pytest.fixture vs @pytest.mark (marks vs fixtures); fixture vs plain helper function; fixture vs unittest setUp/tearDown

Interferências

Coming from unittest: expecting setUp/tearDown methods instead of yield-based cleanup → pytest fixtures use yield to separate setup from teardown. Coming from JavaScript/Jest: expecting beforeEach/afterEach pairs → pytest combines both in a single fixture function using yield.

Família do chunk

  • pytest fixture

Nuance

Do not use fixtures for one-off setup that only a single test needs; use local variables instead. Session-scoped fixtures can significantly speed up test suites but introduce shared state risks. Fixtures are lazy and only instantiated when requested by a test or another fixture, not simply by being defined.

Efeito pragmático

Eliminates boilerplate setup code and ensures reliable resource cleanup in test suites.

Dica de memória

Think of a fixture as a 'setup and teardown helper' for tests.

Nota

Fixtures placed in conftest.py are automatically available to all test modules in that directory tree.

Upgrade path

Can be extended with parametrization, autouse, or scope adjustments.

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

Log in to save chunks.