Interview question
Test a FastAPI resource-ownership boundary
Tests missing, unauthenticated, owner, and cross-owner access through FastAPI's real dependency and routing boundary.
TL;DR
Tests missing, unauthenticated, owner, and cross-owner access through FastAPI's real dependency and routing boundary.
FastAPI TestClient, dependency overrides, object scoping, 401/404 policy, two-user fixtures, and response confidentiality.
Practice the problem like a real interview: restate, reason, implement, and test.
Write tests for GET /documents/{id}. An unauthenticated request returns 401, the owner receives the document, and another authenticated user receives 404 without learning that the document exists. Override authentication only; keep the real route, policy, repository boundary, and response model active.
Next in Python Backend Practical Labs: Django N+1 regression
anonymous -> 401
owner A requests A's document -> 200
user B requests A's document -> 404 with no title/body leak
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(autouse=True)
def clear_overrides(app):
yield
app.dependency_overrides.clear()
def as_user(app, user):
app.dependency_overrides[current_principal] = lambda: Principal(user_id=user.id)
def test_document_ownership(app, client: TestClient, users, document):
anonymous = client.get(f"/documents/{document.id}")
assert anonymous.status_code == 401
as_user(app, users.owner)
own = client.get(f"/documents/{document.id}")
assert own.status_code == 200
assert own.json()["id"] == str(document.id)
as_user(app, users.other)
denied = client.get(f"/documents/{document.id}")
assert denied.status_code == 404
assert document.title not in denied.text
Each request should use one owner-scoped indexed lookup. The test cost is dominated by application and database fixture setup.
Spot a weak answer, missing edge case, or clearer explanation? Send it in.
Say thanks with a standalone, one-time $5 contribution. No account required.