"""Mises à jour en direct (WebSocket) et diagrammes propres à chaque compte.""" from __future__ import annotations import json import threading import time import anyio import psycopg import pytest from starlette.websockets import WebSocketDisconnect from shortstats import collector from shortstats.web.auth import hash_password from ..outils.base import add_channel from ..outils.collecte import NOW, client, iso, make_cfg from ..outils.fake_youtube import CHANNEL, OTHER, FakeYouTube from ..outils.site import ORIGIN, PASSWORD, login_as CHART = {"config": {"x": "views", "y": "likes"}} 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) 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_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", "pattern": "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.routes import realtime monkeypatch.setattr(realtime, "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_collector_announces_data(clean_db): add_channel(clean_db["web"], CHANNEL, checked=True) from datetime import timedelta 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"] 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): add_channel(clean_db["web"], CHANNEL) assert collector.verify_now(make_cfg(clean_db["collector"]), client(FakeYouTube())) == "ok" with psycopg.connect(clean_db["owner"]) as conn: title, checked = conn.execute( "SELECT youtube_title, checked_at FROM shortstats.channel").fetchone() assert title 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