Files
xenia-pos-local/local_backend/tests/test_errors.py
T
bonaminandClaude Opus 5.5 968b6c78fb feat(backend): error codes, backend i18n (en/el) and language fields
Platform v2 step 1.2 (APPS_PLATFORM D-12, §3.2, §8).
- core/errors.py: XeniaError + CODES registry; handlers give every error the
  {"error": {code, params, message}, "detail"} shape: XeniaError, wrapped
  HTTPException (http.<status>, detail untouched), validation.invalid (FastAPI
  detail list kept), and internal.error 500 with the request id (body, header
  and log line)
- orders: the 18 "Order not found" raises -> XeniaError("order.not_found")
- core/i18n: t(key, lang, **params) with en/el JSON (en fallback), venue/zone/
  user language resolution, normalize_language; 56 print keys
- printer_service: every printed label goes through keys. Kitchen,
  cancellation and service-item tickets print in the prep zone's language
  (-> venue.language); reports/receipts/synopsis in venue.language. Greek
  output is unchanged. Print retries now pass the job's zone (language and
  item grouping were lost on retries)
- users.language, prep_zones.language (revision 0003), setting venue.language
  (default en); editable via PATCH /auth/me, staff update, prep zones API;
  "" = inherit
- tests: error shapes, key/placeholder parity, fallback, kitchen ticket per
  zone/venue language, language APIs; pack rule CS-12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:29:31 +02:00

100 lines
3.1 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."}