"""1.3.1 : mesures des commentaires aux étapes sans relevé, adaptateur regex101 <-> PostgreSQL.""" import re from datetime import datetime, timedelta, timezone import psycopg import pytest from shortstats import collector, comment_themes, migrate from shortstats.regex_adapter import RegexTranslationError, to_pcre, to_postgres from shortstats.web import charts from .conftest import add_channel from .fake_youtube import CHANNEL, FakeYouTube from .test_collector import NOW, client, iso, make_cfg from .test_evolution import preview from .test_v130_comments import calls, insert_video from .test_v130_schedule import _owner_cfg from .test_v130_themes import add_comments from .test_web import CH, ORIGIN, app_client, login, users_file # noqa: F401 H = {"Origin": ORIGIN} BS = "\\" # Écrits par morceaux : la séquence antislash-u suivie de 4 chiffres serait # interprétée par certains outils d'édition. U_E9 = BS + "u" + "00e9" U_1F600 = BS + "U" + "0001f600" # -- Adaptateur : traductions exactes ------------------------------------------ @pytest.mark.parametrize("pcre, pg", [ (r"apple ?pie", r"apple ?pie"), (r"\bchat\b", r"\ychat\y"), (r"\Bat", r"\Yat"), (r"(?-i)TV", r"(?c)TV"), (r"(?i)tv", r"tv"), (r"(?s)a.b", r"a.b"), (r"(?m)^bravo$", r"(?w)^bravo$"), (r"(?x) a b # c", r"(?x) a b # c"), (r"(?x)a # \m reste un commentaire", r"(?x)a # \m reste un commentaire"), (r"(?-i)(?m)x", r"(?cw)x"), (r"merci$", r"merci(?=\n?\Z)"), (r"a|b$", r"a|b(?=\n?\Z)"), (r"[$]\$", r"[$]\$"), (r"\Afin\z", r"\Afin\Z"), (r"fin\Z", r"fin(?=\n?\Z)"), (r"\x{e9}t\xe9", U_E9 + "t" + U_E9), (r"\x{1F600}", U_1F600), (r"\h+", r"[[:blank:]]+"), (r"[\h,]", r"[[:blank:],]"), (r"\H", r"[^[:blank:]]"), (r"\N+", r"[^\n]+"), (r"\R", r"(?:\r\n|\n|\r)"), (r"\p{L}+\pN\P{P}", r"[[:alpha:]]+[[:digit:]][^[:punct:]]"), (r"[\p{L}\d]", r"[[:alpha:]\d]"), (r"(?la) (?Pb) (?'y'c)", r"(la) (b) (c)"), (r"(\w)\g1\g{1}", r"(\w)\1\1"), (r"a{,3}", r"a{0,3}"), (r"x{2}y{2,}z{2,5}?", r"x{2}y{2,}z{2,5}?"), (r"{", r"\{"), (r"a{x}", r"a\{x}"), (r"\Qa.b*\E+", r"a\.b\*+"), (r"\Q(fin", r"\(fin"), (r"[\b\w\-\]]", r"[\b\w\-\]]"), (r"[]a]", r"[]a]"), (r"[^]a]", r"[^]a]"), (r"[[:alpha:]]", r"[[:alpha:]]"), (r"(?:ab)+?(?=c)(?!d)(?<=e)(?a+)b", "groupe atomique"), (r"a++", "possessif"), (r"a*+", "possessif"), (r"a?+", "possessif"), (r"a{2}+", "possessif"), (r"(?i:a)b", "seulement au tout début"), (r"a(?i)b", "seulement au tout début"), (r"(?-s)a.b", r"[^\n]"), (r"(?U)a", "option (?U)"), (r"(?R)", "récursion"), (r"(a)(?1)", "récursion"), (r"(?|a)", "(?|"), (r"(?(1)a|b)", "condition"), (r"(*UTF)a", "verbes"), (r"(?C1)a", "(?C"), (r"\K", r"\K"), (r"\G", r"\G"), (r"\X", r"\X"), (r"\v", r"[\n\r]"), (r"\k", r"\1"), (r"(?P=n)", "rappel nommé"), (r"\g{n}", r"\g1"), (r"\10", r"\9"), (r"\p{Lu}", r"\p{L}"), (r"[\P{L}]", "[ ]"), (r"[\B]", "[ ]"), (r"\x", "chiffres"), (r"\x{zz}", r"\x{e9}"), (r"\x{110000}", "Unicode"), (r"\x00", "nul"), (r"\q", "regex101"), ("a" + BS, "fin d'expression"), (r"[abc", "non fermé"), ]) def test_refusals(pcre, message): with pytest.raises(RegexTranslationError) as exc: to_postgres(pcre) assert message in str(exc.value), str(exc.value) @pytest.mark.parametrize("pg, pcre", [ (r"\mchat\M", r"\bchat\b"), # lettre à côté : \b suffit (r"\m(chat)\M", r"\b(?=\w)(chat)\b(?<=\w)"), (r"\mc?hat\M", r"\b(?=\w)c?hat\b"), (r"a+\M", r"a+\b(?<=\w)"), (r"\ychat\y", r"\bchat\b"), (r"(?c)TV", r"(?-i)TV"), (r"(?cw)a$", r"(?m-i)a$"), (r"[[:<:]]chat[[:>:]]", r"\bchat\b"), (U_E9 + "t", r"\x{e9}t"), (r"a\Zb\Bc\bd", r"a\zb\\c\x{8}d"), (r"\[spoiler\]", r"\[spoiler\]"), (r"^_^ \$", r"^_^ \$"), (r"merci$", r"merci\z"), # fin du texte seulement, comme avant (r"(?n)a.b", r"(?n)a.b"), # sans équivalent : gardée, refusée à l'enregistrement (r"a{2,3}b{x", r"a{2,3}b\{x"), (r"merci(?=\n?\Z)", r"merci$"), ]) def test_legacy_expressions_are_shown_in_regex101_syntax(pg, pcre): """Thèmes d'avant la 1.3.1 (syntaxe PostgreSQL) : retraduits pour l'affichage (l'équivalence au réenregistrement : test suivant).""" assert to_pcre(pg) == pcre if pg.startswith("(?n)"): with pytest.raises(RegexTranslationError, match="option"): to_postgres(pcre) # -- Adaptateur : mêmes résultats que PCRE (Python re en tient lieu) ------------ # (expression regex101, équivalent pour le module re de Python, options de re) DIFF = [ (r"\bchat\b", None, 0), (r"apple ?pie", None, 0), (r"saison (2|deux)", None, 0), (r"ép(isode)?\s*[0-9]+", None, 0), (r"^merci", None, 0), (r"merci$", None, 0), (r"merci\s*$", None, 0), (r"1\.5", None, 0), (r"\d{2,}", None, 0), (r"a{0,2}b", None, 0), (r"a{,1}b", r"a{0,1}b", 0), (r"\Bat\b", None, 0), (r"(?=.*chat)(?=.*chien)", None, 0), (r"(?la)\s(?Pla)", r"(la)\s(la)", 0), (r"\Afin\z", r"\Afin\Z", 0), (r"fin\Z", r"fin(?=\n?\Z)", 0), (r"a.b", None, 0), (r"\bété\b", None, 0), (r"[[:alpha:]]+!", r"[^\W\d_]+!", 0), (r"(?i)été", "été", 0), (r"\R", r"(?:\r\n|\n|\r)", 0), (r"^$", None, 0), (r"\.\.\.$", None, 0), ] TEXTS = [ "Super chat !", "Le château", "CHAT noir", "chat noir", "applepie", "Apple Pie", "saison 2", "Saison deux", "épisode12", "ÉP 3", "merci beaucoup", "Un grand merci", "merci\n", "merci \n", "merci\nà tous", "bravo\nmerci", "ligne\nbravo\nfin", "version 1.5", "1x5", "123", "été", "ÉTÉ", "Un été", "aab", "?!?", "non merci", "TV", "tv", "chien et chat", "la la", "la\nla", "tab\there", "", "x\ty", "fin", "fin\n", "fin\n\n", "a\nb", "c'est la fin", "chat\r\nnoir", "wow...", "wow...\n", "xxy", "été", "Café!", "1234", "\U0001f600", ] def test_same_results_as_pcre(clean_db): """Chaque expression traduite reconnaît dans PostgreSQL (~*, comme pour les thèmes) exactement les textes que l'expression d'origine reconnaît avec les réglages i, s et u de regex101 (Python re, mêmes règles sur ces exemples).""" diffs = [] with psycopg.connect(clean_db["web"]) as conn: for pcre, py, flags in DIFF: pg = to_postgres(pcre) py_flags = re.S if flags == -1 else re.I | re.S | flags compiled = re.compile(py if py is not None else pcre, py_flags) got = conn.execute("SELECT array_agg(t ~* %s ORDER BY i) FROM unnest(%s::text[]) WITH ORDINALITY u (t, i)", (pg, TEXTS)).fetchone()[0] for text, ok in zip(TEXTS, got): if bool(compiled.search(text)) != ok: diffs.append((pcre, pg, text, ok)) assert diffs == [] LEGACY = [r"\mchat\M", r"\m(chat)\M", r"\mc?hat\M", r"\mé\w*", r"\w+é\M", r"[[:<:]]la[[:>:]]", r"\yfin\y", r"(?c)TV", r"merci$", r"^merci", r"apple ?pie", r"\mfrieren\M", r"ch[aâ]t\M", r"\d{2,}", U_E9 + "t" + U_E9, r"(?cw)^bravo$", r"(a|b)\1"] def test_legacy_expressions_classify_the_same_after_round_trip(clean_db): """Expression d'avant la 1.3.1, affichée en syntaxe regex101 puis réenregistrée : PostgreSQL reconnaît exactement les mêmes textes.""" diffs = [] with psycopg.connect(clean_db["web"]) as conn: for pg in LEGACY: back = to_postgres(to_pcre(pg)) got = conn.execute( """SELECT array_agg(t ~* %s ORDER BY i), array_agg(t ~* %s ORDER BY i) FROM unnest(%s::text[]) WITH ORDINALITY u (t, i)""", (pg, back, TEXTS)).fetchone() diffs += [(pg, back, t) for t, a, b in zip(TEXTS, *got) if a != b] assert diffs == [] # -- Page Thèmes --------------------------------------------------------------- def test_themes_are_written_in_regex101_syntax(app_client, clean_db): owner = clean_db["owner"] with psycopg.connect(owner, autocommit=True) as conn: # thème d'avant la 1.3.1 : syntaxe PostgreSQL, sans saisie gardée conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Ancien', ARRAY['\\mchat\\M', '(?c)TV'])") add_comments(owner, ["Un chat noir", "le château", "TV et tv", "tv seulement", "l'été arrive"]) login(app_client) r = app_client.post("/themes", data={"name": "Été", "pattern": [r"\bété\b", r"\x{e9}t\xe9$"]}, headers=H, follow_redirects=False) assert r.status_code == 303, r.text with psycopg.connect(clean_db["web"]) as conn: rows = dict((r[0], r[1:]) for r in conn.execute( "SELECT name, patterns, pattern_sources FROM shortstats.theme")) assert rows["Été"] == ([r"\yété\y", U_E9 + "t" + U_E9 + r"(?=\n?\Z)"], [r"\bété\b", r"\x{e9}t\xe9$"]) assert rows["Ancien"][1] is None page = app_client.get("/themes").text # saisie réaffichée telle quelle ; ancien thème retraduit assert 'value="\\bété\\b"' in page and 'value="\\x{e9}t\\xe9$"' in page assert 'value="\\bchat\\b"' in page and 'value="(?-i)TV"' in page assert "regex101" in page and "\\mchat" not in page from .test_v130_themes import themes_of got = themes_of(owner) assert got["rgx00000000"] == ["Ancien"] and got["rgx00000002"] == ["Ancien"] and got["rgx00000004"] == ["Été"] # réenregistré depuis la page (expressions retraduites), l'ancien thème classe pareil with psycopg.connect(clean_db["web"]) as conn: tid = conn.execute("SELECT theme_id FROM shortstats.theme WHERE name = 'Ancien'").fetchone()[0] r = app_client.post(f"/themes/{tid}", data={"name": "Ancien", "pattern": [r"\b(?=\w)chat\b(?<=\w)", "(?-i)TV"]}, headers=H, follow_redirects=False) assert r.status_code == 303 and themes_of(owner) == got def test_untranslatable_expressions_are_refused(app_client, clean_db): login(app_client) r = app_client.post("/themes", data={"name": "PG", "pattern": ["ok", r"\mchat\M", "a++", "(?>x)"]}, headers=H, follow_redirects=False) assert r.status_code == 400 page = r.text assert "3 expression(s) régulière(s) invalide(s)" in page assert "Sans équivalent dans la base : \\m (début de mot) est propre à PostgreSQL : écrivez \\b" in page assert "quantificateur possessif" in page and "groupe atomique" in page assert 'value="\\mchat\\M"' in page with psycopg.connect(clean_db["web"]) as conn: assert conn.execute("SELECT count(*) FROM shortstats.theme WHERE name = 'PG'").fetchone()[0] == 0 def test_live_check_shows_the_translation(app_client, clean_db): add_comments(clean_db["owner"], ["Un chat", "château", "merci\n", "Café"]) login(app_client) data = app_client.post("/api/themes/check", headers=H, json={ "patterns": [r"\bchat\b", r"\bch\w+", r"merci$", r"\x{e9}", r"\xe9", "a++", "("]}).json() by = {p["pattern"]: p for p in data["patterns"]} assert by[r"\bchat\b"] == {"pattern": r"\bchat\b", "ok": True, "error": None, "matches": 1, "translated": r"\ychat\y"} assert by[r"\bch\w+"]["matches"] == 2 assert by["merci$"]["matches"] == 1 and by["merci$"]["translated"] == r"merci(?=\n?\Z)" # deux saisies, une même traduction : comptées chacune assert by[r"\x{e9}"]["matches"] == by[r"\xe9"]["matches"] == 1 assert by["a++"]["ok"] is False and by["a++"]["error"].startswith("Sans équivalent dans la base : ") assert by["a++"]["translated"] is None and by["a++"]["matches"] is None assert by["("]["ok"] is False and "parenthèses" in by["("]["error"] assert data["total"] == 4 # -- Étapes sans relevé : complétées pour les commentaires ---------------------- @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['\\yfrieren\\y'])") return clean_db def points(url, vid): """{étape: (commentaires relevés, complétée, {thème: nombre})} de toutes les étapes d'une vidéo.""" with psycopg.connect(url) as conn: rows = conn.execute( """SELECT st.label, sp.comments_read, sp.estimated, 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 = sp.video_id AND sth.step_id = sp.step_id), '{}') FROM shortstats.step_point sp JOIN shortstats.snapshot_step st USING (step_id) WHERE sp.video_id = %s ORDER BY sp.step_id""", (vid,)).fetchall() return {r[0]: (r[1], r[2], r[3]) for r in rows} def test_late_video_gets_its_past_steps(db): """Vidéo découverte 5 h après sa sortie : relevé à 5 h seulement, mais les commentaires ont leur date : les étapes 1 h à 4 h sont complétées.""" url = db["collector"] add_channel(db["web"], CHANNEL, checked=True) fake = FakeYouTube() pub = NOW - timedelta(hours=5, minutes=5) fake.add_short("vid00000001", iso(pub), comments=3, listed=False) insert_video(db["owner"], "vid00000001", pub) fake.add_comment("vid00000001", "c1", "Frieren !", iso(pub + timedelta(minutes=30))) fake.add_comment("vid00000001", "c2", "rien", iso(pub + timedelta(hours=2, minutes=30))) fake.add_comment("vid00000001", "c3", "frieren encore", iso(pub + timedelta(hours=4, minutes=30))) res = collector.run(make_cfg(url), client(fake), now=NOW) assert (res.snapshots, res.comments_read) == (1, 3) assert points(url, "vid00000001") == { "1 h": (1, True, {"Frieren": 1}), "2 h": (1, True, {"Frieren": 1}), "3 h": (2, True, {"Frieren": 1}), "4 h": (2, True, {"Frieren": 1}), "5 h": (3, False, {"Frieren": 2})} with psycopg.connect(url) as conn: est = conn.execute("""SELECT step_id, taken_at, age_hours FROM shortstats.comment_estimate WHERE video_id = 'vid00000001' ORDER BY step_id""").fetchall() assert [(s, t - pub, float(a)) for s, t, a in est] == [(i, timedelta(hours=i), float(i)) for i in range(1, 5)] # vues et likes : toujours inconnus aux étapes complétées with psycopg.connect(url) as conn: assert conn.execute("""SELECT count(*) FROM shortstats.step_point WHERE estimated AND (view_count IS NOT NULL OR like_count IS NOT NULL)""").fetchone()[0] == 0 # un thème ajouté ensuite s'applique aussi aux étapes complétées with psycopg.connect(db["web"], autocommit=True) as conn: tid = conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Rien', ARRAY['rien']) " "RETURNING theme_id").fetchone()[0] with conn.transaction(): comment_themes.lock(conn) comment_themes.refresh_theme(conn, tid) assert points(url, "vid00000001")["3 h"] == (2, True, {"Frieren": 1, "Rien": 1}) assert points(url, "vid00000001")["2 h"] == (1, True, {"Frieren": 1}) def test_real_snapshot_replaces_completed_step(db): """Étape complétée (commentaires relevés après son heure) puis relevée dans sa tolérance : le relevé remplace l'étape complétée.""" url = db["collector"] add_channel(db["web"], CHANNEL, checked=True) fake = FakeYouTube() pub = NOW - timedelta(hours=6, minutes=10) fake.add_short("vid00000001", iso(pub), comments=1, listed=False) insert_video(db["owner"], "vid00000001", pub) with psycopg.connect(db["owner"], autocommit=True) as conn: conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text) VALUES ('c1', 'vid00000001', %s, 'frieren')""", (pub + timedelta(minutes=30),)) conn.execute("""UPDATE shortstats.video SET snapshot_step = 5, next_step = 6, next_snapshot_at = %s, comment_count_latest = 1, comment_count_read = 1, comments_read_at = %s, comment_scope_read = 'top' WHERE video_id = 'vid00000001'""", (pub + timedelta(hours=6), NOW - timedelta(minutes=5))) comment_themes.classify(conn, ["c1"]) comment_themes.refresh_videos(conn, ["vid00000001"]) before = points(url, "vid00000001") assert list(before) == ["1 h", "2 h", "3 h", "4 h", "5 h", "6 h"] and before["6 h"] == (1, True, {"Frieren": 1}) with psycopg.connect(url, autocommit=True) as conn: assert collector.take_snapshots(conn, client(fake), now=NOW) == 1 after = points(url, "vid00000001") assert after["6 h"] == (1, False, {"Frieren": 1}) assert {k: v for k, v in after.items() if k != "6 h"} == {k: v for k, v in before.items() if k != "6 h"} with psycopg.connect(url) as conn: assert conn.execute("SELECT count(*) FROM shortstats.comment_estimate WHERE step_id = 6").fetchone()[0] == 0 def test_video_without_comments_counts_zero_everywhere(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=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 points(url, "vid00000001") == {"1 h": (0, True, {}), "2 h": (0, True, {}), "3 h": (0, False, {})} def seed_late(owner_url): """Deux vidéos de la chaîne CH : lat00000001 relevée de 1 h à 6 h, lat00000002 relevée à 6 h seulement (découverte tard) ; commentaires relevés pour les deux.""" pub = datetime(2026, 9, 1, 12, 0, tzinfo=timezone.utc) with psycopg.connect(owner_url, autocommit=True) as conn: conn.execute("INSERT INTO shortstats.channel (channel_id, youtube_title) VALUES (%s, 'Ma chaîne')", (CH,)) for vid, steps in (("lat00000001", range(1, 7)), ("lat00000002", [6])): conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, title, comments_read_at, comment_count_read, comment_scope_read) VALUES (%s, %s, %s, 'pending', %s, %s, 4, 'top')""", (vid, CH, pub, f"Vidéo {vid}", pub + timedelta(hours=6, minutes=1))) for sid in steps: conn.execute("""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count, like_count, comment_count) VALUES (%s, %s, %s, %s, 100, 10, 4)""", (vid, sid, pub + timedelta(hours=sid, minutes=1), sid + 0.02)) for i, minutes in enumerate((20, 90, 150, 330)): conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text) VALUES (%s, %s, %s, %s)""", (f"{vid}-{i}", vid, pub + timedelta(minutes=minutes), "applepie" if i % 2 == 0 else "autre chose")) comment_themes.classify(conn, [f"{v}-{i}" for v in ("lat00000001", "lat00000002") for i in range(4)]) comment_themes.refresh_videos(conn, ["lat00000001", "lat00000002"]) def test_charts_use_completed_steps(app_client, clean_db): seed_late(clean_db["owner"]) login(app_client) # évolution : à 2 h, les deux vidéos comptent (lat00000002 par son étape complétée) out = preview(app_client, {"source": "evolution", "x": "age", "y": "comments_read", "agg": "mean", "split_channels": False}) by = {r["lab"]: r for r in out["spec"]["data"]["values"]} assert by["2 h"]["n"] == 2 and by["2 h"]["y"] == 2 and by["6 h"]["n"] == 2 and by["6 h"]["y"] == 4 assert charts.COMMENT_STEPS_NOTE in out["explanation"] assert "relevé(s) ou étape(s) complétée(s)" in out["explanation"] rate = preview(app_client, {"source": "evolution", "x": "age", "y": "theme_rate", "agg": "mean", "split_channels": False}, {"filters": {"theme": {"in": ["applepie"]}}}) r3 = [r for r in rate["spec"]["data"]["values"] if r["lab"] == "3 h"][0] assert r3["n"] == 2 and abs(r3["y"] - 100 * 2 / 3) < 0.001 # 2 « applepie » sur 3 commentaires assert "pour 1 thème(s)" in rate["explanation"] # mesure des commentaires à une étape, par vidéo : lat00000002 n'a pas de relevé à 2 h j7 = preview(app_client, {"x": "theme", "y": "theme_rate@2", "split_channels": False}) got = {(r["id"], r["x"]): r["y"] for r in j7["spec"]["data"]["values"]} assert got == {("lat00000001", "applepie"): 50, ("lat00000002", "applepie"): 50, ("lat00000001", "Apothecary Diaries"): 0, ("lat00000002", "Apothecary Diaries"): 0} assert charts.COMMENT_STEPS_NOTE in j7["explanation"] and "2 vidéo(s)" in j7["explanation"] # les vues restent celles des seuls relevés views = preview(app_client, {"source": "evolution", "x": "age", "y": "views", "agg": "mean", "split_channels": False}) assert {r["lab"]: r["n"] for r in views["spec"]["data"]["values"]}["2 h"] == 1 assert charts.COMMENT_STEPS_NOTE not in views["explanation"] # page Vidéos : détail des étapes, complétées comprises rows = app_client.get("/api/videos/lat00000002/snapshots").json() assert [(r["step"], r["estimated"], r["comments_read"]) for r in rows] == [ ("1 h", True, 1), ("2 h", True, 2), ("3 h", True, 3), ("4 h", True, 3), ("5 h", True, 3), ("6 h", False, 4)] assert rows[0]["views"] is None and rows[5]["views"] == 100 # -- Migration 011 ----------------------------------------------------------------- @pytest.fixture() def before_011(clean_db): owner = clean_db["owner"] with psycopg.connect(owner, autocommit=True) as conn: conn.execute("DROP SCHEMA shortstats CASCADE") migrate.run(_owner_cfg(owner), stop_after="010") yield clean_db migrate.run(_owner_cfg(owner)) def test_migration_011(before_011): owner = before_011["owner"] pub = datetime(2026, 9, 1, 12, 0, tzinfo=timezone.utc) with psycopg.connect(owner, autocommit=True) as conn: conn.execute("INSERT INTO shortstats.channel (channel_id) VALUES (%s)", (CH,)) conn.execute("INSERT INTO shortstats.theme (name, patterns) VALUES ('Tarte', ARRAY['\\mapple ?pie\\M'])") for vid, count in (("late0000001", 4), ("empt0000001", 0)): conn.execute("""INSERT INTO shortstats.video (video_id, channel_id, published_at, status, comment_count_latest, comment_count_read, comments_read_at, comment_scope_read) VALUES (%s, %s, %s, 'pending', %s, %s, %s, %s)""", (vid, CH, pub, count, 4 if count else None, pub + timedelta(hours=6, minutes=1) if count else None, "top" if count else None)) conn.execute("""INSERT INTO shortstats.video_snapshot (video_id, step_id, taken_at, age_hours, view_count, like_count, comment_count) VALUES (%s, 6, %s, 6.02, 100, 10, %s)""", (vid, pub + timedelta(hours=6, minutes=1), count)) for i, minutes in enumerate((20, 90, 150, 330)): conn.execute("""INSERT INTO shortstats.comment (comment_id, video_id, published_at, text) VALUES (%s, 'late0000001', %s, %s)""", (f"late0000001-{i}", pub + timedelta(minutes=minutes), "Apple Pie" if i % 2 == 0 else "autre")) comment_themes.classify(conn, [f"late0000001-{i}" for i in range(4)]) conn.execute("UPDATE shortstats.video_snapshot SET comments_read = 4 WHERE video_id = 'late0000001'") conn.execute("""INSERT INTO shortstats.snapshot_theme (video_id, step_id, theme_id, comments) SELECT 'late0000001', 6, theme_id, 2 FROM shortstats.theme WHERE name = 'Tarte'""") assert migrate.run(_owner_cfg(owner)) == ["011_comment_steps.sql"] def snapshot(conn): est = conn.execute("""SELECT video_id, step_id, taken_at, age_hours, comments_read FROM shortstats.comment_estimate ORDER BY 1, 2""").fetchall() themes = conn.execute("SELECT video_id, step_id, theme_id, comments FROM shortstats.snapshot_theme " "ORDER BY 1, 2, 3").fetchall() reads = conn.execute("SELECT video_id, step_id, comments_read FROM shortstats.video_snapshot " "ORDER BY 1, 2").fetchall() return est, themes, reads with psycopg.connect(owner, autocommit=True) as conn: migrated = snapshot(conn) est, themes, reads = migrated # vidéo sans commentaire : 0 jusqu'à son dernier relevé (6 h) ; l'autre, d'après les dates assert [(v, s, n) for v, s, _t, _a, n in est] == [("empt0000001", s, 0) for s in range(1, 6)] + [ ("late0000001", 1, 1), ("late0000001", 2, 2), ("late0000001", 3, 3), ("late0000001", 4, 3), ("late0000001", 5, 3)] assert [(v, s, n) for v, s, _t, n in themes] == [("late0000001", s, n) for s, n in ((1, 1), (2, 1), (3, 2), (4, 2), (5, 2), (6, 2))] assert reads == [("empt0000001", 6, 0), ("late0000001", 6, 4)] v = conn.execute("""SELECT comment_count_read, comment_scope_read, comments_read_at IS NOT NULL FROM shortstats.video WHERE video_id = 'empt0000001'""").fetchone() assert v == (0, "top", True) # mêmes résultats que le calcul du collecteur with conn.transaction(): comment_themes.refresh_videos(conn, ["late0000001", "empt0000001"]) assert snapshot(conn) == migrated assert conn.execute("SELECT pattern_sources FROM shortstats.theme").fetchone()[0] is None with pytest.raises(psycopg.errors.CheckViolation): conn.execute("UPDATE shortstats.theme SET pattern_sources = ARRAY['a', 'b']")