Files
brain-of-reese/tests/unit/test_ui_settings.py
T
ducoterra df91c6316c
Build and Push Containers / build-and-push-app (push) Successful in 1m47s
Build and Push Containers / build-and-push-db (push) Successful in 11s
phase: 92_theme_save_and_coverage
**Phase 92 final verification pass — all green.** This pass re-verified the completed tasks (all 5 task files already in `complete/`) against every completion criterion; no defects found, nothing to fix.

- Verified: 9th identity var `grid_line` end-to-end (migration `0015` at head, model/`theming.py`/schemas/API, 422 + built-in→NULL tests present); `styles.css` zero hardcoded literals outside `:root` + derived `--brand-*` vars; 9th picker in theme form; wordmark themed; `theme.js` save/reset/re-show/mount live-sync; dedicated E2E suite + phase-91 suite updated.
- `uv run pytest --cov=app --cov-report=term-missing` → **1845 passed, exit 0, TOTAL 99%** (>90%)
- `uv run ruff check .` → clean; `uv run pyright` → 0 errors, 0 warnings
- `uv run pytest tests/e2e/test_theme_save_and_coverage.py -v --no-cov` → **3 passed** (save-live, reset-live, whole-site)
- `uv run pytest tests/e2e/test_admin_theme_tab.py -v --no-cov` → **5 passed**
- Criteria: (1) Save/Reset repaint open page, no nav, SPA-nav survives, pre-paint intact ✅; (2) both `rg` gates green (only `:root` + documented `#fff` Stop label; zero SVG hex attrs), grid/selection/hovers/wash/wordmark E2E-proven ✅; (3) no-op contract live-checked: row-less `/` = no tag + exact A1 CSP, grid-only row = 9-var tag in `COLOR_FIELDS` order + sha256 CSP, with-row ≡ row-less bytes ✅; (4) full suite/coverage/lint/both E2E ✅; (5) commit left to the harness per instructions.
- Deviations (previously made, probe-verified, kept): live repaint uses CSSOM `<html>` overrides because Chromium blocks `<style>` textContent mutations under the locked sha256-only CSP (tag text still mirrors the next load; `<html>` style exact-saved after Save, empty after Reset); wordmark themed via 3 `.brand-mark` CSS rules instead of inline styles (task 03's inline attrs were CSP-blocked — fixed during task 04).
- Next pending phase: none — `todo/` contains only `92_theme_save_and_coverage`.
2026-09-10 00:23:08 -04:00

225 lines
9.8 KiB
Python

"""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:
* 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 ``#``);
* 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,
}
@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 9 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"
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_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