"""Unit: the admin UI-settings API (phase 91, task 01). 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 >300-char string after the trim, a non-``#rrggbb`` color (wrong prefix, 3-digit shorthand, 8 hex chars, missing ``#``) — identity AND semantic fields alike (the loops are ``COLOR_FIELDS``-driven); * 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); an empty / whitespace-only string is the clear operation (NULL); * 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_too_long_string_422_names_the_field( admin_client: TestClient, db: Session ) -> None: """Each of the 3 strings: >300 chars AFTER the trim is a 422 naming that field; a rejected PUT half-writes nothing; exactly 300 still passes (the column is VARCHAR(300)).""" for field in theming.STRING_FIELDS: r = admin_client.put("/api/ui-settings", json={field: "x" * 301}) assert r.status_code == 422, (field, r.text) assert r.json()["detail"] == f"{field} is too long (max 300)" # A whitespace-padded 301 is still 301 after the trim… r = admin_client.put("/api/ui-settings", json={field: " x" * 151}) assert r.status_code == 422, (field, r.text) # No rejected PUT created the row — the upsert runs after validation. assert _row(db) is None # Exactly 300 passes — stored, trimmed. r = admin_client.put("/api/ui-settings", json={"app_name": "y" * 300}) assert r.status_code == 200, r.text assert r.json()["app_name"] == "y" * 300 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_empty_string_is_the_clear_operation( admin_client: TestClient, db: Session ) -> None: """A whitespace-only (or empty) string trims to empty → NULL — the clear operation, not a 422 and not a stored blank: the effective value falls back to the env default.""" r = admin_client.put("/api/ui-settings", json={"app_name": " ", "footer_text": ""}) assert r.status_code == 200, r.text row = _row(db) assert row is not None assert row.app_name is None assert row.footer_text is None # The response reports the effective (env) fallback, not "". assert r.json()["app_name"] == get_settings().app_name assert r.json()["footer_text"] == get_settings().footer_text 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 12 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 == "First" 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"] == "Second" 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 == "Second" # the new string landed assert rows[0].app_name is None # absent in the second body → NULL