- Backend: every HTTPException in routers/ is an error code now (260 raises, ~105 new codes, texts in en + el); XeniaError(detail=...) keeps the three v1-shaped answers old pages read; bad / unknown tokens answer auth.session_ended; test_errors refuses new HTTPExceptions. - Manager: v2.json is the list of pages on the v2 rules: scripts/lint.mjs lints them, tests/v2-guards.test.mjs refuses Greek and colour literals, `strict` paths make set-state-in-effect an error. - src/live/useLiveQuery.js (react-query + live events + refresh on reconnect); Signed in now uses it. - Dead manager files removed (3.1k lines unreachable from main.jsx). - Tests: backend 544 passed, manager unit 33, run-all (no Android) passed (manager's live bell check passed on a rerun). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
127 lines
4.3 KiB
Python
127 lines
4.3 KiB
Python
"""Error responses (§3.2): {"error": {code, params, message}, "detail"}."""
|
|
import pytest
|
|
from fastapi import FastAPI, HTTPException
|
|
from fastapi.testclient import TestClient
|
|
from pydantic import BaseModel
|
|
|
|
from core.errors import CODES, XeniaError, install_error_handlers
|
|
|
|
|
|
def _app():
|
|
app = FastAPI()
|
|
install_error_handlers(app)
|
|
|
|
@app.get("/xenia")
|
|
def xenia():
|
|
raise XeniaError("order.not_found", order_id=7)
|
|
|
|
@app.get("/plain")
|
|
def plain():
|
|
raise HTTPException(status_code=409, detail="Table busy")
|
|
|
|
@app.get("/dict")
|
|
def as_dict():
|
|
raise HTTPException(status_code=409, detail={"message": "2 tables open", "open_orders": 2})
|
|
|
|
@app.get("/boom")
|
|
def boom():
|
|
raise RuntimeError("bug")
|
|
|
|
class Body(BaseModel):
|
|
qty: int
|
|
|
|
@app.post("/validate")
|
|
def validate(body: Body):
|
|
return body
|
|
|
|
return TestClient(app)
|
|
|
|
|
|
def test_xenia_error_shape():
|
|
r = _app().get("/xenia")
|
|
assert r.status_code == 404
|
|
assert r.json() == {"error": {"code": "order.not_found", "params": {"order_id": 7},
|
|
"message": "Order 7 not found."},
|
|
"detail": "Order 7 not found."}
|
|
|
|
|
|
def test_plain_http_exception_is_wrapped_and_keeps_detail():
|
|
r = _app().get("/plain")
|
|
assert r.status_code == 409
|
|
assert r.json() == {"error": {"code": "http.409", "params": {}, "message": "Table busy"}, "detail": "Table busy"}
|
|
|
|
|
|
def test_dict_detail_kept_as_is():
|
|
body = _app().get("/dict").json()
|
|
assert body["detail"] == {"message": "2 tables open", "open_orders": 2}
|
|
assert body["error"]["message"] == "2 tables open"
|
|
|
|
|
|
def test_unknown_route_has_error_shape():
|
|
body = _app().get("/nope").json()
|
|
assert body["error"]["code"] == "http.404" and body["detail"] == "Not Found"
|
|
|
|
|
|
def test_validation_error_shape_keeps_fastapi_detail_list():
|
|
r = _app().post("/validate", json={"qty": "many"})
|
|
assert r.status_code == 422
|
|
body = r.json()
|
|
assert body["error"]["code"] == "validation.invalid"
|
|
assert body["error"]["params"]["errors"][0]["field"] == "qty"
|
|
assert isinstance(body["detail"], list) and body["detail"][0]["loc"] == ["body", "qty"]
|
|
|
|
|
|
def test_unhandled_exception_has_error_shape():
|
|
r = _app_no_raise().get("/boom")
|
|
assert r.status_code == 500
|
|
assert r.json()["error"]["code"] == "internal.error"
|
|
|
|
|
|
def _app_no_raise():
|
|
return TestClient(_app().app, raise_server_exceptions=False)
|
|
|
|
|
|
def test_unregistered_code_is_a_bug():
|
|
with pytest.raises(KeyError):
|
|
XeniaError("no.such.code")
|
|
|
|
|
|
def test_every_code_has_status_and_message():
|
|
for code, (status, message) in CODES.items():
|
|
assert 400 <= status < 600 and message and code == code.lower()
|
|
|
|
|
|
def test_unknown_order_on_real_api(client, make_user, login): # plan step 1.2 "done when"
|
|
m = make_user(role="store_manager")
|
|
r = client.get("/api/orders/999999", headers=login(m))
|
|
assert r.status_code == 404
|
|
assert r.json()["error"] == {"code": "order.not_found", "params": {"order_id": 999999},
|
|
"message": "Order 999999 not found."}
|
|
|
|
|
|
def test_backend_code_raises_codes_not_http_exceptions():
|
|
"""Step 6.1: every error the app raises is a registered code (XeniaError) with texts in
|
|
both languages; a plain HTTPException would reach the apps as an untranslated `http.<status>`."""
|
|
import pathlib
|
|
import re
|
|
root = pathlib.Path(__file__).resolve().parents[1]
|
|
found = [f"{p.relative_to(root)}:{n}" for d in ("routers", "services", "core", "modules")
|
|
for p in (root / d).rglob("*.py") if p.name != "errors.py"
|
|
for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1)
|
|
if re.search(r"\bHTTPException\s*\(", line)]
|
|
assert found == [], "use XeniaError (core/errors.py) instead: " + ", ".join(found)
|
|
|
|
|
|
def test_a_code_can_keep_a_v1_shaped_detail():
|
|
app = FastAPI()
|
|
install_error_handlers(app)
|
|
|
|
@app.get("/x")
|
|
def x():
|
|
raise XeniaError("business_day.orders_open", open_orders=2, partially_paid=1,
|
|
detail={"message": "2 tables open", "open_orders": 2, "partially_paid": 1})
|
|
|
|
body = TestClient(app).get("/x").json()
|
|
assert body["error"]["code"] == "business_day.orders_open" and body["error"]["params"] == {"open_orders": 2, "partially_paid": 1}
|
|
assert body["detail"]["open_orders"] == 2
|