A pytest fixture is a reusable setup function that supplies test data or resources. Fixtures make business-flow tests repeatable by preparing students, vouchers, and courses before each test. section 12.5
Listing 12.5 Creating fixtures to set up tests with pytest
# file: ch12/tests.py
[...]
import pytest #1
[...]
@pytest.fixture #2
def new_student_voucher() -> tuple[UUID, str]:
student_details = {
"first_name": "John",
"last_name": "Connor",
"date_birth": datetime(1985, 2, 28),
"phone_number": "634-430-6045",
"address": "19828 Valerio Street, Winnetka, CA",
"email": "john.connor@apithreats.com",
"password": "john.connor",
}
with session_maker() as session:
student, voucher = register_new_student(
student_profile=RegisterStudent(**student_details),
db_session=session
) #3
return student.id, voucher.code #4
@pytest.fixture
def course_id() -> UUID:
with session_maker() as session:
course = session.scalar(select(Course))
return course.id #5
The fixture example creates a student and voucher, then retrieves a course ID; pytest calls the fixtures when their names appear in a test function signature. section 12.5
Use fixtures to test realistic API conditions:
- Create a new student and voucher, then attempt two registrations with the same voucher; expect success first and a 409 Conflict response second. section 12.5
- Create one student's voucher, authenticate another student, and submit that voucher; expect a 403 response. section 12.5









