339 lines
18 KiB
Python
339 lines
18 KiB
Python
"""Lecture des commentaires : comptes par relevé, pagination, budget, réponses."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import timedelta
|
|
|
|
import psycopg
|
|
import pytest
|
|
|
|
from shortstats import collector
|
|
|
|
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
|
|
|
|
|
|
@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['\\mfrieren\\M'])")
|
|
return clean_db
|
|
|
|
|
|
def set_count(fake, vid, n):
|
|
fake.videos[vid]["statistics"]["commentCount"] = str(n)
|
|
|
|
|
|
def per_step(url, vid):
|
|
"""{étape: (commentaires relevés, {thème: nombre})} des relevés d'une vidéo."""
|
|
with psycopg.connect(url) as conn:
|
|
rows = conn.execute(
|
|
"""SELECT st.label, sn.comments_read,
|
|
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 = sn.video_id AND sth.step_id = sn.step_id), '{}')
|
|
FROM shortstats.video_snapshot sn JOIN shortstats.snapshot_step st USING (step_id)
|
|
WHERE sn.video_id = %s ORDER BY sn.step_id""", (vid,)).fetchall()
|
|
return {r[0]: (r[1], r[2]) for r in rows}
|
|
|
|
|
|
def state(url, vid):
|
|
with psycopg.connect(url) as conn:
|
|
cur = conn.execute("""SELECT comment_count_latest, comment_count_read, comment_page_token,
|
|
comments_read_at, comment_scope_read, next_step, snapshots_ended
|
|
FROM shortstats.video WHERE video_id = %s""", (vid,))
|
|
return dict(zip([d.name for d in cur.description], cur.fetchone()))
|
|
|
|
|
|
def stored(url, vid):
|
|
with psycopg.connect(url) as conn:
|
|
return sorted(r[0] for r in conn.execute(
|
|
"SELECT comment_id FROM shortstats.comment WHERE video_id = %s", (vid,)))
|
|
|
|
|
|
def test_counts_per_snapshot_are_cumulative_and_retroactive(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=1, listed=False)
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
fake.add_comment("vid00000001", "c1", "Frieren, enfin !", iso(NOW - timedelta(hours=2, minutes=30)))
|
|
|
|
# 1 h : un commentaire
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW - timedelta(hours=2))
|
|
assert (res.snapshots, res.comments_read) == (1, 1)
|
|
assert per_step(url, "vid00000001") == {"1 h": (1, {"Frieren": 1})}
|
|
|
|
# 3 h : deux de plus (un de chaque thème)
|
|
fake.add_comment("vid00000001", "c2", "une applepie s'il vous plaît", iso(NOW - timedelta(hours=1, minutes=30)))
|
|
fake.add_comment("vid00000001", "c3", "FRIEREN saison 2", iso(NOW - timedelta(minutes=10)))
|
|
set_count(fake, "vid00000001", 3)
|
|
fake.calls.clear()
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW)
|
|
assert res.comments_read == 2 and len(calls(fake, "commentThreads")) == 1 # arrêt sur les déjà lus
|
|
assert per_step(url, "vid00000001") == {
|
|
"1 h": (1, {"Frieren": 1}),
|
|
"3 h": (3, {"Frieren": 2, "applepie": 1}),
|
|
}
|
|
|
|
# Un commentaire publié avant le relevé de 1 h mais visible seulement maintenant
|
|
# (retenu pour modération) : compté dans tous les relevés pris après sa publication.
|
|
fake.add_comment("vid00000001", "c0", "frieren !!", iso(NOW - timedelta(hours=2, minutes=10)))
|
|
set_count(fake, "vid00000001", 4)
|
|
collector.run(make_cfg(url), client(fake), now=NOW + timedelta(hours=1, minutes=5))
|
|
got = per_step(url, "vid00000001")
|
|
assert got["1 h"] == (2, {"Frieren": 2})
|
|
assert got["3 h"] == (4, {"Frieren": 3, "applepie": 1})
|
|
assert got["4 h"] == (4, {"Frieren": 3, "applepie": 1})
|
|
# « \mfrieren\M » : le mot entier seulement, majuscules comprises
|
|
with psycopg.connect(url) as conn:
|
|
assert conn.execute("SELECT count(*) FROM shortstats.comment_theme").fetchone()[0] == 4
|
|
|
|
|
|
def test_snapshot_counted_at_once_when_nothing_new(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
fake.add_short("vid00000001", iso(pub), comments=1, listed=False)
|
|
fake.add_comment("vid00000001", "c1", "frieren", iso(pub + timedelta(minutes=30)))
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
collector.run(make_cfg(url), client(fake), now=NOW)
|
|
fake.calls.clear()
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW + timedelta(hours=1))
|
|
assert res.snapshots == 1 and calls(fake, "commentThreads") == [] # même nombre : rien à relire
|
|
assert per_step(url, "vid00000001") == {"1 h": (1, {"Frieren": 1}), "2 h": (1, {"Frieren": 1})}
|
|
|
|
|
|
def test_video_without_comments_costs_nothing(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
pub = NOW - timedelta(hours=1, 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 per_step(url, "vid00000001") == {"1 h": (0, {})}
|
|
|
|
|
|
def test_pagination_and_incremental_reading(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
fake.page_size = 2
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
fake.add_short("vid00000001", iso(pub), comments=5, listed=False)
|
|
for i in range(5):
|
|
fake.add_comment("vid00000001", f"c{i}", f"commentaire {i}", iso(pub + timedelta(minutes=i)))
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW)
|
|
assert (res.comments_read, res.comment_units) == (5, 3) # 3 pages de 2
|
|
s = state(url, "vid00000001")
|
|
assert (s["comment_count_read"], s["comment_page_token"], s["comment_scope_read"]) == (5, None, "top")
|
|
fake.add_comment("vid00000001", "c5", "nouveau", iso(NOW + timedelta(minutes=30)))
|
|
set_count(fake, "vid00000001", 6)
|
|
fake.calls.clear()
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW + timedelta(hours=1))
|
|
assert (res.comments_read, res.comment_units) == (1, 1) # 1re page : déjà lus, arrêt
|
|
assert len(stored(url, "vid00000001")) == 6
|
|
|
|
|
|
def test_budget_interrupts_and_resumes(db, monkeypatch):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
monkeypatch.setattr(collector, "COMMENT_RUN_UNITS", 2)
|
|
fake = FakeYouTube()
|
|
fake.page_size = 1
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
fake.add_short("vid00000001", iso(pub), comments=4, listed=False)
|
|
for i in range(4):
|
|
fake.add_comment("vid00000001", f"c{i}", "frieren", iso(pub + timedelta(minutes=i)))
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW)
|
|
assert (res.comments_read, res.comment_units) == (2, 2)
|
|
s = state(url, "vid00000001")
|
|
assert s["comment_page_token"] == "full:c1" and s["comments_read_at"] is None
|
|
assert per_step(url, "vid00000001") == {"1 h": (None, {})} # pas encore compté
|
|
# un commentaire arrive pendant l'interruption
|
|
fake.add_comment("vid00000001", "c9", "frieren", iso(NOW + timedelta(minutes=5)))
|
|
set_count(fake, "vid00000001", 5)
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW + timedelta(minutes=15))
|
|
assert res.comment_units == 2 and state(url, "vid00000001")["comment_page_token"] == "new:"
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW + timedelta(minutes=30))
|
|
assert stored(url, "vid00000001") == ["c0", "c1", "c2", "c3", "c9"]
|
|
s = state(url, "vid00000001")
|
|
assert s["comment_page_token"] is None and s["comment_count_read"] == 4 # nombre du dernier relevé
|
|
assert per_step(url, "vid00000001") == {"1 h": (4, {"Frieren": 4})} # c9 publié après le relevé
|
|
|
|
|
|
def test_daily_budget(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
fake.add_short("vid00000001", iso(pub), comments=1, listed=False)
|
|
fake.add_comment("vid00000001", "c1", "x", iso(pub))
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
with psycopg.connect(url, autocommit=True) as conn: # 24 h glissantes
|
|
conn.execute("INSERT INTO shortstats.collect_run (comment_units) VALUES (4999)")
|
|
conn.execute("INSERT INTO shortstats.collect_run (started_at, comment_units) VALUES (now() - interval '25 hours', 9000)")
|
|
res = collector.run(make_cfg(url, comment_units_per_day=4999), client(fake), now=NOW)
|
|
assert res.comment_units == 0 and stored(url, "vid00000001") == []
|
|
res = collector.run(make_cfg(url, comment_units_per_day=5000), client(fake), now=NOW)
|
|
assert res.comment_units == 1 and stored(url, "vid00000001") == ["c1"]
|
|
# 0 : lecture désactivée
|
|
fake.add_comment("vid00000001", "c2", "y", iso(pub))
|
|
set_count(fake, "vid00000001", 2)
|
|
res = collector.run(make_cfg(url, comment_units_per_day=0), client(fake), now=NOW + timedelta(hours=1))
|
|
assert res.snapshots == 1 and res.comment_units == 0
|
|
|
|
|
|
def test_replies_scope_and_switching_back(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True, scope="all")
|
|
fake = FakeYouTube()
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
at = iso(pub + timedelta(minutes=10))
|
|
fake.add_short("vid00000001", iso(pub), comments=13, listed=False)
|
|
fake.add_comment("vid00000001", "a", "fil a", at, replies=[(f"r{i}", "frieren" if i < 2 else "ok", at) for i in range(7)])
|
|
fake.add_comment("vid00000001", "b", "fil b frieren", at, replies=[(f"r{i}", "bien", at) for i in range(3)])
|
|
fake.add_comment("vid00000001", "c", "fil c", at)
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW)
|
|
# 1 page de fils (avec 5 réponses chacun au plus) + 1 page de réponses pour le fil a (7 réponses)
|
|
assert (res.comments_read, res.comment_units) == (13, 2)
|
|
assert [c[1]["parentId"] for c in calls(fake, "comments")] == ["a"]
|
|
assert per_step(url, "vid00000001") == {"1 h": (13, {"Frieren": 3})}
|
|
assert state(url, "vid00000001")["comment_scope_read"] == "all"
|
|
with psycopg.connect(url) as conn:
|
|
assert conn.execute("SELECT count(*) FROM shortstats.comment WHERE parent_id = 'a'").fetchone()[0] == 7
|
|
# retour au 1er niveau (page Chaînes) : réponses retirées sans appel à l'API
|
|
with psycopg.connect(db["web"], autocommit=True) as conn:
|
|
conn.execute("UPDATE shortstats.channel SET comment_scope = 'top'")
|
|
fake.calls.clear()
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW + timedelta(minutes=15))
|
|
assert res.comment_units == 0 and stored(url, "vid00000001") == ["a", "b", "c"]
|
|
assert per_step(url, "vid00000001") == {"1 h": (3, {"Frieren": 1})}
|
|
assert state(url, "vid00000001")["comment_scope_read"] == "top"
|
|
|
|
|
|
def test_switching_to_replies_rereads_everything(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
at = iso(pub + timedelta(minutes=10))
|
|
fake.add_short("vid00000001", iso(pub), comments=3, listed=False)
|
|
fake.add_comment("vid00000001", "a", "fil a", at, replies=[("r1", "frieren", at), ("r2", "x", at)])
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
collector.run(make_cfg(url), client(fake), now=NOW)
|
|
assert stored(url, "vid00000001") == ["a"]
|
|
assert all(c[1]["part"] == "snippet" for c in calls(fake, "commentThreads"))
|
|
with psycopg.connect(db["web"], autocommit=True) as conn:
|
|
conn.execute("UPDATE shortstats.channel SET comment_scope = 'all'")
|
|
fake.calls.clear()
|
|
collector.run(make_cfg(url), client(fake), now=NOW + timedelta(minutes=15))
|
|
assert calls(fake, "commentThreads")[0][1]["part"] == "snippet,replies"
|
|
assert stored(url, "vid00000001") == ["a", "a.r1", "a.r2"]
|
|
assert per_step(url, "vid00000001") == {"1 h": (3, {"Frieren": 1})}
|
|
|
|
|
|
def test_ended_or_excluded_videos_are_not_read(db):
|
|
url = db["collector"]
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
with psycopg.connect(db["owner"], autocommit=True) as conn:
|
|
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, comment_count_latest,
|
|
snapshots_ended)
|
|
VALUES ('ended000001', %s, %s, 'too_old', 5, 'done'),
|
|
('long0000001', %s, %s, 'not_short', 5, NULL)""",
|
|
(CHANNEL, NOW - timedelta(days=2000), CHANNEL, NOW - timedelta(days=20)))
|
|
res = collector.run(make_cfg(url), client(fake), now=NOW)
|
|
assert res.comment_units == 0 and calls(fake, "commentThreads") == []
|
|
|
|
|
|
def test_most_urgent_snapshots_first(db, monkeypatch):
|
|
"""Au-delà du lot, la tolérance qui expire le plus tôt passe d'abord (pas la vidéo la plus ancienne)."""
|
|
url = db["collector"]
|
|
monkeypatch.setattr(collector, "SNAPSHOT_BATCH", 1)
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
fake = FakeYouTube()
|
|
old = NOW - timedelta(hours=30, minutes=10) # « 1 j 6 h » échue depuis 10 min, tolérance 3 h
|
|
new = NOW - timedelta(hours=1, minutes=20) # « 1 h » échue depuis 20 min, tolérance 30 min
|
|
for vid, pub in (("old00000001", old), ("new00000001", new)):
|
|
fake.add_short(vid, iso(pub), comments=0, listed=False)
|
|
insert_video(db["owner"], vid, pub)
|
|
with psycopg.connect(url, autocommit=True) as conn:
|
|
assert collector.take_snapshots(conn, client(fake), NOW) == 1
|
|
assert per_step(url, "new00000001") == {"1 h": (0, {})} and per_step(url, "old00000001") == {}
|
|
assert collector.take_snapshots(conn, client(fake), NOW + timedelta(minutes=15)) == 1
|
|
assert per_step(url, "old00000001") == {"1 j 6 h": (0, {})}
|
|
|
|
|
|
def test_next_step_is_maintained(db):
|
|
url = db["collector"]
|
|
fake = FakeYouTube()
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
with psycopg.connect(url, autocommit=True) as conn:
|
|
# découverte : prochaine étape « 1 h »
|
|
fake.add_short("disc0000001", iso(NOW - timedelta(minutes=20)), comments=0)
|
|
collector.discover(conn, make_cfg(url), client(fake), NOW)
|
|
assert state(url, "disc0000001")["next_step"] == 1
|
|
conn.execute("UPDATE shortstats.video SET status = 'not_short'") # hors suivi pour la suite
|
|
|
|
pub = NOW - timedelta(hours=1, minutes=5)
|
|
fake.add_short("vid00000001", iso(pub), title="Avant", comments=0, listed=False)
|
|
insert_video(db["owner"], "vid00000001", pub)
|
|
fake.videos["vid00000001"]["snippet"]["title"] = "Après"
|
|
assert collector.take_snapshots(conn, client(fake), NOW) == 1
|
|
assert state(url, "vid00000001")["next_step"] == 2
|
|
# titre mis à jour au relevé
|
|
assert conn.execute("SELECT title FROM shortstats.video WHERE video_id = 'vid00000001'").fetchone()[0] == "Après"
|
|
# collecteur arrêté : à 3 h 45, « 3 h » est hors tolérance et « 4 h » pas encore échue :
|
|
# étapes sautées sans appel à l'API
|
|
fake.calls.clear()
|
|
assert collector.take_snapshots(conn, client(fake), pub + timedelta(hours=3, minutes=45)) == 0
|
|
assert fake.calls == []
|
|
nxt = conn.execute("""SELECT st.label, v.next_snapshot_at FROM shortstats.video v
|
|
JOIN shortstats.snapshot_step st ON st.step_id = v.next_step
|
|
WHERE video_id = 'vid00000001'""").fetchone()
|
|
assert nxt == ("4 h", pub + timedelta(hours=4))
|
|
# rien n'est échu : aucune requête du tout
|
|
assert collector.take_snapshots(conn, client(fake), pub + timedelta(hours=3, minutes=50)) == 0
|
|
assert fake.calls == []
|
|
assert collector.take_snapshots(conn, client(fake), pub + timedelta(hours=4, minutes=1)) == 1
|
|
assert list(per_step(url, "vid00000001")) == ["1 h", "4 h"]
|
|
|
|
|
|
def test_last_step_ends_tracking(db):
|
|
url = db["collector"]
|
|
fake = FakeYouTube()
|
|
pub = NOW - timedelta(days=3 * 365 + 1, minutes=30)
|
|
fake.add_short("vid00000001", iso(pub), comments=0, listed=False)
|
|
add_channel(db["web"], CHANNEL, checked=True)
|
|
with psycopg.connect(db["owner"], autocommit=True) as conn:
|
|
conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, snapshot_step)
|
|
VALUES ('vid00000001', %s, %s, 'too_old', 150)""", (CHANNEL, pub))
|
|
with psycopg.connect(url, autocommit=True) as conn:
|
|
assert collector.take_snapshots(conn, client(fake), NOW) == 1
|
|
assert list(per_step(url, "vid00000001")) == ["36 mois"]
|
|
s = state(url, "vid00000001")
|
|
assert s["next_step"] is None and s["snapshots_ended"] == "done"
|
|
|
|
|
|
def test_rights(db):
|
|
with psycopg.connect(db["web"], autocommit=True) as conn:
|
|
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
|
conn.execute("UPDATE shortstats.video_snapshot SET comments_read = 1")
|
|
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
|
conn.execute("INSERT INTO shortstats.comment (comment_id, video_id, published_at, text) "
|
|
"VALUES ('x', 'y', now(), 'z')")
|
|
add_channel(db["web"], CHANNEL)
|
|
with psycopg.connect(db["collector"], autocommit=True) as conn:
|
|
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
|
conn.execute("UPDATE shortstats.channel SET comment_scope = 'all'")
|
|
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
|
conn.execute("UPDATE shortstats.theme SET name = 'x'")
|