Files
xenia-pos-local/local_backend/tests/test_errors.py
T
bonaminandClaude Opus 5.5 8a02173450 feat(manager): the overview, online orders and the day summary on v2 (platform-v2 step 6.2)
- DashboardPage (2.8k lines) → src/pages/overview/: OverviewPage + cards (shifts, tables,
  pending prints, notes, bookings, messages) and dialogs (order at a glance, shift review /
  end with the cash handover, day summary with cash count and checks); arithmetic in
  overviewLogic.js (tests/overview.test.mjs). Data via useLiveQuery: orders and tables
  live, day and shifts every 15 s. Bookings typed in venue time; decline reason in a dialog.
- OnlineOrdersPage → src/pages/online/ on react-query + live events; unused API helpers dropped.
- WorkdaySummaryModal → overview/DaySummaryDialog + DaySummaryTabs.
- Every text in manager.json (en + el, 342 keys); tokens only; v2.json adds overview, hooks.
- Backend: business day open/close answer only with codes (license.locked, license.expired,
  business_day.orders_open); XeniaError's v1 `detail` removed.
- @xenia/i18n: formatDateTime with Intl options threw "unknown date style" (fixed, tested).
- e2e manager.mjs: open the day, a shift (start, stats, end short), a live table, a booking,
  day stats, Greek, close the day (forced), online orders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:01:51 +02:00

113 lines
3.8 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)