liveBook · Manning

Test fixture

As explained in Secure APIs

A pytest fixture is a reusable test setup function that supplies data or resources to test functions and may manage their preparation and cleanup.

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

How Secure APIs covers it

How deep it goes
Defines fixtures and demonstrates injected test data, without examining pytest internals or broader fixture configuration.
Examples
Uses student, voucher, course, access-token, registration-payload, coupon-reuse, and coupon-abuse test examples.
What you can do after
Build repeatable pytest API tests that generate setup data and verify coupon-reuse and cross-student voucher protections.
How it connects
Connects pytest fixtures with unit testing, API security, authentication, authorization, and business-flow vulnerabilities.

Also explained in

Compare how 10 books explain test fixture →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secure APIs. The section links point to the parts of the book it draws on.