Živý režim po vzoru Kahootu (OpenSpec změna `zivy-rezim-trida`, nová capability `live-room`). - Schválená učitelka založí nad publikovanou sadou místnost (režim Psaní / Výběr A–D, délka, časový limit); tabule ukáže 6místný kód a QR. - Připojení kódem a přezdívkou; přihlášeným se kola zapisují do DB a žebříčků, ostatní mají body jen v místnosti. - Synchronní průběh řízený učitelkou: otázka končí limitem nebo odpovědí všech, pak vyhodnocení a průběžné pořadí, na konci stupně vítězů. - Bodování shodné s běžnou hrou včetně bonusu za sérii. - Moderace (vyhození hráče, zamčení místnosti), rate limit neúspěšných pokusů o kód podle session i IP, aktualizace pollingem. - Specifikace synchronizovány do `openspec/specs/live-room/`, změna archivována. Closes #23 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_013nPfHY7UqPQTQpoHNjSQ4K Reviewed-on: #27 Co-authored-by: David Spáčil <spacildavi@gmail.com>
201 lines
6.9 KiB
Python
201 lines
6.9 KiB
Python
"""Testy sdíleného vzhledu: stylesheet, oblasti a čistota šablon."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import sqlite3
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from flask.testing import FlaskClient
|
|
|
|
from poznavacky.security import hash_password
|
|
|
|
PKG = Path(__file__).resolve().parent.parent / "poznavacky"
|
|
TEMPLATES = sorted((PKG / "templates").rglob("*.html"))
|
|
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
|
_STYLE_ATTR_RE = re.compile(r"""\sstyle\s*=\s*(["'])(.*?)\1""", re.S)
|
|
_STYLE_TAG_RE = re.compile(r"<style[\s>]", re.I)
|
|
_CSS_VAR_DECL_RE = re.compile(r"^\s*--[\w-]+\s*:")
|
|
_EXTERNAL_RE = re.compile(
|
|
r"""<(?:link|script)\b[^>]*\b(?:href|src)\s*=\s*["']\s*(?:https?:)?//""",
|
|
re.I,
|
|
)
|
|
|
|
|
|
def _area(html: str) -> str | None:
|
|
match = re.search(r'<body[^>]*data-area="([^"]+)"', html)
|
|
return match.group(1) if match else None
|
|
|
|
|
|
def test_stylesheet_and_fonts_are_served(client: FlaskClient) -> None:
|
|
css = client.get("/static/css/app.css")
|
|
assert css.status_code == 200
|
|
assert "text/css" in css.content_type
|
|
body = css.get_data(as_text=True)
|
|
assert '[data-area="admin"]' in body
|
|
assert "prefers-reduced-motion" in body
|
|
assert not re.search(r"url\(\s*[\"']?(?:https?:)?//", body)
|
|
for name in ("baloo2-latin.woff2", "baloo2-latin-ext.woff2", "OFL.txt"):
|
|
assert client.get(f"/static/fonts/{name}").status_code == 200
|
|
|
|
|
|
def test_base_layout_links_stylesheet_and_viewport(client: FlaskClient) -> None:
|
|
html = client.get("/").get_data(as_text=True)
|
|
assert "/static/css/app.css" in html
|
|
assert "viewport-fit=cover" in html
|
|
assert "interactive-widget=resizes-content" in html
|
|
|
|
|
|
def test_area_attribute_student_and_admin(
|
|
client: FlaskClient, db: sqlite3.Connection
|
|
) -> None:
|
|
assert _area(client.get("/").get_data(as_text=True)) == "zak"
|
|
assert _area(client.get("/prihlaseni").get_data(as_text=True)) == "zak"
|
|
|
|
db.execute(
|
|
"""
|
|
INSERT INTO uzivatele (email, heslo_hash, jmeno, prijmeni, role, stav)
|
|
VALUES ('ucitelka-ui@example.test', ?, 'Jana', 'Testova',
|
|
'ucitelka', 'schvaleny')
|
|
""",
|
|
(hash_password("heslo1234"),),
|
|
)
|
|
db.commit()
|
|
page = client.get("/prihlaseni").get_data(as_text=True)
|
|
match = _CSRF_RE.search(page)
|
|
assert match is not None
|
|
resp = client.post(
|
|
"/prihlaseni",
|
|
data={
|
|
"csrf_token": match.group(1),
|
|
"email": "ucitelka-ui@example.test",
|
|
"heslo": "heslo1234",
|
|
},
|
|
)
|
|
assert resp.status_code == 302
|
|
|
|
admin = client.get("/admin")
|
|
assert admin.status_code == 200
|
|
assert _area(admin.get_data(as_text=True)) == "admin"
|
|
assert _area(client.get("/").get_data(as_text=True)) == "zak"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path", TEMPLATES, ids=lambda p: str(p.relative_to(PKG / "templates"))
|
|
)
|
|
def test_templates_have_no_inline_styles(path: Path) -> None:
|
|
source = path.read_text(encoding="utf-8")
|
|
assert not _STYLE_TAG_RE.search(source), "blok <style> v šabloně"
|
|
for match in _STYLE_ATTR_RE.finditer(source):
|
|
decls = [d for d in match.group(2).split(";") if d.strip()]
|
|
assert decls and all(_CSS_VAR_DECL_RE.match(d) for d in decls), (
|
|
f"inline styl {match.group(0).strip()!r}; povolené jsou jen "
|
|
"CSS proměnné (--název: hodnota)"
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"path", TEMPLATES, ids=lambda p: str(p.relative_to(PKG / "templates"))
|
|
)
|
|
def test_templates_load_no_third_party_resources(path: Path) -> None:
|
|
source = path.read_text(encoding="utf-8")
|
|
assert not _EXTERNAL_RE.search(source)
|
|
assert "fonts.googleapis.com" not in source
|
|
|
|
|
|
def _tokens(css: str, selector: str) -> dict[str, str]:
|
|
block = re.search(re.escape(selector) + r"\s*\{(.*?)\n\}", css, re.S)
|
|
assert block is not None, selector
|
|
return dict(re.findall(r"(--[\w-]+):\s*(#[0-9a-fA-F]{6})\s*;", block[1]))
|
|
|
|
|
|
def _luminance(hex_color: str) -> float:
|
|
def channel(value: int) -> float:
|
|
c = value / 255
|
|
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
|
|
|
|
r, g, b = (int(hex_color[i : i + 2], 16) for i in (1, 3, 5))
|
|
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)
|
|
|
|
|
|
def _contrast(fg: str, bg: str) -> float:
|
|
hi, lo = sorted((_luminance(fg), _luminance(bg)), reverse=True)
|
|
return (hi + 0.05) / (lo + 0.05)
|
|
|
|
|
|
_COMMON_PAIRS = [
|
|
("--fg", "--bg"),
|
|
("--fg", "--surface"),
|
|
("--fg", "--surface-2"),
|
|
("--muted", "--bg"),
|
|
("--muted", "--surface"),
|
|
("--muted", "--surface-2"),
|
|
("--link", "--bg"),
|
|
("--link", "--surface"),
|
|
("--accent-fg", "--accent"),
|
|
("--flash-fg", "--flash-bg"),
|
|
]
|
|
_STUDENT_PAIRS = [
|
|
("--on-ok", "--ok"),
|
|
("--on-part", "--part"),
|
|
("--on-bad", "--bad"),
|
|
("--on-opt-a", "--opt-a"),
|
|
("--on-opt-b", "--opt-b"),
|
|
("--on-opt-c", "--opt-c"),
|
|
("--on-opt-d", "--opt-d"),
|
|
]
|
|
|
|
|
|
def test_token_contrast_meets_wcag_aa() -> None:
|
|
css = (PKG / "static" / "css" / "app.css").read_text(encoding="utf-8")
|
|
student = _tokens(css, ":root")
|
|
admin = {**student, **_tokens(css, '[data-area="admin"]')}
|
|
checks = [("zak", student, p) for p in _COMMON_PAIRS + _STUDENT_PAIRS]
|
|
checks += [("admin", admin, p) for p in _COMMON_PAIRS]
|
|
checks.append(("admin", admin, ("--bad", "--surface")))
|
|
failures = []
|
|
for area, tokens, (fg, bg) in checks:
|
|
ratio = _contrast(tokens[fg], tokens[bg])
|
|
if ratio < 4.5:
|
|
failures.append(f"{area}: {fg} na {bg} = {ratio:.2f}")
|
|
# Pole pro odpověď ve hře má pevné barvy (tmavý text na bílé).
|
|
for fg in ("#1a1e3a", "#5a6088"):
|
|
ratio = _contrast(fg, "#ffffff")
|
|
if ratio < 4.5:
|
|
failures.append(f"hra: {fg} na #ffffff = {ratio:.2f}")
|
|
assert not failures, failures
|
|
|
|
|
|
_FULLSCREEN_TEMPLATES = {
|
|
"game/play.html",
|
|
"live/board.html",
|
|
"live/player.html",
|
|
}
|
|
|
|
|
|
def test_fixed_position_classes_stay_in_game_templates() -> None:
|
|
"""Třída s `position: fixed` nesmí kolidovat s běžnou stránkou.
|
|
|
|
Regrese: kořen tabule hry pro třídu se jmenoval `.lb` jako panel
|
|
žebříčku a roztáhl ho přes detail sady.
|
|
"""
|
|
css = (PKG / "static/css/app.css").read_text(encoding="utf-8")
|
|
fixed_classes: set[str] = set()
|
|
for selectors, body in re.findall(r"([^{}]+)\{([^{}]*)\}", css):
|
|
if re.search(r"position:\s*fixed", body):
|
|
for selector in selectors.split(","):
|
|
last = selector.strip().split()[-1]
|
|
fixed_classes.update(re.findall(r"\.([\w-]+)", last))
|
|
offenders = []
|
|
for path in TEMPLATES:
|
|
rel = path.relative_to(PKG / "templates").as_posix()
|
|
if rel in _FULLSCREEN_TEMPLATES:
|
|
continue
|
|
source = path.read_text(encoding="utf-8")
|
|
for attr in re.findall(r'class="([^"]*)"', source):
|
|
for cls in attr.split():
|
|
if cls in fixed_classes:
|
|
offenders.append(f"{rel}: .{cls}")
|
|
assert not offenders, offenders
|