"""Unit: the admin UI-settings API (phase 91, task 01; colors-only since phase 190, task 02). Covers ``app/api/ui_settings.py`` — the PUT validation + normalization contract and the GET/PUT persistence on the single ``ui_settings`` row (all 17 palette colors since phase 93, task 01 — the 9 identity + the 8 semantic state): * PUT validation — the 422s NAME the offending field (fixed details): a non-``#rrggbb`` color (wrong prefix, 3-digit shorthand, 8 hex chars, missing ``#``) — identity AND semantic fields alike (the loops are ``COLOR_FIELDS``-driven); * the STRINGS are accepted and IGNORED (phase 190, A1 — the admin Settings panel is the single writable owner of ``app_name`` / ``input_placeholder`` / ``footer_text``): no body string is written, whatever its length or whitespace, and the stored columns are left exactly as they were (never cleared) — so an old cached client's Save cannot re-bake a name and shadow the panel; * normalization — colors are lowercased on store; a color EQUAL to its built-in is stored as NULL (the owner-locked rule: "save the defaults" must leave the row empty — the no-op injection contract); * GET — the effective merge (a partial row reports the DB values over the env/built-in defaults); * upsert — the first PUT CREATES the id-1 row, the second UPDATES that same row (one row, always id 1). House pattern (the ``test_tokens_api`` precedent): the real app via TestClient (cookie jar = the house admin-login fixture) against the real compose Postgres; the single row is global state, so an autouse fixture resets it around every test. """ from __future__ import annotations from collections.abc import Iterator import pytest from fastapi.testclient import TestClient from sqlalchemy import select, text from sqlalchemy.orm import Session from app.config import get_settings from app.core import theming from app.models import UiSettings ALL_NULL_BODY: dict[str, str | None] = { "app_name": None, "input_placeholder": None, "footer_text": None, "bg": None, "surface": None, "ink": None, "ink_soft": None, "line": None, "grid_line": None, "brand": None, "brand_soft": None, "brand_ink": None, # The 8 semantic state colors (phase 93, task 01). "ok_bg": None, "ok_ink": None, "err_bg": None, "err_ink": None, "err_line": None, "accent_bg": None, "accent_ink": None, "accent_line": None, } @pytest.fixture(autouse=True) def clean_ui_settings(db: Session) -> Iterator[None]: """ui_settings holds ONE row of global state: reset it around every test (the ``clean_tokens`` house pattern, DELETE — the row is created only by the PUT upsert, so "absent" is the natural pristine state).""" db.execute(text("DELETE FROM ui_settings")) db.commit() yield db.execute(text("DELETE FROM ui_settings")) db.commit() def _row(db: Session) -> UiSettings | None: return db.execute(select(UiSettings).where(UiSettings.id == 1)).scalars().first() def test_put_string_fields_are_ignored_not_validated( admin_client: TestClient, db: Session ) -> None: """Phase 190 (A1): the 3 string fields of the body are DROPPED before the handler reads them — no trim, no length check, no 422. A 400-char name (the old 422 case) is a plain 200 that writes nothing, and the response reports the effective (env) value; the palette in the same body still saves. An old cached client can therefore never re-bake a brand string from this surface — and can never be blocked by a validation error on a field this API no longer owns.""" for field in theming.STRING_FIELDS: r = admin_client.put( "/api/ui-settings", json={field: "x" * 301, "brand": "#818cf8"} ) assert r.status_code == 200, (field, r.text) assert r.json()[field] == getattr(get_settings(), field) db.expire_all() row = _row(db) assert row is not None assert getattr(row, field) is None, f"{field} must never be stored" assert row.brand == "#818cf8" # the colors half still saves beside it # And the row the PUT created holds no string at all. db.expire_all() row = _row(db) assert row is not None for field in theming.STRING_FIELDS: assert getattr(row, field) is None def test_put_bad_hex_422_names_the_field(admin_client: TestClient) -> None: """Each of the 17 colors: anything not ``^#[0-9a-fA-F]{6}$`` is a 422 naming that field — 3-digit shorthand, 8 hex digits, a bare hex without ``#``, a named color, and the empty string (the color clear operation is ``null``, not ``""``).""" for field in theming.COLOR_FIELDS: for bad in ("fff", "#ff", "ff00aa", "#12345678", "red"): r = admin_client.put("/api/ui-settings", json={field: bad}) assert r.status_code == 422, (field, bad, r.text) assert r.json()["detail"] == f"{field} must be a #rrggbb hex color" # Phase 92 (task 01): the 9th identity color names its 422 the same # fixed way as the other 8 (the loop above already covers it via # COLOR_FIELDS; the explicit case pins the field name in the detail). r = admin_client.put("/api/ui-settings", json={"grid_line": "nope"}) assert r.status_code == 422, r.text assert r.json()["detail"] == "grid_line must be a #rrggbb hex color" # Phase 93 (task 01): the semantic state fields name their 422 the # same fixed way (the loop covers all 8 via COLOR_FIELDS; the # explicit case pins a semantic field name in the detail). r = admin_client.put("/api/ui-settings", json={"err_line": "nope"}) assert r.status_code == 422, r.text assert r.json()["detail"] == "err_line must be a #rrggbb hex color" r = admin_client.put("/api/ui-settings", json={"accent_ink": "#12345678"}) assert r.status_code == 422, r.text assert r.json()["detail"] == "accent_ink must be a #rrggbb hex color" def test_put_lowercases_colors_on_store( admin_client: TestClient, db: Session ) -> None: """Uppercase hex passes the validator and is stored LOWERCASE — the canonical form the tag renderer and the drift comparison rely on.""" r = admin_client.put("/api/ui-settings", json={"brand": "#818CF8"}) assert r.status_code == 200, r.text assert r.json()["brand"] == "#818cf8" row = _row(db) assert row is not None assert row.brand == "#818cf8" # the stored column, not just the response def test_put_built_in_color_is_stored_as_null( admin_client: TestClient, db: Session ) -> None: """The owner-locked normalization: a color equal to its built-in is stored as NULL — PUTting the whole built-in palette (with one value in uppercase, proving the compare happens AFTER the lowercase) leaves the row COMPLETELY empty: "save the defaults" must keep an unset deployment byte-identical (the no-op injection contract).""" body = dict(ALL_NULL_BODY) for key, value in theming.BUILTIN_COLORS.items(): body[key] = value.upper() if key == "brand" else value r = admin_client.put("/api/ui-settings", json=body) assert r.status_code == 200, r.text # The response is the effective values — still the built-ins… for key in theming.COLOR_FIELDS: assert r.json()[key] == theming.BUILTIN_COLORS[key] # …and the row itself is empty (the upsert created a row of NULLs). row = _row(db) assert row is not None, "the PUT upsert creates the id-1 row" assert row.id == 1 for field in (*theming.STRING_FIELDS, *theming.COLOR_FIELDS): assert getattr(row, field) is None, f"{field} must be stored as NULL" def test_put_grid_line_built_in_is_stored_as_null( admin_client: TestClient, db: Session ) -> None: """Phase 92 (task 01): the 9th identity color gets the same owner-locked normalization as the other 8 — PUTting the built-in grid hex stores NULL (the response still reports the built-in, and the row's grid column stays empty); a NON-built-in value is stored as-is (lowercased).""" r = admin_client.put("/api/ui-settings", json={"grid_line": "#4a2626"}) assert r.status_code == 200, r.text assert r.json()["grid_line"] == theming.BUILTIN_COLORS["grid_line"] row = _row(db) assert row is not None assert row.grid_line is None # built-in → NULL r = admin_client.put("/api/ui-settings", json={"grid_line": "#123123"}) assert r.status_code == 200, r.text assert r.json()["grid_line"] == "#123123" db.expire_all() # drop the test session's pre-second-PUT view (house pattern) row = _row(db) assert row is not None assert row.grid_line == "#123123" # non-built-in is stored as-is def test_put_semantic_built_in_is_stored_as_null( admin_client: TestClient, db: Session ) -> None: """Phase 93 (task 01): the 8 semantic state colors get the same owner-locked normalization as the 9 identity colors — a value equal to its built-in stores NULL (the response still reports the built-in; the compare happens AFTER the lowercase — one value is PUT uppercase, proving it); a NON-built-in value is stored as-is (lowercased).""" r = admin_client.put("/api/ui-settings", json={"ok_ink": "#6EE7A8"}) assert r.status_code == 200, r.text assert r.json()["ok_ink"] == theming.BUILTIN_COLORS["ok_ink"] row = _row(db) assert row is not None assert row.ok_ink is None # built-in (uppercase in) → NULL r = admin_client.put("/api/ui-settings", json={"err_bg": "#2D0A0A"}) assert r.status_code == 200, r.text db.expire_all() # drop the test session's pre-second-PUT view (house pattern) row = _row(db) assert row is not None assert row.err_bg is None # the second built-in (uppercase) → NULL too r = admin_client.put("/api/ui-settings", json={"accent_ink": "#CCCCCC"}) assert r.status_code == 200, r.text assert r.json()["accent_ink"] == "#cccccc" db.expire_all() row = _row(db) assert row is not None assert row.accent_ink == "#cccccc" # non-built-in stored as-is, lowercased # A semantic field NOT in the body clears back to NULL (full # replacement — the built-in returns via the resolver). assert row.ok_ink is None assert r.json()["ok_ink"] == theming.BUILTIN_COLORS["ok_ink"] def test_put_cannot_clear_a_stored_string( admin_client: TestClient, db: Session ) -> None: """The A1 fallback survives the write strip: a legacy row that holds a baked-in string keeps it through an empty / whitespace / explicit ``null`` PUT — the Theme tab neither writes nor CLEARS the strings (clearing one is the panel's ``DELETE /api/admin/settings/{key}``). The response keeps reporting the effective value, so the old client still shows what the deployment shows.""" db.add(UiSettings(id=1, app_name="Legacy bake", footer_text="Legacy footer")) db.commit() for body in ({"app_name": " ", "footer_text": ""}, {"app_name": None}): r = admin_client.put("/api/ui-settings", json=body) assert r.status_code == 200, (body, r.text) db.expire_all() row = _row(db) assert row is not None assert row.app_name == "Legacy bake" # never written, never cleared assert row.footer_text == "Legacy footer" # The response reports the EFFECTIVE value (the stored fallback). assert r.json()["app_name"] == "Legacy bake" assert r.json()["footer_text"] == "Legacy footer" def test_get_effective_merge_partial_row(admin_client: TestClient, db: Session) -> None: """GET reports the DB values over the defaults, column by column: a row with ONLY ``bg`` set (hand-inserted) reports that color plus the built-ins and the env strings — all 20 keys, no nulls.""" db.add(UiSettings(id=1, bg="#123456")) db.commit() r = admin_client.get("/api/ui-settings") assert r.status_code == 200 body = r.json() assert set(body) == set(theming.STRING_FIELDS) | set(theming.COLOR_FIELDS) assert body["bg"] == "#123456" # the DB value wins for key in theming.COLOR_FIELDS: if key != "bg": assert body[key] == theming.BUILTIN_COLORS[key] assert body["app_name"] == get_settings().app_name assert body["input_placeholder"] == get_settings().input_placeholder assert body["footer_text"] == get_settings().footer_text def test_upsert_creates_then_updates_the_id_1_row( admin_client: TestClient, db: Session ) -> None: """The first PUT creates the id-1 row; the second updates the SAME row (still exactly one row, still id 1 — the single-row contract).""" r1 = admin_client.put( "/api/ui-settings", json={"brand": "#123abc", "app_name": "First"} ) assert r1.status_code == 200, r1.text row = _row(db) assert row is not None and row.id == 1 assert row.brand == "#123abc" assert row.app_name is None # phase 190 A1: the body's string is dropped r2 = admin_client.put( "/api/ui-settings", json={"brand": "#abcdef", "input_placeholder": "Second"} ) assert r2.status_code == 200, r2.text assert r2.json()["brand"] == "#abcdef" assert r2.json()["input_placeholder"] == get_settings().input_placeholder db.expire_all() # drop the test session's pre-second-PUT view (house pattern) rows = db.execute(select(UiSettings)).scalars().all() assert len(rows) == 1, "the upsert must never create a second row" assert rows[0].id == 1 assert rows[0].brand == "#abcdef" # updated, not appended assert rows[0].input_placeholder is None # the strings are never written assert rows[0].app_name is None