What is a pytest fixture?
Options
- A decorator that makes a test skip itself
- A reusable function giving setup and teardown (Correct option)
- A test that always passes by its own design
- 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.