"""Relevés successifs : calendrier, tolérance, lots, fin du suivi, droits.""" from __future__ import annotations from datetime import timedelta import psycopg import pytest from shortstats import collector from shortstats.web import chart_catalog from ..outils.base import add_channel from ..outils.collecte import NOW, client, iso, make_cfg from ..outils.fake_youtube import CHANNEL, FakeYouTube def insert_video(url, vid, age, status="pending"): with psycopg.connect(url, autocommit=True) as conn: conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status) VALUES (%s, %s, %s, %s)""", (vid, CHANNEL, NOW - age, status)) def snaps(url, vid): with psycopg.connect(url) as conn: return conn.execute( """SELECT st.label, sn.age_hours::float, sn.view_count FROM shortstats.video_snapshot sn JOIN shortstats.snapshot_step st USING (step_id) WHERE video_id = %s ORDER BY step_id""", (vid,)).fetchall() def stat_calls(fake): return [c for c in fake.calls if c[0] == "videos" and c[1].get("part") == "snippet,statistics"] @pytest.fixture() def setup(clean_db): add_channel(clean_db["web"], CHANNEL, checked=True) fake = FakeYouTube() return clean_db, fake def test_schedule(clean_db): with psycopg.connect(clean_db["web"]) as conn: rows = conn.execute("SELECT label, nominal_hours, age::text FROM shortstats.snapshot_step ORDER BY step_id").fetchall() labels = [r[0] for r in rows] assert len(rows) == 151 assert labels[:24] == [f"{h} h" for h in range(1, 25)] assert labels[24:27] == ["1 j 3 h", "1 j 6 h", "1 j 9 h"] and labels[39] == "3 j" assert labels[40:42] == ["3 j 6 h", "3 j 12 h"] and labels[55] == "7 j" assert labels[56] == "8 j" and labels[78] == "30 j" assert labels[79] == "5 sem." and labels[126] == "52 sem." assert labels[127] == "13 mois" and labels[-1] == "36 mois" hours = [float(r[1]) for r in rows] assert hours == sorted(hours) assert str(rows[-1][2]) == "3 years" def test_hourly_steps_and_skips(setup): db, fake = setup url = db["collector"] fake.add_short("traj0000001", iso(NOW - timedelta(hours=1, minutes=5)), views=100, listed=False) insert_video(db["owner"], "traj0000001", timedelta(hours=1, minutes=5)) assert collector.take_snapshots(psycopg.connect(url, autocommit=True), client(fake), NOW) == 1 assert snaps(url, "traj0000001") == [("1 h", pytest.approx(1.08, abs=0.01), 100)] # même passage relancé : rien de nouveau with psycopg.connect(url, autocommit=True) as conn: assert collector.take_snapshots(conn, client(fake), NOW + timedelta(minutes=10)) == 0 # collecteur arrêté 4 h : on relève l'étape 5 h, sans inventer 2 h, 3 h ni 4 h fake.videos["traj0000001"]["statistics"]["viewCount"] = "900" assert collector.take_snapshots(conn, client(fake), NOW + timedelta(hours=4)) == 1 got = snaps(url, "traj0000001") assert [g[0] for g in got] == ["1 h", "5 h"] and got[1][2] == 900 def test_tolerance_and_old_videos(setup): db, fake = setup url = db["collector"] # Short ancien (découvert à plus de 7 jours) : suivi pour ses étapes à venir seulement. fake.add_short("old00000001", iso(NOW - timedelta(days=47)), listed=False) insert_video(db["owner"], "old00000001", timedelta(days=47), status="too_old") # Pas un Short : jamais suivi. fake.add_short("long0000001", iso(NOW - timedelta(hours=1, minutes=5)), listed=False) insert_video(db["owner"], "long0000001", timedelta(hours=1, minutes=5), status="not_short") with psycopg.connect(url, autocommit=True) as conn: # 47 j : l'étape « 6 sem. » (42 j) est échue depuis 5 j, au-delà de 10 % : ignorée assert collector.take_snapshots(conn, client(fake), NOW) == 0 # à 49 j + 1 h : « 7 sem. » relevée assert collector.take_snapshots(conn, client(fake), NOW + timedelta(days=2, hours=1)) == 1 assert [s[0] for s in snaps(url, "old00000001")] == ["7 sem."] assert snaps(url, "long0000001") == [] def test_batches_of_50_cost_one_unit_each(setup): db, fake = setup for i in range(60): vid = f"batch{i:06d}" fake.add_short(vid, iso(NOW - timedelta(hours=3, minutes=10)), listed=False) insert_video(db["owner"], vid, timedelta(hours=3, minutes=10)) c = client(fake) with psycopg.connect(db["collector"], autocommit=True) as conn: assert collector.take_snapshots(conn, c, NOW) == 60 assert len(stat_calls(fake)) == 2 and c.quota_used == 2 def test_missing_video_stops_after_three_misses(setup): db, fake = setup url = db["collector"] insert_video(db["owner"], "gone0000001", timedelta(hours=1, minutes=5)) with psycopg.connect(url, autocommit=True) as conn: for k in range(3): collector.take_snapshots(conn, client(fake), NOW + timedelta(minutes=5 * k)) row = conn.execute("SELECT snapshot_misses, snapshots_ended FROM shortstats.video " "WHERE video_id = 'gone0000001'").fetchone() assert row == (3, "unavailable") fake.calls.clear() assert collector.take_snapshots(conn, client(fake), NOW + timedelta(hours=1)) == 0 assert stat_calls(fake) == [] def test_tracking_ends_after_three_years(setup): db, fake = setup insert_video(db["owner"], "ancien00001", timedelta(days=4 * 365), status="too_old") with psycopg.connect(db["collector"], autocommit=True) as conn: collector.take_snapshots(conn, client(fake), NOW) assert conn.execute("SELECT snapshots_ended FROM shortstats.video").fetchone()[0] == "done" assert stat_calls(fake) == [] def test_run_includes_snapshots_and_announces_data(setup): db, fake = setup fake.add_short("runsnap0001", iso(NOW - timedelta(hours=2, minutes=3))) res = collector.run(make_cfg(db["collector"]), client(fake), now=NOW) # découverte assert res.discovered == 1 and res.snapshots == 1 # 2 h échue depuis 3 min assert [s[0] for s in snaps(db["collector"], "runsnap0001")] == ["2 h"] def test_rights_on_snapshots(setup): db, _ = setup insert_video(db["owner"], "rights00001", timedelta(hours=2)) with psycopg.connect(db["web"], autocommit=True) as conn: with pytest.raises(psycopg.errors.InsufficientPrivilege): conn.execute("INSERT INTO shortstats.video_snapshot (video_id, step_id, age_hours) " "VALUES ('rights00001', 1, 1)") with psycopg.connect(db["collector"], autocommit=True) as conn: conn.execute("INSERT INTO shortstats.video_snapshot (video_id, step_id, age_hours) VALUES ('rights00001', 1, 1)") with pytest.raises(psycopg.errors.InsufficientPrivilege): conn.execute("DELETE FROM shortstats.video_snapshot") with pytest.raises(psycopg.errors.InsufficientPrivilege): conn.execute("UPDATE shortstats.video_snapshot SET view_count = 1") def test_steps_match_migration(clean_db): with psycopg.connect(clean_db["web"]) as conn: rows = conn.execute("SELECT step_id, label, nominal_hours::float FROM shortstats.snapshot_step " "ORDER BY step_id").fetchall() assert [(a, b, float(c)) for a, b, c in chart_catalog.STEPS] == rows assert chart_catalog.STEP_BY_ID[chart_catalog.J7_STEP][0] == "7 j" def test_collector_follows_new_schedule(clean_db): add_channel(clean_db["web"], CHANNEL, checked=True) fake = FakeYouTube() fake.add_short("sched000001", iso(NOW - timedelta(hours=7, minutes=10)), views=10, listed=False) with psycopg.connect(clean_db["owner"], autocommit=True) as conn: conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status) VALUES ('sched000001', %s, %s, 'pending')""", (CHANNEL, NOW - timedelta(hours=7, minutes=10))) taken = [] with psycopg.connect(clean_db["collector"], autocommit=True) as conn: # 7 h, 8 h, 9 h... : un relevé par heure le premier jour, puis toutes les 3 h for minutes in [0] + [60 * k for k in range(1, 25)]: collector.take_snapshots(conn, client(fake), NOW + timedelta(minutes=minutes)) taken = [r[0] for r in conn.execute( """SELECT st.label FROM shortstats.video_snapshot sn JOIN shortstats.snapshot_step st USING (step_id) ORDER BY step_id""")] assert taken[:4] == ["7 h", "8 h", "9 h", "10 h"] and "24 h" in taken assert taken[-2:] == ["1 j 3 h", "1 j 6 h"] and "1 j 4 h" not in taken # prochaine étape annoncée : selon le nouveau calendrier with psycopg.connect(clean_db["web"]) as conn: nxt = conn.execute("""SELECT st.label FROM shortstats.snapshot_step st JOIN shortstats.video v ON st.step_id > v.snapshot_step ORDER BY st.step_id LIMIT 1""").fetchone()[0] assert nxt == "1 j 9 h"