shortstats/tests/test_live.py
ploush d5312c3667
Some checks failed
build / test (push) Failing after 1m3s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
Upgrade 1.1.0
2026-11-01 13:47:38 +01:00

220 lines
9.2 KiB
Python

"""Temps réel (WebSocket), diagrammes personnels, vérification immédiate des chaînes."""
import json
import threading
import time
import anyio
import psycopg
import pytest
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from shortstats import collector
from shortstats.config import WebConfig
from shortstats.web import live
from shortstats.web.app import create_app
from shortstats.web.auth import hash_password
from .fake_youtube import CHANNEL, OTHER, FakeYouTube
from .test_collector import NOW, client, make_cfg
ORIGIN = "http://testserver"
PASSWORD = "un-mot-de-passe-solide"
CHART = {"config": {"x": "views", "y": "likes"}}
@pytest.fixture()
def two_users(clean_db, tmp_path):
path = tmp_path / "users.txt"
path.write_text(f"alice:{hash_password(PASSWORD)}\nbob:{hash_password(PASSWORD)}\n")
cfg = WebConfig(database_url=clean_db["web"], secret_key="x" * 40, users_file=str(path),
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 c:
yield c
def login_as(c, user):
c.post("/logout", headers={"Origin": ORIGIN})
r = c.post("/login", data={"username": user, "password": PASSWORD}, headers={"Origin": ORIGIN},
follow_redirects=False)
assert r.status_code == 303 and r.headers["location"] == "/"
def recv(ws, timeout=5.0):
"""Prochain événement (hors « resync »), ou None si rien n'arrive à temps."""
async def _next():
with anyio.fail_after(timeout):
return await ws._send_rx.receive()
while True:
try:
msg = ws.portal.call(_next)
except TimeoutError:
return None
if msg["type"] != "websocket.send":
return msg
data = json.loads(msg["text"])
if data["type"] != "resync":
return data
def post(c, url, **kw):
return c.post(url, headers={"Origin": ORIGIN}, follow_redirects=False, **kw)
# -- diagrammes personnels ---------------------------------------------------
def test_charts_are_personal(two_users):
c = two_users
login_as(c, "alice")
a1 = post(c, "/api/charts", json=CHART).json()["id"]
a2 = post(c, "/api/charts", json=CHART).json()["id"]
login_as(c, "bob")
assert c.get("/api/charts").json() == []
b1 = post(c, "/api/charts", json=CHART).json()["id"]
assert [ch["id"] for ch in c.get("/api/charts").json()] == [b1]
# rien de ce qui appartient à alice n'est accessible à bob
assert c.get(f"/api/charts/{a1}/render").status_code == 404
assert c.put(f"/api/charts/{a1}", json=CHART, headers={"Origin": ORIGIN}).status_code == 404
assert c.delete(f"/api/charts/{a1}", headers={"Origin": ORIGIN}).status_code == 404
assert post(c, f"/api/charts/{a1}/move", json={"direction": 1}).status_code == 404
login_as(c, "alice")
assert [ch["id"] for ch in c.get("/api/charts").json()] == [a1, a2]
assert post(c, f"/api/charts/{a2}/move", json={"direction": -1}).status_code == 204
assert [ch["id"] for ch in c.get("/api/charts").json()] == [a2, a1]
def test_migration_renumbers_positions_per_owner(clean_db):
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
assert conn.execute("SELECT 1 FROM pg_indexes WHERE indexname = 'chart_owner_idx'").fetchone()
# -- WebSocket ----------------------------------------------------------------
def test_ws_requires_session_and_same_origin(two_users):
c = two_users
with pytest.raises(WebSocketDisconnect):
with c.websocket_connect("/ws", headers={"Origin": ORIGIN}):
pass
login_as(c, "alice")
with pytest.raises(WebSocketDisconnect):
with c.websocket_connect("/ws", headers={"Origin": "https://evil.example"}):
pass
with c.websocket_connect("/ws", headers={"Origin": ORIGIN}) as ws:
post(c, "/channels", data={"channel": CHANNEL, "author": OTHER})
assert recv(ws) == {"type": "channels"}
def test_ws_events_reach_the_right_people(two_users, clean_db):
c = two_users
login_as(c, "alice")
with c.websocket_connect("/ws", headers={"Origin": ORIGIN}) as ws_alice:
login_as(c, "bob")
with c.websocket_connect("/ws", headers={"Origin": ORIGIN}) as ws_bob:
# diagramme de bob : seul bob est prévenu
post(c, "/api/charts", json=CHART)
assert recv(ws_bob) == {"type": "charts"}
# chaîne ajoutée : commune, tout le monde est prévenu (et rien d'autre avant pour alice)
post(c, "/channels", data={"channel": CHANNEL, "author": OTHER})
assert recv(ws_alice) == {"type": "channels"}
assert recv(ws_bob) == {"type": "channels"}
# thème modifié : les données changent pour tout le monde
post(c, "/themes", data={"name": "Nouveau", "keywords": "mot"})
assert recv(ws_alice) == {"type": "data"}
assert recv(ws_bob) == {"type": "data"}
# demande de collecte puis collecte : « run » puis « run » et « channels »
assert post(c, "/api/collect").status_code == 202
assert recv(ws_alice) == {"type": "run"}
collector.run(make_cfg(clean_db["collector"]), client(FakeYouTube()), now=NOW)
got = [recv(ws_alice) for _ in range(3)]
assert got == [{"type": "run"}, {"type": "run"}, {"type": "channels"}]
def test_ws_closed_when_user_removed(two_users, monkeypatch, tmp_path):
from shortstats.web import app as app_module
monkeypatch.setattr(app_module, "WS_SESSION_CHECK_S", 0.2) # lu à chaque vérification
c = two_users
login_as(c, "alice")
cfg_path = tmp_path / "users.txt" # le fichier de la fixture
with c.websocket_connect("/ws", headers={"Origin": ORIGIN}) as ws:
cfg_path.write_text(f"bob:{hash_password(PASSWORD)}\n") # alice retirée du fichier
time.sleep(0.05)
msg = recv(ws, timeout=5)
assert msg is not None and msg["type"] == "websocket.close" and msg["code"] == 4401
def test_parse_event_rejects_unknown():
assert live.parse_event('{"type": "run"}') == {"type": "run"}
assert live.parse_event('{"type": "charts", "user": "alice"}')["user"] == "alice"
for bad in ("x", "[]", '{"type": "autre"}', '{"type": "charts", "user": 3}'):
assert live.parse_event(bad) is None
def test_collector_announces_data(clean_db):
from .conftest import add_channel
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True)
from datetime import timedelta
from .test_collector import iso
fake = FakeYouTube()
fake.add_short("vid00000001", iso(NOW - timedelta(days=2)), title="Récent") # découvert
with psycopg.connect(clean_db["web"], autocommit=True) as conn:
conn.execute("LISTEN shortstats_events")
collector.run(make_cfg(clean_db["collector"]), client(fake), now=NOW)
kinds = [json.loads(n.payload)["type"] for n in conn.notifies(timeout=2, stop_after=3)]
assert kinds == ["run", "run", "data"]
# -- vérification immédiate --------------------------------------------------
def test_watch_verifies_new_channel_immediately(two_users, clean_db):
calls = []
stop = threading.Event()
def fake_verify(cfg):
calls.append(time.monotonic())
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("UPDATE shortstats.channel SET checked_at = now()")
return "ok"
t = threading.Thread(target=collector.watch, args=(make_cfg(clean_db["collector"]),),
kwargs={"poll_s": 30, "stop": stop, "verify_fn": fake_verify}, daemon=True)
t.start()
time.sleep(0.5)
login_as(two_users, "alice")
sent = time.monotonic()
post(two_users, "/channels", data={"channel": CHANNEL, "author": OTHER})
deadline = time.monotonic() + 5
while not calls and time.monotonic() < deadline:
time.sleep(0.05)
stop.set()
assert calls and calls[0] - sent < 3
def test_verify_now_fills_names_and_backs_off_on_error(clean_db):
from .conftest import add_channel
add_channel(clean_db["web"], CHANNEL, author_id=OTHER)
assert collector.verify_now(make_cfg(clean_db["collector"]), client(FakeYouTube())) == "ok"
with psycopg.connect(clean_db["owner"]) as conn:
title, author, checked = conn.execute(
"SELECT youtube_title, author_title, checked_at FROM shortstats.channel").fetchone()
assert title and author and checked
calls = []
stop = threading.Event()
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("UPDATE shortstats.channel SET checked_at = NULL")
def failing(cfg):
calls.append(1)
return "error"
t = threading.Thread(target=collector.watch, args=(make_cfg(clean_db["collector"]),),
kwargs={"poll_s": 0.2, "stop": stop, "verify_fn": failing}, daemon=True)
t.start()
time.sleep(1.5)
assert calls == [1] # pas de nouvel essai toutes les 0,2 s après un échec
with psycopg.connect(clean_db["web"], autocommit=True) as conn:
conn.execute("SELECT pg_notify('shortstats_collect', 'verify')") # nouvelle saisie sur le site
time.sleep(1)
stop.set()
assert len(calls) == 2