Skip to main content
In this lesson we add tests to ensure unauthenticated users cannot retrieve posts. We’ll first review the existing authenticated test, examine a failing assertion, then add a test for the unauthorized case.

Authenticated client — existing test

This test verifies that an authorized client can fetch all posts:
Notes about the test:
  • authorized_client is expected to include authentication credentials (e.g., a JWT).
  • test_posts is a fixture that creates posts in the test database before the request runs.
  • The validate helper ensures each returned post can be parsed into the PostOut Pydantic schema, which will raise an error if the response shape is wrong.
When running the suite, the test produced a failing assertion:
This failure indicates that res.json() returned a different number of posts than test_posts. Possible causes include:
  • The API filters posts by owner, returning only posts belonging to the authorized user rather than all test posts.
  • The test_posts fixture created posts under different users or contexts.
  • There is an ordering or creation timing issue in setup causing fewer posts to exist at request time.
Troubleshooting tips:
  • Print res.json() during the test run to inspect the exact returned payload.
  • Verify how test_posts assigns ownership to posts and that authorized_client corresponds to the same user.
  • Ensure database cleanup/fixtures are running deterministically; check for shared state between tests.
Make the request without authentication to verify unauthorized behaviour. The test fixtures will create posts (and any necessary test users) before the request runs, so you don’t need to create a user manually.

Unauthorized user — new test

Add a test that confirms unauthenticated users receive 401 Unauthorized when requesting the posts list:
This simple assertion ensures the API enforces authentication for the /posts/ endpoint. The client fixture performs requests without any authentication headers.

Test summary

Additional recommendations

  • Use debug prints (or pytest -k test_name -s) to inspect res.json() during development.
  • If authorization is user-scoped, assert that the number of returned posts equals the posts owned by the authorized user (not necessarily len(test_posts)).
  • Validate the response schema by mapping results to schemas.PostOut (as shown) to detect shape mismatches early.

Watch Video