Fixtures
A fixture is reusable test setup (and teardown) that pytest injects into a test by parameter name. @pytest.fixture defines one; def test_ok(db): requests it.
Detailed Explanation
Copy-pasting "create a client, open a db, insert a user" is how suites rot. A fixture names that block. pytest looks up db, runs the fixture function, and passes the return value into the test. A fixture that yields runs the code after yield as teardown, even if the test failed. That is a context manager in test clothing.
Scope controls how often the fixture runs: function (default) once per test, class, module, package, session. A session-scoped database is fast and dangerous if tests write without isolation. Prefer function scope until a profile says otherwise.
Fixtures can request other fixtures. client(db) builds an app bound to that db. Autouse fixtures run without being named; use them sparingly (turning on a timezone, isolating os.environ). An autouse fixture that hits the network will surprise everyone.
conftest.py makes fixtures visible without import. A conftest.py in tests/api/ does not leak into tests/unit/ unless you put one higher up. That directory rule is how you keep heavy fixtures off unit tests.
unittest uses setUp instead. pytest can wrap TestCase but fixtures shine on test functions. Factory fixtures that return a function (make_user) let each test choose how many objects to create.
Do not hide the interesting arrangement in a fixture. If the test is about a missing email, construct that user in the test so the reader sees it. Fixtures are for the boring, expensive, or fragile parts.
Code Examples
import pytest
@pytest.fixture
def cart():
items = ["A-1"]
yield items
items.clear()
def test_add(cart):
cart.append("B-2")
assert cart == ["A-1", "B-2"]@pytest.fixture
def make_user():
def _make(name: str, admin: bool = False) -> dict:
return {"name": name, "admin": admin}
return _make
def test_admin(make_user):
user = make_user("ada", admin=True)
assert user["admin"]Common Gotchas
Mutating a session-scoped list
the next test sees leftover state. Build fresh data or use function scope.
Fixture teardown after `yield` raising
pytest reports it as an error. Keep teardown defensive.
Autouse for convenience
it couples every test to that setup. Name the fixture and request it.
The parameter name is the lookup key
`def test_ok(cart):` must match `@pytest.fixture` named `cart`, not the file name.