liveBook · Manning

Pytest

As explained in Secure APIs

pytest is a Python testing framework for discovering and running tests with assertions, fixtures, and extensible plugins.

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

How Secure APIs covers it

How deep it goes
Demonstrates test setup, requests, assertions, installation, execution, and focused selection, but not pytest internals.
Examples
Uses unauthenticated course requests, cross-student registration requests, administrator endpoints, and focused pytest commands.
What it assumes
Assumes Python test code, an API test client, application models, and authentication-token helpers.
What you can do after
Diagnose unauthorized access and privilege-escalation flaws by writing, running, and filtering API security tests.
How it connects
Connects pytest with API security, authentication, BOLA, RBAC, authorization, and FastAPI.

Also explained in

Compare how 11 books explain pytest →

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.