"""Parcours dans un vrai navigateur (Chromium) : tableau de bord, éditeur, plein écran, export et import, partage, pages Vidéos, Thèmes et Aide. Aucune erreur JavaScript. Ignorés sans Playwright et son Chromium (``pip install playwright`` puis ``python -m playwright install chromium-headless-shell``), sans base de test, ou sans le bundle Vega (``npm run build``). Ils vérifient ce que les tests du serveur ne voient pas : les scripts de la page (1.3.3 : un script qui ne trouvait plus un élément de la page ; 1.3.4 : un diagramme qui tremblait en plein écran). """ from __future__ import annotations import socket import threading import time import pytest from shortstats.config import WebConfig from shortstats.web.auth import hash_password from shortstats.web.templating import HERE from ..outils.base import seed_comments, seed_snapshots, seed_videos from ..outils.site import PASSWORD playwright = pytest.importorskip("playwright.sync_api", reason="Playwright absent") uvicorn = pytest.importorskip("uvicorn") if not (HERE / "static" / "vendor" / "vega-bundle.js").exists(): pytest.skip("bundle Vega absent (npm run build)", allow_module_level=True) TWO_AXES = {"source": "evolution", "x": "age", "y": "views", "y_more": ["like_rate"], "type": "bar", "type2": "line", "split_channels": False, "highlight": [{"rank": "latest", "n": 1}, {"rank": "latest", "n": 2}]} @pytest.fixture(scope="module") def site(db_urls, tmp_path_factory): """Le site servi par uvicorn sur un port libre, pour toute la durée du module.""" from shortstats.web.app import create_app users = tmp_path_factory.mktemp("navigateur") / "users.txt" users.write_text(f"alice:{hash_password(PASSWORD)}\n") cfg = WebConfig(database_url=db_urls["web"], secret_key="x" * 40, users_file=str(users), session_max_age_s=3600, cookie_secure=False, login_max_failures=50, login_lock_minutes=1) with socket.socket() as s: s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] server = uvicorn.Server(uvicorn.Config(create_app(cfg), host="127.0.0.1", port=port, log_level="warning")) thread = threading.Thread(target=server.run, daemon=True) thread.start() for _ in range(100): if server.started: break time.sleep(0.05) yield f"http://127.0.0.1:{port}" server.should_exit = True thread.join(timeout=5) @pytest.fixture(scope="module") def navigateur(): with playwright.sync_playwright() as p: try: # vraies barres de défilement (le mode sans écran les cache) : voir le plein écran browser = p.chromium.launch(ignore_default_args=["--hide-scrollbars"]) except Exception as exc: # Chromium non installé pytest.skip(f"Chromium indisponible : {exc}") yield browser browser.close() @pytest.fixture() def page(site, navigateur, clean_db): seed_snapshots(clean_db["owner"]) seed_videos(clean_db["owner"]) seed_comments(clean_db["owner"]) context = navigateur.new_context(viewport={"width": 1440, "height": 900}, bypass_csp=True) pg = context.new_page() pg.errors = [] pg.on("pageerror", lambda e: pg.errors.append(f"erreur : {e}")) pg.on("console", lambda m: m.type == "error" and pg.errors.append(f"console : {m.text}")) pg.goto(site + "/login") pg.fill("input[name=username]", "alice") pg.fill("input[name=password]", PASSWORD) pg.click("button[type=submit]") pg.wait_for_url(site + "/") pg.site = site yield pg context.close() assert pg.errors == [], pg.errors def api(pg, method, path, data=None): r = pg.request.fetch(pg.site + path, method=method, headers={"Origin": pg.site}, **({"data": data} if data is not None else {})) assert r.ok, r.text() return r.json() if r.text() else None def drawn(pg, scope=".card"): pg.wait_for_selector(f"{scope} .chart-box svg, {scope} .chart-box canvas", timeout=20000) def test_editeur_ajout_et_modification(page): page.click("#add-chart") page.wait_for_selector("#editor[open]") page.wait_for_selector("#preview svg, #preview canvas", timeout=20000) # deux ordonnées : un onglet d'agrégation chacune page.click("#add-y") page.wait_for_function("document.querySelectorAll('#f-aggs .agg-box').length === 2") box = page.locator("#f-aggs .agg-box").first box.locator(":scope > summary").click() box.locator("select").nth(1).select_option("formula") box.locator("textarea").fill("$date € [2026-09-05,2026-09-20]") page.wait_for_function("[...document.querySelectorAll('#f-aggs .agg-check')].some(e => e.textContent.startsWith('→'))") page.click("#editor-save") page.wait_for_selector("#editor:not([open])", state="attached") drawn(page) assert page.locator(".card").count() == 1 # modification : l'éditeur reprend les deux ordonnées et la formule page.click('.card [data-action="edit"]') page.wait_for_selector("#editor[open]") page.wait_for_function("document.querySelectorAll('#f-aggs .agg-box').length === 2") assert "2026-09-05" in page.locator("#f-aggs textarea").first.input_value() page.locator("#editor [data-close]").first.click() def test_plein_ecran_sans_tremblement(page): api(page, "POST", "/api/charts", {"config": TWO_AXES}) page.reload() drawn(page) page.click('.card [data-action="full"]') page.wait_for_selector(".card.is-full") page.wait_for_timeout(800) # masquer les vidéos mises en avant par défaut, puis en ajouter une labels = page.locator(".is-full .chart-box svg .role-legend-label text") n = labels.count() for i in range(n - 2, n): labels.nth(i).click(force=True) page.wait_for_timeout(600) page.click(".is-full .hl-add-btn") page.select_option(".is-full .hl-rank", index=2) page.click(".is-full .hl-rank-row button") page.wait_for_timeout(1500) # dessin qui dépasse sa zone de quelques pixels : la zone ne doit pas osciller page.add_style_tag(content=".chart-box svg { margin-bottom: 3px; margin-right: 3px; }") page.evaluate("() => window.dispatchEvent(new Event('resize'))") page.wait_for_timeout(500) sizes = page.evaluate("""async () => { const box = document.querySelector('.is-full .chart-box'), out = new Set(); const t0 = performance.now(); while (performance.now() - t0 < 1500) { const g = box.querySelector('svg, canvas').getBoundingClientRect(); out.add(`${box.clientWidth}x${box.clientHeight}/${Math.round(g.width)}x${Math.round(g.height)}`); await new Promise((r) => requestAnimationFrame(r)); } return [...out]; }""") assert len(sizes) == 1, sizes page.click('.is-full [data-action="full"]') # « Quitter le plein écran » page.wait_for_selector(".card:not(.is-full)") def test_export_import_et_partage(page): api(page, "POST", "/api/charts", {"config": {"x": "publish_date", "y": "views"}}) page.reload() drawn(page) page.click("#export-charts") page.wait_for_selector("#export-dialog[open]") page.wait_for_function("document.querySelector('#export-text').value.includes('shorts-stats/diagrammes')") text = page.locator("#export-text").input_value() page.locator("#export-dialog [data-close]").first.click() page.click("#import-charts") page.fill("#import-text", text) page.click("#import-go") page.wait_for_function("document.querySelectorAll('#charts .card').length === 2") # partage public page.locator('.card [data-action="share"]').first.click() page.click("#share-start") page.wait_for_function("document.querySelector('#share-url').value.includes('/shared/')") url = page.locator("#share-url").input_value() page.locator("#share-dialog [data-close]").first.click() page.goto(url) drawn(page, "#shared") def test_pages_videos_themes_aide(page): page.goto(page.site + "/videos") details = page.locator("details[data-video]").first details.locator("summary").click() page.wait_for_function("document.querySelector('details[data-video] .snapshots-body').textContent.trim().length > 0") page.goto(page.site + "/themes") page.locator("form[data-theme-form] .re-input").last.fill("(?i)short") page.wait_for_function("[...document.querySelectorAll('.re-preview, .re-status')].some(e => e.textContent.trim())") page.goto(page.site + "/help") page.fill("#help-q", "plein écran") page.wait_for_function("document.querySelector('#help-count').textContent.trim().length > 0") page.goto(page.site + "/channels") page.wait_for_selector("#ch-new", state="attached") def _preview_ok(page): """Aperçu rendu (ou « Pas de données »), sans message d'erreur de l'éditeur.""" page.wait_for_function("""() => { const err = document.querySelector('#editor-error'); const box = document.querySelector('#preview'); return box.querySelector('svg, canvas, .chart-empty') && !document.querySelector('#preview .loading') && err.hidden; }""", timeout=20000) def _pick(page, select, value): page.select_option(select, value) page.wait_for_timeout(350) # aperçu programmé 250 ms après le dernier choix _preview_ok(page) def test_editeur_toutes_les_regles_des_axes(page): """Chaque règle des menus (évolution, un point par relevé, axes inversés, analyse thématique, deux types d'axes) donne un aperçu, sans erreur JavaScript.""" page.click("#add-chart") page.wait_for_selector("#editor[open]") _preview_ok(page) _pick(page, "#f-x-data", "evo:age") # évolution assert page.locator("#f-y-moment").input_value() == "all" page.click("#add-y") # 2e statistique en évolution page.wait_for_function("document.querySelectorAll('#f-y-more select').length === 2") _preview_ok(page) page.locator("#f-y-more button").click() # ordonnée retirée page.wait_for_timeout(350) _preview_ok(page) _pick(page, "#f-x-data", "stat:views") # un point par relevé _pick(page, "#f-x-moment", "all") _pick(page, "#f-y-data", "evo:age") # axes inversés : temps en ordonnée _pick(page, "#f-y-data", "stat:views") _pick(page, "#f-x-data", "count") # nombre de vidéos en abscisse _pick(page, "#f-y-data", "weekday") _pick(page, "#f-x-data", "theme") # analyse thématique assert page.locator("#f-y-data").input_value() == "stat:theme_rate" _pick(page, "#f-x-data", "publish_date") _pick(page, "#f-y-data", "stat:views") _pick(page, "#f-y-moment", "j7") page.click("#add-y") # deux catégories : type de l'axe de droite page.locator("#f-y-more select").first.select_option("stat:likes") page.wait_for_timeout(400) page.locator("#advanced > summary").click() page.wait_for_function("!document.querySelector('#type2-wrap').hidden") _pick(page, "#f-type", "bar") _pick(page, "#f-type2", "line") _pick(page, "#f-scale", "log") _pick(page, "#f-mshape", page.locator("#f-mshape option").nth(1).get_attribute("value")) # aucune chaîne cochée : message, pas d'aperçu boxes = page.locator("#f-channels input[type=checkbox]") for i in range(boxes.count()): boxes.nth(i).uncheck() page.wait_for_function("document.querySelector('#editor-error').textContent.includes('chaîne')") boxes.first.check() page.wait_for_timeout(350) _preview_ok(page) page.locator("#editor [data-close]").first.click() def test_editeur_agregations_mises_en_avant_et_filtres(page): page.click("#add-chart") page.wait_for_selector("#editor[open]") _preview_ok(page) box = page.locator("#f-aggs .agg-box").first box.locator(":scope > summary").click() selects = box.locator("select") selects.nth(0).select_option("median") for mode in ("year", "hours", "weeks", "months", "range", "tod", "formula", "all"): selects.nth(1).select_option(mode) page.wait_for_timeout(450) _preview_ok(page) box.locator("input[type=number]").last.fill("5") # les 5 plus récentes de chaque point page.wait_for_timeout(450) _preview_ok(page) assert "5 dernières vidéos" in box.locator(".agg-summary").text_content() # vidéo mise en avant choisie dans l'éditeur, par son rang puis par son titre page.click("#f-highlight .hl-add-btn") page.click("#f-highlight .hl-rank-row button") page.wait_for_selector("#f-highlight .hl-chip") page.click("#f-highlight .hl-add-btn") page.fill("#f-highlight .hl-search", "Short") page.wait_for_selector("#f-highlight .hl-result") page.locator("#f-highlight .hl-result").first.click() page.wait_for_function("document.querySelectorAll('#f-highlight .hl-chip').length === 2") page.locator("#f-highlight .hl-style-btn").first.click() page.locator("#f-highlight .hl-style select").first.select_option("square") page.locator("#f-highlight .hl-style-actions button").click() page.wait_for_timeout(400) _preview_ok(page) # filtres par défaut : un filtre ajouté puis effacé page.locator("#defaults-box > summary").click() page.wait_for_selector("#f-defaults .add-filter") page.locator("#f-defaults .add-filter").select_option(index=1) # ligne de filtre, sans valeur page.wait_for_timeout(400) page.locator("#f-defaults .seg-btn", has_text="Chaque vidéo").click() # réglage enregistré page.wait_for_timeout(400) _preview_ok(page) assert "(réglés)" in page.locator("#defaults-summary").text_content() page.click("#editor-save") page.wait_for_selector("#editor:not([open])", state="attached") drawn(page) # la carte reprend tout à la réouverture page.click('.card [data-action="edit"]') page.wait_for_selector("#editor[open]") page.wait_for_function("document.querySelectorAll('#f-highlight .hl-chip').length === 2") assert "(réglés)" in page.locator("#defaults-summary").text_content() page.locator("#editor [data-close]").first.click() def test_commandes_des_cartes(page): api(page, "POST", "/api/charts", {"config": {"x": "publish_date", "y": "views", "type": "line"}}) api(page, "POST", "/api/charts", {"config": {"x": "weekday", "y": "likes"}}) page.reload() page.wait_for_function("document.querySelectorAll('#charts .card .chart-box svg').length === 2", timeout=20000) card = page.locator(".card").first title = card.locator(".card-title").text_content() # Chaque vidéo / Agrégé, + Filtre, zoom vertical, réinitialiser card.locator(".seg-btn", has_text="Chaque vidéo").click() page.wait_for_timeout(600) card.locator(".add-filter").select_option(index=1) page.wait_for_timeout(600) card.locator(".y-filters input[type=number]").last.fill("10000") card.locator(".y-filters input[type=number]").last.dispatch_event("change") page.wait_for_timeout(600) assert not card.locator(".ctl-reset").is_disabled() card.locator(".ctl-reset").click() page.wait_for_timeout(600) drawn(page) # déplacer, PNG, supprimer card.locator('[data-action="down"]').click() page.wait_for_function(f"document.querySelectorAll('#charts .card .card-title')[1].textContent === {title!r}") with page.expect_download() as dl: page.locator('.card [data-action="png"]').first.click() assert dl.value.suggested_filename.endswith(".png") page.once("dialog", lambda d: d.accept()) page.locator('.card [data-action="delete"]').first.click() page.wait_for_function("document.querySelectorAll('#charts .card').length === 1")