pytest is a Python testing framework for running focused tests with assertions. In API security work, it turns expected authorization behavior into repeatable checks that can expose serious flaws. section 12.4
A practical pytest security workflow includes:
- Create a test client, select a resource, make an unauthenticated request, and assert the expected status code. section 12.4
- Test BOLA by authenticating one student and requesting another student's registration, expecting a forbidden response. section 12.4
- Test RBAC by using a regular user's token against an administrator endpoint. section 12.4
Run a focused test
Install pytest with `uv add --dev pytest`, then run `PYTHONPATH=\`pwd\` pytest tests.py -k "bola"` to execute the BOLA test. A failing assertion can reveal unauthorized access. section 12.4
Listing 12.2 Running a broken authentication test
# file: ch12/tests.py
from sqlalchemy import select
from starlette_testclient import TestClient
from db_session import session_maker
from models import Course
from server import server
client = TestClient(server) #1
def test_broken_authentication():
with session_maker() as session: #2
course = session.scalar(select(Course)) #3
lessons = course.lessons
response = client.get(
f"/courses/{course.id}/lessons/{lessons[0].id}"
) #4
assert response.status_code == 403 #5
Inspect the complete broken-authentication test, including database selection, request construction, and status-code assertion. section 12.4










