Performance: Fixture organization
This affects test suite startup time and memory usage, impacting how quickly tests can run and how responsive the development feedback loop is.
import pytest @pytest.fixture(scope='session') def db_connection(): conn = create_connection() yield conn conn.close() def test_one(db_connection): assert db_connection.is_connected() def test_two(db_connection): assert db_connection.is_connected()
import pytest @pytest.fixture def db_connection(): conn = create_connection() yield conn conn.close() def test_one(db_connection): assert db_connection.is_connected() def test_two(db_connection): assert db_connection.is_connected()
| Pattern | Setup Calls | Teardown Calls | Resource Usage | Verdict |
|---|---|---|---|---|
| Function-scoped fixture | Runs before each test | Runs after each test | High (repeated connections) | [X] Bad |
| Session-scoped fixture | Runs once per test session | Runs once after all tests | Low (shared connection) | [OK] Good |
@pytest.fixture before the function.yield allows setup before and teardown after the test.conftest.py fixture code:import pytest
@pytest.fixture
def client():
from fastapi.testclient import TestClient
from myapp.main import app
with TestClient(app) as c:
yield c
client.get('/items') return inside a test?client.get('/items') sends a test HTTP GET request to the '/items' route and returns a response object.conftest.py:import pytest
@pytest.fixture
def db():
connection = connect_to_db()
yield connection
connection.close()NameError: name 'connect_to_db' is not defined. How do you fix it?connect_to_db is not defined or imported in the file.conftest.py are automatically discovered and shared across test files in the same folder or subfolders.Pass the test and this pattern moves unknown