shortstats/tests/integration/test_collecteur.py
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

216 lines
11 KiB
Python

"""Collecte complète avec l'API YouTube simulée."""
from __future__ import annotations
from datetime import timedelta
import psycopg
from shortstats import collector
from shortstats.youtube import YouTubeClient
from ..outils.base import add_channel
from ..outils.collecte import NOW, client, iso, make_cfg
from ..outils.fake_youtube import CHANNEL
THIRD = "UC" + "c" * 22
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))
def test_full_cycle(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL)
fake.add_short("recent00001", iso(NOW - timedelta(days=2)), title="Récent", comments=0)
fake.add_short("dueshort001", iso(NOW - timedelta(days=7, minutes=5)), title="Prêt", views=12345, likes=678,
comments=2)
fake.add_short("ancient0001", iso(NOW - timedelta(days=30)), title="Ancien", comments=0)
fake.add_comment("dueshort001", "c1", "merci à tous", iso(NOW - timedelta(days=6)))
fake.add_comment("dueshort001", "c2", "Nouvel épisode : APOTHECARY DIARIES et une applepie",
iso(NOW - timedelta(days=5)))
# Premier passage juste avant les 7 jours de dueshort001 : vérification de la
# chaîne, découverte et relevés successifs, mais pas de relevé complet.
res = collector.run(make_cfg(url), client(fake), now=NOW - timedelta(minutes=10))
assert (res.status, res.discovered, res.collected, res.snapshots) == ("ok", 2, 0, 3)
assert video(url, "ancient0001")["status"] == "too_old"
assert video(url, "dueshort001")["status"] == "pending"
ch = channel(url, CHANNEL)
assert (ch["youtube_title"], ch["check_error"], ch["comment_scope"]) == ("Ma chaîne", None, "top")
# commentaires relevés pour la seule vidéo qui en a, et classés par thème
assert (res.comments_read, res.comment_units) == (2, 1)
with psycopg.connect(clean_db["web"]) as conn:
themes = sorted(r[0] for r in conn.execute(
"""SELECT t.name FROM shortstats.comment_theme ct JOIN shortstats.theme t USING (theme_id)
WHERE ct.comment_id = 'c2'"""))
assert themes == ["Apothecary Diaries", "applepie"]
# 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, 2, 45)
assert v["publish_hour"] is not None and 1 <= v["publish_isodow"] <= 7
assert video(url, "recent00001")["status"] == "pending"
assert "author_comment_text" not in v and "comment_author_channel_id" not in v
with psycopg.connect(url) as conn:
runs = conn.execute("SELECT status, quota_units, comment_units, comments_read "
"FROM shortstats.collect_run ORDER BY run_id").fetchall()
# 1re : channels + playlist + relevés successifs + commentaires ; 2e : playlist + videos + relevés
# (le nombre de commentaires n'a pas bougé : rien à relire)
assert runs == [("ok", 4, 1, 2), ("ok", 3, 0, 0)]
def test_verification_reports_unknown_channel(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL)
add_channel(clean_db["web"], THIRD) # 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["check_error"] is None
assert "chaîne introuvable" in ch3["check_error"]
assert "author_channel_id" not in ch1
# 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_paused_channel_not_discovered_but_pending_collected(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, 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, checked=True)
fake.add_short("dueshort001", iso(NOW - timedelta(hours=2, minutes=5)), title="x", comments=1, listed=False)
fake.add_comment("dueshort001", "c1", "Frieren arrive bientôt", iso(NOW - timedelta(hours=1)))
pending(clean_db["collector"], "dueshort001", age=timedelta(hours=2, minutes=5))
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.comment_theme").fetchone()[0] == 0
assert conn.execute("SELECT comments_read FROM shortstats.video_snapshot").fetchone()[0] == 1
# thème ajouté sur le site : appliqué aux commentaires déjà lus et à leurs relevés
from shortstats.web.data import Repo, make_pool
with make_pool(clean_db["web"]) as pool:
theme_id = Repo(pool).save_theme(None, "Frieren", ["frieren"])
with psycopg.connect(clean_db["web"]) as conn:
assert conn.execute("SELECT comment_id FROM shortstats.comment_theme").fetchone()[0] == "c1"
assert conn.execute("SELECT theme_id, comments FROM shortstats.snapshot_theme").fetchall() == [(theme_id, 1)]
def test_no_comment_means_no_api_call(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, 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")["status"] == "collected"
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, 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, 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"]) == ("collected", None)
# commentaires annoncés mais illisibles : lecture close, pas de nouvel essai à chaque collecte
assert v["comment_count_read"] == v["comment_count_latest"] == 10 and v["comment_page_token"] is None
fake.calls.clear()
collector.run(make_cfg(url), client(fake), now=NOW + timedelta(minutes=15))
assert not [c for c in fake.calls if c[0] == "commentThreads"]
def test_not_short_filter_when_using_all_uploads(clean_db, fake):
url = clean_db["collector"]
add_channel(clean_db["web"], CHANNEL, 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)
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)
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]