acupedia-api/tests/test_exception_handlers.py

51 lines
1.9 KiB
Python

from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from app.core.exception_handlers import register_exception_handlers
from app.features.access.errors import AccessUnauthorizedError
from app.features.auth.errors import InvalidTokenError
from app.features.content.errors import ModuleNotFoundError
from app.features.search.errors import SearchScopeError
def _app() -> FastAPI:
app = FastAPI()
register_exception_handlers(app)
return app
def test_dependency_access_unauthorized_is_401_not_500() -> None:
app = _app()
def dependency() -> None:
raise AccessUnauthorizedError("Unauthorized.")
@app.get("/protected")
def protected(_: None = Depends(dependency)) -> dict[str, bool]:
return {"ok": True}
response = TestClient(app).get("/protected")
assert response.status_code == 401
assert response.json() == {"detail": {"code": "AUTH_UNAUTHORIZED", "message": "Your session is missing, expired, or invalid."}}
def test_auth_invalid_token_is_401() -> None:
app = _app()
@app.get("/token")
def token() -> None:
raise InvalidTokenError("Unauthorized.")
response = TestClient(app).get("/token")
assert response.status_code == 401
assert response.json()["detail"]["code"] == "AUTH_UNAUTHORIZED"
def test_module_not_found_is_404() -> None:
app = _app()
@app.get("/module")
def module() -> None:
raise ModuleNotFoundError("Unknown module.")
response = TestClient(app).get("/module")
assert response.status_code == 404
assert response.json()["detail"]["code"] == "MODULE_NOT_FOUND"
def test_invalid_search_scope_is_422() -> None:
app = _app()
@app.get("/search")
def search() -> None:
raise SearchScopeError("Invalid scope.")
response = TestClient(app).get("/search")
assert response.status_code == 422
assert response.json()["detail"]["code"] == "SEARCH_SCOPE_INVALID"