Repaso
EspaƱol
TestingIntermediateTST-01

What is a pytest fixture?

Options

  1. A decorator that makes a test skip itself
  2. A reusable function giving setup and teardown (Correct option)
  3. A test that always passes by its own design
  4. A flag to run the whole test suite in parallel

Answer

A reusable function that provides setup (and teardown via yield) to tests that request it by parameter name

Why

Many tests need the same preparation: a test user, a database session, a temporary folder. A fixture is a function marked with @pytest.fixture that prepares it.

A test simply lists the fixture's name as a parameter and pytest passes in the result.

Code after yield is cleanup that runs after the test, even if it failed. scope controls reuse (per test, module or whole session).

@pytest.fixture
def db():
    conn = make_test_db()
    yield conn          # the test runs here
    conn.close()        # cleanup

def test_create_user(db):
    ...

Remember

Fixture = reusable setup injected by parameter name.

Key terms

Practice this question in Repaso