shortstats/tests/test_snapshots.py
ploush 30e925324b
All checks were successful
build / test (push) Successful in 3m10s
build / images (collector) (push) Successful in 19s
build / images (web) (push) Successful in 21s
Upgrade 1.2.0
2026-11-01 18:17:50 +01:00

145 lines
6.7 KiB
Python

"""Relevés successifs (v1.2.0) : étapes, collecte, tolérance, fin de suivi, droits."""
from datetime import timedelta
import psycopg
import pytest
from shortstats import collector
from .conftest import add_channel
from .fake_youtube import CHANNEL, OTHER, FakeYouTube
from .test_collector import NOW, client, iso, make_cfg
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") == "statistics"]
@pytest.fixture()
def setup(clean_db):
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, 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) == 60
assert labels[:12] == ["1 h", "2 h", "3 h", "4 h", "5 h", "6 h", "9 h", "12 h", "15 h", "18 h", "21 h", "24 h"]
assert labels[12:18] == [f"{d} j" for d in range(2, 8)]
assert labels[18:25] == [f"{w} sem." for w in range(2, 9)]
assert labels[25] == "2 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=20)), listed=False)
insert_video(db["owner"], "old00000001", timedelta(days=20), 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:
# 20 j : l'étape « 2 sem. » (14 j) est échue depuis 6 j, au-delà de 10 % : ignorée
assert collector.take_snapshots(conn, client(fake), NOW) == 0
# à 21 j + 1 h : « 3 sem. » relevée
assert collector.take_snapshots(conn, client(fake), NOW + timedelta(days=1, hours=1)) == 1
assert [s[0] for s in snaps(url, "old00000001")] == ["3 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")