"""Étapes passées sans relevé, complétées d'après la date des commentaires.""" from __future__ import annotations from datetime import datetime, timedelta, timezone import psycopg import pytest from shortstats import collector, comment_themes from shortstats.web import chart_catalog from ..outils.base import add_channel from ..outils.collecte import NOW, calls, client, insert_video, iso, make_cfg from ..outils.fake_youtube import CHANNEL, FakeYouTube from ..outils.site import CH, login, preview @pytest.fixture() def db(clean_db): with psycopg.connect(clean_db["owner"], autocommit=True) as conn: conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Frieren', ARRAY['\\yfrieren\\y'])") return clean_db def points(url, vid): """{étape: (commentaires relevés, complétée, {thème: nombre})} de toutes les étapes d'une vidéo.""" with psycopg.connect(url) as conn: rows = conn.execute( """SELECT st.label, sp.comments_read, sp.estimated, coalesce((SELECT jsonb_object_agg(t.name, sth.comments) FROM shortstats.snapshot_theme sth JOIN shortstats.theme t USING (theme_id) WHERE sth.video_id = sp.video_id AND sth.step_id = sp.step_id), '{}') FROM shortstats.step_point sp JOIN shortstats.snapshot_step st USING (step_id) WHERE sp.video_id = %s ORDER BY sp.step_id""", (vid,)).fetchall() return {r[0]: (r[1], r[2], r[3]) for r in rows} def seed_late(owner_url): """Deux vidéos de la chaîne CH : lat00000001 relevée de 1 h à 6 h, lat00000002 relevée à 6 h seulement (découverte tard) ; commentaires relevés pour les deux.""" pub = datetime(2026, 9, 1, 12, 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')", (CH,)) for vid, steps in (("lat00000001", range(1, 7)), ("lat00000002", [6])): conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, title, comments_read_at, comment_count_read, comment_scope_read) VALUES (%s, %s, %s, 'pending', %s, %s, 4, 'top')""", (vid, CH, pub, f"Vidéo {vid}", pub + timedelta(hours=6, minutes=1))) for sid in steps: conn.execute("""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count, like_count, comment_count) VALUES (%s, %s, %s, %s, 100, 10, 4)""", (vid, sid, pub + timedelta(hours=sid, minutes=1), sid + 0.02)) for i, minutes in enumerate((20, 90, 150, 330)): conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text) VALUES (%s, %s, %s, %s)""", (f"{vid}-{i}", vid, pub + timedelta(minutes=minutes), "applepie" if i % 2 == 0 else "autre chose")) comment_themes.classify(conn, [f"{v}-{i}" for v in ("lat00000001", "lat00000002") for i in range(4)]) comment_themes.refresh_videos(conn, ["lat00000001", "lat00000002"]) def test_late_video_gets_its_past_steps(db): """Vidéo découverte 5 h après sa sortie : relevé à 5 h seulement, mais les commentaires ont leur date : les étapes 1 h à 4 h sont complétées.""" url = db["collector"] add_channel(db["web"], CHANNEL, checked=True) fake = FakeYouTube() pub = NOW - timedelta(hours=5, minutes=5) fake.add_short("vid00000001", iso(pub), comments=3, listed=False) insert_video(db["owner"], "vid00000001", pub) fake.add_comment("vid00000001", "c1", "Frieren !", iso(pub + timedelta(minutes=30))) fake.add_comment("vid00000001", "c2", "rien", iso(pub + timedelta(hours=2, minutes=30))) fake.add_comment("vid00000001", "c3", "frieren encore", iso(pub + timedelta(hours=4, minutes=30))) res = collector.run(make_cfg(url), client(fake), now=NOW) assert (res.snapshots, res.comments_read) == (1, 3) assert points(url, "vid00000001") == { "1 h": (1, True, {"Frieren": 1}), "2 h": (1, True, {"Frieren": 1}), "3 h": (2, True, {"Frieren": 1}), "4 h": (2, True, {"Frieren": 1}), "5 h": (3, False, {"Frieren": 2})} with psycopg.connect(url) as conn: est = conn.execute("""SELECT step_id, taken_at, age_hours FROM shortstats.comment_estimate WHERE video_id = 'vid00000001' ORDER BY step_id""").fetchall() assert [(s, t - pub, float(a)) for s, t, a in est] == [(i, timedelta(hours=i), float(i)) for i in range(1, 5)] # vues et likes : toujours inconnus aux étapes complétées with psycopg.connect(url) as conn: assert conn.execute("""SELECT count(*) FROM shortstats.step_point WHERE estimated AND (view_count IS NOT NULL OR like_count IS NOT NULL)""").fetchone()[0] == 0 # un thème ajouté ensuite s'applique aussi aux étapes complétées with psycopg.connect(db["web"], autocommit=True) as conn: tid = conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Rien', ARRAY['rien']) " "RETURNING theme_id").fetchone()[0] with conn.transaction(): comment_themes.lock(conn) comment_themes.refresh_theme(conn, tid) assert points(url, "vid00000001")["3 h"] == (2, True, {"Frieren": 1, "Rien": 1}) assert points(url, "vid00000001")["2 h"] == (1, True, {"Frieren": 1}) def test_real_snapshot_replaces_completed_step(db): """Étape complétée (commentaires relevés après son heure) puis relevée dans sa tolérance : le relevé remplace l'étape complétée.""" url = db["collector"] add_channel(db["web"], CHANNEL, checked=True) fake = FakeYouTube() pub = NOW - timedelta(hours=6, minutes=10) fake.add_short("vid00000001", iso(pub), comments=1, listed=False) insert_video(db["owner"], "vid00000001", pub) with psycopg.connect(db["owner"], autocommit=True) as conn: conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text) VALUES ('c1', 'vid00000001', %s, 'frieren')""", (pub + timedelta(minutes=30),)) conn.execute("""UPDATE shortstats.video SET snapshot_step = 5, next_step = 6, next_snapshot_at = %s, comment_count_latest = 1, comment_count_read = 1, comments_read_at = %s, comment_scope_read = 'top' WHERE video_id = 'vid00000001'""", (pub + timedelta(hours=6), NOW - timedelta(minutes=5))) comment_themes.classify(conn, ["c1"]) comment_themes.refresh_videos(conn, ["vid00000001"]) before = points(url, "vid00000001") assert list(before) == ["1 h", "2 h", "3 h", "4 h", "5 h", "6 h"] and before["6 h"] == (1, True, {"Frieren": 1}) with psycopg.connect(url, autocommit=True) as conn: assert collector.take_snapshots(conn, client(fake), now=NOW) == 1 after = points(url, "vid00000001") assert after["6 h"] == (1, False, {"Frieren": 1}) assert {k: v for k, v in after.items() if k != "6 h"} == {k: v for k, v in before.items() if k != "6 h"} with psycopg.connect(url) as conn: assert conn.execute("SELECT count(*) FROM shortstats.comment_estimate WHERE step_id = 6").fetchone()[0] == 0 def test_video_without_comments_counts_zero_everywhere(db): url = db["collector"] add_channel(db["web"], CHANNEL, checked=True) fake = FakeYouTube() pub = NOW - timedelta(hours=3, minutes=5) fake.add_short("vid00000001", iso(pub), comments=0, listed=False) insert_video(db["owner"], "vid00000001", pub) res = collector.run(make_cfg(url), client(fake), now=NOW) assert res.comment_units == 0 and calls(fake, "commentThreads") == [] assert points(url, "vid00000001") == {"1 h": (0, True, {}), "2 h": (0, True, {}), "3 h": (0, False, {})} def test_charts_use_completed_steps(app_client, clean_db): seed_late(clean_db["owner"]) login(app_client) # évolution : à 2 h, les deux vidéos comptent (lat00000002 par son étape complétée) out = preview(app_client, {"source": "evolution", "x": "age", "y": "comments_read", "agg": "mean", "split_channels": False}) by = {r["lab"]: r for r in out["spec"]["data"]["values"]} assert by["2 h"]["n"] == 2 and by["2 h"]["y"] == 2 and by["6 h"]["n"] == 2 and by["6 h"]["y"] == 4 assert chart_catalog.COMMENT_STEPS_NOTE in out["explanation"] assert "relevé(s) ou étape(s) complétée(s)" in out["explanation"] rate = preview(app_client, {"source": "evolution", "x": "age", "y": "theme_rate", "agg": "mean", "split_channels": False}, {"filters": {"theme": {"in": ["applepie"]}}}) r3 = [r for r in rate["spec"]["data"]["values"] if r["lab"] == "3 h"][0] assert r3["n"] == 2 and abs(r3["y"] - 100 * 2 / 3) < 0.001 # 2 « applepie » sur 3 commentaires assert "pour 1 thème(s)" in rate["explanation"] # mesure des commentaires à une étape, par vidéo : lat00000002 n'a pas de relevé à 2 h j7 = preview(app_client, {"x": "theme", "y": "theme_rate@2", "split_channels": False}) got = {(r["id"], r["x"]): r["y"] for r in j7["spec"]["data"]["values"]} assert got == {("lat00000001", "applepie"): 50, ("lat00000002", "applepie"): 50, ("lat00000001", "Apothecary Diaries"): 0, ("lat00000002", "Apothecary Diaries"): 0} assert chart_catalog.COMMENT_STEPS_NOTE in j7["explanation"] and "2 vidéo(s)" in j7["explanation"] # les vues restent celles des seuls relevés views = preview(app_client, {"source": "evolution", "x": "age", "y": "views", "agg": "mean", "split_channels": False}) assert {r["lab"]: r["n"] for r in views["spec"]["data"]["values"]}["2 h"] == 1 assert chart_catalog.COMMENT_STEPS_NOTE not in views["explanation"] # page Vidéos : détail des étapes, complétées comprises rows = app_client.get("/api/videos/lat00000002/snapshots").json() assert [(r["step"], r["estimated"], r["comments_read"]) for r in rows] == [ ("1 h", True, 1), ("2 h", True, 2), ("3 h", True, 3), ("4 h", True, 3), ("5 h", True, 3), ("6 h", False, 4)] assert rows[0]["views"] is None and rows[5]["views"] == 100