shortstats/tests/test_collector.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

259 lines
13 KiB
Python

from datetime import datetime, timedelta, timezone
import psycopg
import pytest
from shortstats import collector
from shortstats.config import CollectorConfig
from shortstats.youtube import YouTubeClient
from .conftest import add_channel
from .fake_youtube import CHANNEL, OTHER, FakeYouTube
NOW = datetime(2026, 10, 31, 12, 0, tzinfo=timezone.utc)
THIRD = "UC" + "c" * 22
def iso(dt: datetime) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
def make_cfg(url, **over):
base = dict(database_url=url, api_key="test-key", collect_after_hours=168, shorts_playlist_prefix="UUSH",
shorts_max_duration_s=None, comment_max_pages=3, max_attempts=2, run_retention_days=90)
base.update(over)
return CollectorConfig(**base)
def client(fake):
return YouTubeClient("test-key", "https://yt.test/youtube/v3", transport=fake.transport())
def video(url, vid):
with psycopg.connect(url) as conn:
cur = conn.execute("SELECT * FROM shortstats.video WHERE video_id = %s", (vid,))
cols = [d.name for d in cur.description]
row = cur.fetchone()
return dict(zip(cols, row)) if row else None
def channel(url, cid):
with psycopg.connect(url) as conn:
cur = conn.execute("SELECT * FROM shortstats.channel WHERE channel_id = %s", (cid,))
cols = [d.name for d in cur.description]
return dict(zip(cols, cur.fetchone()))
def pending(url, vid, channel_id=CHANNEL, age=timedelta(days=8)):
with psycopg.connect(url, autocommit=True) as conn:
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at)
VALUES (%s, %s, %s)""", (vid, channel_id, NOW - age))
@pytest.fixture()
def fake():
return FakeYouTube()
def test_full_cycle(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER) # A n'est pas le propriétaire
fake.add_short("recent00001", iso(NOW - timedelta(days=2)), title="Récent")
fake.add_short("dueshort001", iso(NOW - timedelta(days=7, minutes=5)), title="Prêt", views=12345, likes=678, comments=90)
fake.add_short("ancient0001", iso(NOW - timedelta(days=30)), title="Ancien")
fake.comments["dueshort001"] = [[
fake.thread(CHANNEL, "merci à tous (commentaire du propriétaire, non retenu)"),
fake.thread(OTHER, "Nouvel épisode : APOTHECARY DIARIES et une applepie", likes=42, cid="pinned"),
]]
# Premier passage juste avant les 7 jours de dueshort001 : vérification de la
# chaîne et découverte, mais aucun relevé.
res = collector.run(make_cfg(url), client(fake), now=NOW - timedelta(minutes=10))
assert (res.status, res.discovered, res.collected) == ("ok", 2, 0)
assert video(url, "ancient0001")["status"] == "too_old"
assert video(url, "dueshort001")["status"] == "pending"
ch = channel(url, CHANNEL)
assert (ch["youtube_title"], ch["author_title"], ch["check_error"]) == ("Ma chaîne", "Utilisateur A", None)
# Passage suivant : dueshort001 a 7 jours, il est relevé ; la chaîne n'est pas revérifiée.
res = collector.run(make_cfg(url), client(fake), now=NOW)
assert (res.status, res.discovered, res.collected) == ("ok", 0, 1)
v = video(url, "dueshort001")
assert v["status"] == "collected"
assert (v["title"], v["view_count"], v["like_count"], v["comment_count"], v["duration_s"]) == ("Prêt", 12345, 678, 90, 45)
assert (v["author_comment_status"], v["author_comment_id"], v["author_comment_likes"], v["author_comment_rank"]) == ("found", "pinned", 42, 2)
assert v["comment_author_channel_id"] == OTHER
assert v["publish_hour"] is not None and 1 <= v["publish_isodow"] <= 7
assert video(url, "recent00001")["status"] == "pending"
with psycopg.connect(clean_db["web"]) as conn:
names = sorted(r[0] for r in conn.execute(
"SELECT name FROM shortstats.video_theme WHERE video_id = 'dueshort001'"))
assert names == ["Apothecary Diaries", "applepie"]
with psycopg.connect(url) as conn:
runs = conn.execute("SELECT status, quota_units FROM shortstats.collect_run ORDER BY run_id").fetchall()
# 1re : channels + playlist + relevés successifs ; 2e : playlist + videos + comments + relevés
assert runs == [("ok", 3), ("ok", 4)]
def test_user_a_is_set_per_channel(clean_db, fake):
"""Chaque chaîne a son propre utilisateur A, qui peut différer du propriétaire."""
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True) # A différent du propriétaire
add_channel(clean_db["web"], THIRD, author_id=THIRD, checked=True) # A = propriétaire
fake.channel_names[THIRD] = "Troisième"
for vid, ch in (("vidchan0001", CHANNEL), ("vidchan0002", THIRD)):
fake.add_short(vid, iso(NOW - timedelta(days=8)), channel=ch, listed=False)
pending(url, vid, ch)
fake.comments[vid] = [[
fake.thread(CHANNEL, "commentaire du propriétaire 1", likes=1, cid=f"{vid}-own1"),
fake.thread(OTHER, "commentaire de A : applepie", likes=99, cid=f"{vid}-other"),
fake.thread(THIRD, "commentaire du propriétaire 3", likes=7, cid=f"{vid}-own3"),
]]
collector.run(make_cfg(url), client(fake), now=NOW)
v1, v2 = video(url, "vidchan0001"), video(url, "vidchan0002")
assert (v1["author_comment_id"], v1["author_comment_likes"], v1["comment_author_channel_id"]) == ("vidchan0001-other", 99, OTHER)
assert (v2["author_comment_id"], v2["author_comment_likes"], v2["comment_author_channel_id"]) == ("vidchan0002-own3", 7, THIRD)
def test_verification_reports_unknown_ids(clean_db, fake):
url = clean_db["collector"]
unknown_author = "UC" + "x" * 22
add_channel(clean_db["web"], CHANNEL, author_id=unknown_author)
add_channel(clean_db["web"], THIRD, author_id=OTHER) # chaîne inconnue de l'API
collector.run(make_cfg(url), client(fake), now=NOW)
ch1, ch3 = channel(url, CHANNEL), channel(url, THIRD)
assert ch1["youtube_title"] == "Ma chaîne" and ch1["author_title"] is None
assert "auteur du commentaire épinglé introuvable" in ch1["check_error"]
assert "chaîne introuvable" in ch3["check_error"]
# Une chaîne en erreur n'est revérifiée qu'après 6 h : pas de nouvel appel channels.list.
fake.calls.clear()
collector.run(make_cfg(url), client(fake), now=NOW)
assert not [c for c in fake.calls if c[0] == "channels"]
def test_verification_does_not_overwrite_concurrent_edit(clean_db, fake):
"""Si l'utilisateur A change sur le site pendant la vérification, le résultat n'est pas enregistré."""
add_channel(clean_db["web"], CHANNEL, author_id=CHANNEL)
with psycopg.connect(clean_db["collector"], autocommit=True) as conn:
fake_titles = {CHANNEL: "Ma chaîne"}
class Client:
quota_used = 0
def channel_titles(self, ids):
with psycopg.connect(clean_db["web"], autocommit=True) as web:
web.execute("UPDATE shortstats.channel SET author_channel_id = %s", (OTHER,))
return fake_titles
collector.verify_channels(conn, Client())
assert channel(clean_db["collector"], CHANNEL)["checked_at"] is None
def test_paused_channel_not_discovered_but_pending_collected(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, active=False, checked=True)
fake.add_short("newshort001", iso(NOW - timedelta(days=1)))
fake.add_short("dueshort001", iso(NOW - timedelta(days=8)), listed=False)
pending(url, "dueshort001")
res = collector.run(make_cfg(url), client(fake), now=NOW)
assert (res.discovered, res.collected) == (0, 1)
assert video(url, "newshort001") is None
assert not [c for c in fake.calls if c[0] in {"playlistItems", "channels"}]
def test_no_channel_is_not_an_error(clean_db, fake):
res = collector.run(make_cfg(clean_db["collector"]), client(fake), now=NOW)
assert (res.status, res.discovered, res.quota_units) == ("ok", 0, 0)
def test_theme_added_later_applies_retroactively(clean_db, fake):
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True)
fake.add_short("dueshort001", iso(NOW - timedelta(days=8)), title="x", listed=False)
pending(clean_db["collector"], "dueshort001")
fake.comments["dueshort001"] = [[fake.thread(OTHER, "Frieren arrive bientôt")]]
collector.run(make_cfg(clean_db["collector"]), client(fake), now=NOW)
with psycopg.connect(clean_db["web"], autocommit=True) as conn:
assert conn.execute("SELECT count(*) FROM shortstats.video_theme").fetchone()[0] == 0
conn.execute("INSERT INTO shortstats.theme (name, keywords) VALUES ('Frieren', ARRAY['frieren'])")
assert conn.execute("SELECT name FROM shortstats.video_theme").fetchone()[0] == "Frieren"
def test_no_comment_means_no_api_call(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True)
fake.add_short("nocomment01", iso(NOW - timedelta(days=8)), comments=0, listed=False)
pending(url, "nocomment01")
collector.run(make_cfg(url), client(fake), now=NOW)
assert video(url, "nocomment01")["author_comment_status"] == "not_found"
assert not [c for c in fake.calls if c[0] == "commentThreads"]
def test_unavailable_after_max_attempts(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True)
pending(url, "deleted0001")
collector.run(make_cfg(url), client(fake), now=NOW)
assert (video(url, "deleted0001")["status"], video(url, "deleted0001")["attempts"]) == ("pending", 1)
collector.run(make_cfg(url), client(fake), now=NOW)
assert video(url, "deleted0001")["status"] == "unavailable"
def test_comments_disabled_and_hidden_likes(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True)
fake.add_short("dueshort001", iso(NOW - timedelta(days=8)), likes=None, listed=False)
fake.disabled.add("dueshort001")
pending(url, "dueshort001")
collector.run(make_cfg(url), client(fake), now=NOW)
v = video(url, "dueshort001")
assert (v["status"], v["like_count"], v["author_comment_status"]) == ("collected", None, "comments_disabled")
def test_not_short_filter_when_using_all_uploads(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, author_id=OTHER, checked=True)
fake.add_short("longvideo01", iso(NOW - timedelta(days=8)), duration="PT12M", listed=False)
pending(url, "longvideo01")
collector.run(make_cfg(url, shorts_playlist_prefix="UU", shorts_max_duration_s=180), client(fake), now=NOW)
assert video(url, "longvideo01")["status"] == "not_short"
def test_quota_exceeded_is_logged(clean_db, fake):
add_channel(clean_db["web"], CHANNEL, author_id=OTHER)
fake.quota_exceeded = True
res = collector.run(make_cfg(clean_db["collector"]), client(fake), now=NOW)
assert res.status == "error" and "Quota" in res.message
with psycopg.connect(clean_db["collector"]) as conn:
assert conn.execute("SELECT status FROM shortstats.collect_run").fetchone()[0] == "error"
def test_concurrent_run_is_skipped(clean_db, fake):
with psycopg.connect(clean_db["collector"], autocommit=True) as conn:
conn.execute("SELECT pg_advisory_lock(hashtext('shortstats-collector'))")
res = collector.run(make_cfg(clean_db["collector"]), client(fake), now=NOW)
assert res.status == "skipped"
conn.execute("SELECT pg_advisory_unlock(hashtext('shortstats-collector'))")
def test_ip_restriction_error_is_visible(clean_db, fake):
"""Clé API restreinte à une autre adresse (typiquement l'IPv4 alors que l'appel part en IPv6) :
le message de Google, avec l'adresse refusée, est conservé en entier pour le tableau de bord."""
import httpx
add_channel(clean_db["web"], CHANNEL, author_id=OTHER)
ip = "2a01:e0a:1234:5678:a1b2:c3d4:e5f6:7890"
message = ("The provided API key has an IP address restriction. The originating IP address "
f"of the call ({ip}) violates this restriction.")
def handler(request):
return httpx.Response(403, json={"error": {"code": 403, "message": message,
"errors": [{"reason": "forbidden", "message": message}]}})
blocked = YouTubeClient("test-key", "https://yt.test/youtube/v3", transport=httpx.MockTransport(handler))
res = collector.run(make_cfg(clean_db["collector"]), blocked, now=NOW)
assert res.status == "error" and ip in res.message
with psycopg.connect(clean_db["collector"]) as conn:
stored = conn.execute("SELECT message FROM shortstats.collect_run").fetchone()[0]
assert ip in stored[:400]