"""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"]", 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']*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