Interview frequency: …
Short answer
A fixture prepares a dependency or data a test needs, which the test requests by name as a parameter, and it controls its own lifetime (scope) and cleanup after yield.
Explanation
The scope decides how often it is created: function (the default), class, module, or session. Put shared fixtures in conftest.py. Code after yield runs as cleanup even if the test fails. Make each fixture represent one clear resource, and compose fixtures from each other instead of one huge fixture that sets up the whole application and hides state. Avoid autouse except for things that are truly global.
Code example
import pytest
@pytest.fixture
def tmp_db(tmp_path):
db = Database(tmp_path / "test.sqlite")
db.migrate()
yield db
db.close() # Cleanup after the test
def test_insert(tmp_db):
tmp_db.insert("users", {"name": "Ali"})
assert tmp_db.count("users") == 1Common mistakes
- Using scope="session" for a resource each test modifies, so tests depend on their run order.
- One huge fixture that prepares everything, making it hard to see what each test needs.