shortstats/tests/test_web.py
ploush 8481edf66e
All checks were successful
build / test (push) Successful in 6m34s
build / images (collector) (push) Successful in 20s
build / images (web) (push) Successful in 23s
upgrade 1.3.1
2026-11-07 01:44:37 +01:00

367 lines
18 KiB
Python

from datetime import datetime, timedelta, timezone
import psycopg
import pytest
from fastapi.testclient import TestClient
from shortstats.config import WebConfig
from shortstats.web.app import create_app
from shortstats.web.auth import hash_password
ORIGIN = "http://testserver"
CH = "UC" + "a" * 22
OTHER = "UC" + "b" * 22
PASSWORD = "un-mot-de-passe-solide"
@pytest.fixture()
def users_file(tmp_path):
path = tmp_path / "users.txt"
path.write_text(f"# comptes\nalice:{hash_password(PASSWORD)}\nligne invalide\n")
return path
@pytest.fixture()
def app_client(clean_db, users_file):
cfg = WebConfig(database_url=clean_db["web"], secret_key="x" * 40, users_file=str(users_file),
session_max_age_s=3600, cookie_secure=False, login_max_failures=3, login_lock_minutes=15)
with TestClient(create_app(cfg), base_url=ORIGIN) as client:
yield client
def login(client, password=PASSWORD, origin=ORIGIN):
return client.post("/login", data={"username": "alice", "password": password},
headers={"Origin": origin}, follow_redirects=False)
def seed_videos(owner_url, n=30):
base = datetime(2026, 9, 1, 17, 0, tzinfo=timezone.utc)
with psycopg.connect(owner_url, autocommit=True) as conn:
conn.execute("""INSERT INTO shortstats.channel (channel_id, youtube_title)
VALUES (%s, 'Ma chaîne') ON CONFLICT DO NOTHING""", (CH,))
for i in range(n):
conn.execute(
"""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, collected_at, title,
duration_s, view_count, like_count, comment_count)
VALUES (%s, %s, %s, 'collected', now(), %s, %s, %s, %s, %s)""",
(f"vid{i:08d}", CH, base + timedelta(days=i, hours=i % 5), f"<b>Short {i}</b>",
30 + i, 1000 * (i + 1), 40 * (i + 1), 5 + i),
)
# Commentaires de seed_comments : (texte, thèmes du jeu de test « Apothecary Diaries » et « applepie »).
COMMENT_TEXTS = ["Apothecary Diaries saison 2", "une applepie", "rien", "APOTHECARY DIARIES et applepie"]
def seed_comments(owner_url, n=30):
"""Pour les vidéos de seed_videos : un relevé à 7 j, et 2 + (i % 4) commentaires relevés
(publiés avant le relevé), classés par thème comme le ferait le collecteur."""
from shortstats import comment_themes
base = datetime(2026, 9, 1, 17, 0, tzinfo=timezone.utc)
vids, ids = [], []
with psycopg.connect(owner_url, autocommit=True) as conn:
for i in range(n):
vid = f"vid{i:08d}"
published = base + timedelta(days=i, hours=i % 5)
taken = published + timedelta(hours=168)
conn.execute(
"""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count,
like_count, comment_count)
VALUES (%s, 56, %s, 168, %s, %s, %s)""", (vid, taken, 1000 * (i + 1), 40 * (i + 1), 5 + i))
for k in range(2 + i % 4):
cid = f"{vid}-c{k}"
conn.execute(
"""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text)
VALUES (%s, %s, %s, %s)""",
(cid, vid, published + timedelta(hours=k + 1), COMMENT_TEXTS[(i + k) % 4]))
ids.append(cid)
conn.execute("""UPDATE shortstats.video SET comments_read_at = %s, comment_count_read = %s,
comment_count_latest = %s, comment_scope_read = 'top'
WHERE video_id = %s""", (taken, 5 + i, 5 + i, vid))
vids.append(vid)
comment_themes.classify(conn, ids)
comment_themes.refresh_videos(conn, vids)
def test_pages_require_login(app_client):
r = app_client.get("/", follow_redirects=False)
assert r.status_code == 303 and r.headers["location"] == "/login"
assert app_client.get("/api/charts").status_code == 401
assert app_client.get("/videos", follow_redirects=False).status_code == 303
def test_healthz_and_security_headers(app_client):
r = app_client.get("/healthz")
assert r.json() == {"status": "ok"}
r = app_client.get("/login")
assert "script-src 'self'" in r.headers["content-security-policy"]
assert r.headers["x-frame-options"] == "DENY"
assert r.headers["cache-control"] == "no-store"
def test_login_logout_flow(app_client):
assert "incorrect" in login(app_client, password="mauvais").text
r = login(app_client)
assert r.status_code == 303 and r.headers["location"] == "/"
cookie = r.headers["set-cookie"].lower()
assert "httponly" in cookie and "samesite=strict" in cookie
assert app_client.get("/").status_code == 200
app_client.post("/logout", headers={"Origin": ORIGIN})
assert app_client.get("/api/charts").status_code == 401
def test_login_rejects_foreign_origin(app_client):
r = login(app_client, origin="https://evil.example")
assert r.status_code == 403
def test_throttle_after_failures(app_client):
for _ in range(3):
login(app_client, password="mauvais")
r = login(app_client) # bon mot de passe, mais compte bloqué
assert "Trop d&#39;essais" in r.text
def test_removing_user_revokes_session(app_client, users_file):
login(app_client)
assert app_client.get("/api/charts").status_code == 200
users_file.write_text("# plus personne\n")
import os
os.utime(users_file, (1, 1)) # forcer une date de modification différente
assert app_client.get("/api/charts").status_code == 401
def test_chart_crud_and_render(app_client, clean_db):
seed_videos(clean_db["owner"])
seed_comments(clean_db["owner"])
login(app_client)
h = {"Origin": ORIGIN}
cfg = {"x": "weekday", "y": "views", "type": "auto", "agg": "auto", "color": None, "scale": "auto", "title": ""}
r = app_client.post("/api/charts", json={"config": cfg}, headers=h)
assert r.status_code == 201
chart_id = r.json()["id"]
# « Thème » seul (sans mesure de thème) : refusé, avec la raison
r = app_client.post("/api/charts", json={"config": {**cfg, "x": "theme", "y": "count"}}, headers=h)
assert r.status_code == 400 and "mesure de thème" in r.json()["error"]
r2 = app_client.post("/api/charts", json={"config": {**cfg, "x": "theme", "y": "theme_rate@56"}}, headers=h)
second = r2.json()["id"]
out = app_client.get(f"/api/charts/{chart_id}/render").json()
assert out["n"] == 30 and out["spec"]["mark"]["type"] in {"boxplot", "bar"}
themes = {v["x"] for v in app_client.get(f"/api/charts/{second}/render").json()["spec"]["data"]["values"]}
assert themes == {"Apothecary Diaries", "applepie"}
assert app_client.post(f"/api/charts/{second}/move", json={"direction": -1}, headers=h).status_code == 204
assert [c["id"] for c in app_client.get("/api/charts").json()] == [second, chart_id]
r = app_client.put(f"/api/charts/{chart_id}", json={"config": {**cfg, "type": "heatmap", "y": "count"}}, headers=h)
assert r.status_code == 400 and "impossible" in r.json()["error"]
assert app_client.delete(f"/api/charts/{chart_id}", headers=h).status_code == 204
assert app_client.delete(f"/api/charts/{chart_id}", headers=h).status_code == 404
def test_api_requires_json_and_same_origin(app_client):
login(app_client)
cfg = {"x": "views", "y": "likes"}
assert app_client.post("/api/charts", json={"config": cfg}).status_code == 403 # sans Origin
r = app_client.post("/api/charts", data={"config": "x"}, headers={"Origin": ORIGIN})
assert r.status_code == 400
def test_preview_and_compat(app_client, clean_db):
seed_videos(clean_db["owner"])
login(app_client)
r = app_client.post("/api/preview", json={"config": {"x": "views", "y": "likes"}}, headers={"Origin": ORIGIN})
assert r.json()["resolved"]["type"] == "scatter"
compat = app_client.get("/api/compat?x=views&y=count").json()
assert compat["histogram"] is None and compat["scatter"]
def test_themes_page_and_crud(app_client, clean_db):
seed_videos(clean_db["owner"])
seed_comments(clean_db["owner"])
login(app_client)
h = {"Origin": ORIGIN}
r = app_client.post("/themes", data={"name": "Saison", "pattern": ["saison 2", "saison deux", ""]}, headers=h,
follow_redirects=False)
assert r.headers["location"] == "/themes?msg=created"
page = app_client.get("/themes").text
assert "Saison" in page and 'value="saison 2"' in page and 'value="saison deux"' in page
# comptes : commentaires reconnus et vidéos concernées (« saison 2 » : 1 commentaire sur 4 environ)
with psycopg.connect(clean_db["owner"]) as conn:
n = conn.execute("""SELECT count(*), count(DISTINCT c.video_id) FROM shortstats.comment c
WHERE c.text ~* 'saison (2|deux)'""").fetchone()
stored = conn.execute("""SELECT count(*) FROM shortstats.comment_theme ct JOIN shortstats.theme t
USING (theme_id) WHERE t.name = 'Saison'""").fetchone()[0]
assert n[0] > 0 and stored == n[0]
assert f"{n[0]} commentaire(s) dans {n[1]} vidéo(s)" in page
# doublon de nom : page réaffichée avec la saisie
r = app_client.post("/themes", data={"name": "Saison", "pattern": "x"}, headers=h, follow_redirects=False)
assert r.status_code == 400 and "Un thème porte déjà ce nom." in r.text
r = app_client.post("/themes", data={"name": "", "pattern": "x"}, headers=h, follow_redirects=False)
assert r.status_code == 400 and "Nom du thème" in r.text
r = app_client.post("/themes", data={"name": "Vide", "pattern": ["", " "]}, headers=h, follow_redirects=False)
assert r.status_code == 400 and "Au moins une expression régulière" in r.text
def test_video_titles_are_escaped(app_client, clean_db):
seed_videos(clean_db["owner"], n=3)
login(app_client)
html = app_client.get("/videos").text
assert "&lt;b&gt;Short 0&lt;/b&gt;" in html and "<b>Short 0</b>" not in html
def channels_in_db(owner_url):
with psycopg.connect(owner_url) as conn:
return {r[0]: r[1:] for r in conn.execute(
"SELECT channel_id, comment_scope, active, youtube_title, checked_at FROM shortstats.channel")}
def test_channel_management(app_client, clean_db):
login(app_client)
h = {"Origin": ORIGIN}
def post(path, data):
return app_client.post(path, data=data, headers=h, follow_redirects=False).headers["location"]
third = "UC" + "c" * 22
# Ajout : commentaires de 1er niveau par défaut, ou avec les réponses
assert post("/channels", {"channel": CH}) == "/channels?msg=created"
assert post("/channels", {"channel": f"https://www.youtube.com/channel/{third}/shorts",
"comment_scope": "all"}) == "/channels?msg=created"
fourth = "UC" + "e" * 22
assert post("/channels", {"channel": fourth, "comment_scope": "n'importe quoi"}) == "/channels?msg=created"
rows = channels_in_db(clean_db["owner"])
assert (rows[CH][:2], rows[third][:2], rows[fourth][:2]) == (("top", True), ("all", True), ("top", True))
post(f"/channels/{fourth}/delete", {})
# Erreurs de saisie
assert post("/channels", {"channel": CH}) == "/channels?msg=duplicate"
assert post("/channels", {"channel": "@machaine"}) == "/channels?msg=handle"
assert post("/channels", {"channel": "https://www.youtube.com/@machaine"}) == "/channels?msg=handle"
assert post("/channels", {"channel": "UC123"}) == "/channels?msg=invalid_channel"
# Changer les commentaires relevés ou mettre en pause ne relance pas la vérification
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("UPDATE shortstats.channel SET checked_at = now(), youtube_title = 'Nom vérifié'")
assert post(f"/channels/{CH}", {"comment_scope": "all", "active": "on"}) == "/channels?msg=updated"
assert post(f"/channels/{third}", {"comment_scope": "top"}) == "/channels?msg=updated" # case décochée
rows = channels_in_db(clean_db["owner"])
assert rows[CH][:3] == ("all", True, "Nom vérifié") and rows[CH][3] is not None
assert rows[third][:3] == ("top", False, "Nom vérifié") and rows[third][3] is not None
# Réactiver une chaîne relance sa vérification
post(f"/channels/{third}", {"comment_scope": "top", "active": "on"})
assert channels_in_db(clean_db["owner"])[third][3] is None
# Page : identifiants, état, réglage des commentaires ; plus de commentaire épinglé
page = app_client.get("/channels").text
assert third in page and "vérification en cours" in page
assert "épinglé" not in page and 'name="author"' not in page
assert '<option value="all" selected>1er niveau + réponses</option>' in page
assert '<option value="top" selected>1er niveau</option>' in page
assert f'href="https://www.youtube.com/channel/{third}/shorts"' in page
# Suppression : refusée si des vidéos existent, acceptée sinon
seed_videos(clean_db["owner"], n=2)
assert post(f"/channels/{CH}/delete", {}) == "/channels?msg=has_videos"
assert post(f"/channels/{third}/delete", {}) == "/channels?msg=deleted"
assert post("/channels/pas-un-id/delete", {}) == "/channels?msg=missing"
assert set(channels_in_db(clean_db["owner"])) == {CH}
def test_channel_field_in_charts_and_dashboard_banner(app_client, clean_db):
login(app_client)
assert "Aucune chaîne suivie" in app_client.get("/").text
seed_videos(clean_db["owner"], n=6)
out = app_client.post("/api/preview", json={"config": {"x": "channel", "y": "views"}},
headers={"Origin": ORIGIN}).json()
assert {v["x"] for v in out["spec"]["data"]["values"]} == {"Ma chaîne"}
assert "Aucune chaîne suivie" not in app_client.get("/").text
# -- v1.1.0 : changement de mot de passe -----------------------------------------
NEW_PASSWORD = "un-autre-mot-de-passe-long"
def change(client, current, new, confirm=None):
r = client.post("/account/password", headers={"Origin": ORIGIN}, follow_redirects=False,
data={"current": current, "new": new, "confirm": new if confirm is None else confirm})
return r.headers["location"]
def test_account_page_requires_login(app_client):
assert app_client.get("/account", follow_redirects=False).headers["location"] == "/login"
r = app_client.post("/account/password", headers={"Origin": ORIGIN},
data={"current": PASSWORD, "new": NEW_PASSWORD, "confirm": NEW_PASSWORD},
follow_redirects=False)
assert r.headers["location"] == "/login"
def test_change_password_validation(app_client):
login(app_client)
assert "Changer de mot de passe" in app_client.get("/account").text
assert change(app_client, "mauvais", NEW_PASSWORD) == "/account?msg=wrong_current"
assert change(app_client, PASSWORD, "court") == "/account?msg=too_short"
assert change(app_client, PASSWORD, NEW_PASSWORD, confirm="autre-chose-long") == "/account?msg=mismatch"
assert change(app_client, PASSWORD, PASSWORD) == "/account?msg=unchanged"
# Aucune de ces tentatives n'a changé le mot de passe.
app_client.post("/logout", headers={"Origin": ORIGIN})
assert login(app_client).headers["location"] == "/"
def test_change_password_flow(app_client, clean_db, users_file):
other = TestClient(app_client.app, base_url=ORIGIN) # 2e navigateur de la même personne
login(app_client)
login(other)
assert other.get("/api/charts").status_code == 200
assert change(app_client, PASSWORD, NEW_PASSWORD) == "/account?msg=changed"
# La session courante reste ouverte, l'autre est fermée.
assert app_client.get("/api/charts").status_code == 200
assert other.get("/api/charts").status_code == 401
# Ancien mot de passe refusé, nouveau accepté.
assert "incorrect" in login(other, password=PASSWORD).text
assert login(other, password=NEW_PASSWORD).headers["location"] == "/"
# Le haché est en base, users.txt n'a pas été modifié.
with psycopg.connect(clean_db["owner"]) as conn:
row = conn.execute("SELECT password_hash FROM shortstats.user_password WHERE username = 'alice'").fetchone()
assert row and row[0].startswith("$argon2id$")
assert "alice:" in users_file.read_text() and row[0] not in users_file.read_text()
def test_admin_reset_in_file_overrides_changed_password(app_client, users_file):
"""Mot de passe oublié : l'administrateur remplace la ligne de users.txt, qui reprend la main."""
import os
login(app_client)
assert change(app_client, PASSWORD, NEW_PASSWORD) == "/account?msg=changed"
reset = "mot-de-passe-de-secours"
users_file.write_text(f"alice:{hash_password(reset)}\n")
os.utime(users_file, (2, 2))
assert app_client.get("/api/charts").status_code == 401 # sessions fermées
assert "incorrect" in login(app_client, password=NEW_PASSWORD).text
assert login(app_client, password=reset).headers["location"] == "/"
def test_removed_user_cannot_use_changed_password(app_client, users_file):
import os
login(app_client)
change(app_client, PASSWORD, NEW_PASSWORD)
users_file.write_text("# plus personne\n")
os.utime(users_file, (3, 3))
assert app_client.get("/api/charts").status_code == 401
assert "incorrect" in login(app_client, password=NEW_PASSWORD).text
def test_change_password_is_throttled(app_client):
login(app_client)
for _ in range(3): # LOGIN_MAX_FAILURES = 3 dans la fixture
change(app_client, "mauvais", NEW_PASSWORD)
assert change(app_client, PASSWORD, NEW_PASSWORD) == "/account?msg=throttled"
def test_change_password_rejects_foreign_origin(app_client):
login(app_client)
r = app_client.post("/account/password", headers={"Origin": "https://evil.example"},
data={"current": PASSWORD, "new": NEW_PASSWORD, "confirm": NEW_PASSWORD})
assert r.status_code == 403