Fixtures help set up things you need for tests. Organizing them well keeps tests clean and easy to understand.
Fixture organization in FastAPI
import pytest @pytest.fixture(scope='function') def my_fixture(): # setup code yield resource # teardown code
Use @pytest.fixture to create a fixture function.
The scope controls how often the fixture runs: 'function', 'module', 'session', etc.
import pytest @pytest.fixture def sample_data(): return {'name': 'Alice', 'age': 30}
import pytest @pytest.fixture(scope='module') def db_connection(): conn = connect_to_db() yield conn conn.close()
import pytest @pytest.fixture(scope='session') def app_client(): from fastapi.testclient import TestClient from myapp import app client = TestClient(app) yield client
This example shows a fixture named client that creates a FastAPI test client once per module. The test uses this fixture to call the /hello endpoint and check the response.
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() @app.get('/hello') def hello(): return {'message': 'Hello World'} @pytest.fixture(scope='module') def client(): with TestClient(app) as c: yield c def test_hello(client): response = client.get('/hello') assert response.status_code == 200 assert response.json() == {'message': 'Hello World'}
Keep fixtures in a separate file like conftest.py to share them easily.
Use yield in fixtures to run cleanup code after tests finish.
Choose fixture scope carefully to balance speed and isolation.
Fixtures help prepare and clean up test environments.
Organize fixtures by scope and reuse to keep tests simple.
Use conftest.py to share fixtures across test files.
Practice
Solution
Step 1: Understand the role of fixtures
Fixtures are used to prepare resources like database connections or test clients before tests run.Step 2: Recognize their benefit in test code
They help keep test code clean by avoiding repeated setup code in each test.Final Answer:
To prepare resources and keep test code clean -> Option BQuick Check:
Fixtures = prepare resources + clean tests [OK]
- Confusing fixtures with app logic
- Thinking fixtures deploy the app
- Using fixtures to define database models
Solution
Step 1: Identify pytest fixture syntax
Fixtures require the decorator@pytest.fixturebefore the function.Step 2: Recognize yield usage for setup/teardown
Usingyieldallows setup before and teardown after the test.Final Answer:
@pytest.fixture\ndef my_fixture(): yield client -> Option DQuick Check:
Use @pytest.fixture and yield for fixtures [OK]
- Missing @pytest.fixture decorator
- Using FastAPI route decorators instead
- Declaring fixture as a class without decorator
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
What will
client.get('/items') return inside a test?Solution
Step 1: Analyze the fixture setup
The fixture creates a TestClient instance for the FastAPI app and yields it for use in tests.Step 2: Understand what client.get('/items') does
Callingclient.get('/items')sends a test HTTP GET request to the '/items' route and returns a response object.Final Answer:
A TestClient response object for the '/items' endpoint -> Option AQuick Check:
Fixture yields TestClient, so client.get returns response [OK]
- Thinking yield causes syntax error
- Assuming fixture returns None
- Forgetting to import app in fixture
conftest.py:import pytest
@pytest.fixture
def db():
connection = connect_to_db()
yield connection
connection.close()When running tests, you get an error:
NameError: name 'connect_to_db' is not defined. How do you fix it?Solution
Step 1: Identify cause of NameError
The error means the functionconnect_to_dbis not defined or imported in the file.Step 2: Fix by importing or defining connect_to_db
To fix, add the proper import statement or define the function before using it in the fixture.Final Answer:
Import or define the function connect_to_db before using it -> Option AQuick Check:
NameError means missing import or definition [OK]
- Removing yield does not fix NameError
- Changing fixture name won't fix missing function
- Converting to class does not solve missing import
Solution
Step 1: Understand fixture sharing in pytest
Fixtures defined inconftest.pyare automatically discovered and shared across test files in the same folder or subfolders.Step 2: Recognize why other options are poor
Copying code duplicates it, defining inside test functions prevents reuse, and putting fixtures in app files mixes concerns.Final Answer:
Define the fixture in conftest.py at the root test folder -> Option CQuick Check:
conftest.py shares fixtures across tests [OK]
- Duplicating fixture code in every test file
- Defining fixtures inside test functions
- Mixing fixtures with app code
Ready to prove it?
Pass the test and this pattern moves unknown
