shortstats/tests/test_collect_request.py
ploush d5312c3667
Some checks failed
build / test (push) Failing after 1m3s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
Upgrade 1.1.0
2026-11-01 13:47:38 +01:00

201 lines
8.4 KiB
Python

"""Bouton « Lancer une collecte » (demande en base, veilleur, API)."""
import threading
import time
import httpx
import psycopg
import pytest
from shortstats import collector
from shortstats.youtube import YouTubeClient
from .conftest import add_channel
from .fake_youtube import CHANNEL, OTHER, FakeYouTube
from .test_collector import NOW, client, make_cfg
from .test_web import ORIGIN, app_client, login, users_file # noqa: F401 (fixtures)
def request_collect(web_url, user="alice", age_min=0):
with psycopg.connect(web_url, autocommit=True) as conn:
rid = conn.execute("INSERT INTO shortstats.collect_request (requested_by) VALUES (%s) RETURNING request_id",
(user,)).fetchone()[0]
if age_min:
with psycopg.connect(OWNER_URL[0], autocommit=True) as conn:
conn.execute("UPDATE shortstats.collect_request SET requested_at = now() - make_interval(mins => %s) "
"WHERE request_id = %s", (age_min, rid))
return rid
OWNER_URL = [None]
@pytest.fixture(autouse=True)
def _owner(clean_db):
OWNER_URL[0] = clean_db["owner"]
def request_row(url, rid):
with psycopg.connect(url) as conn:
return conn.execute("SELECT started_at, finished_at, run_id FROM shortstats.collect_request "
"WHERE request_id = %s", (rid,)).fetchone()
def test_any_run_serves_pending_requests(clean_db):
add_channel(clean_db["web"], CHANNEL, author_id=OTHER)
rid = request_collect(clean_db["web"])
res = collector.run(make_cfg(clean_db["collector"]), client(FakeYouTube()), now=NOW)
assert res.status == "ok"
started, finished, run_id = request_row(clean_db["owner"], rid)
assert started and finished and run_id
def test_collector_cannot_create_requests(clean_db):
with psycopg.connect(clean_db["collector"], autocommit=True) as conn:
with pytest.raises(psycopg.errors.InsufficientPrivilege):
conn.execute("INSERT INTO shortstats.collect_request (requested_by) VALUES ('x')")
def test_web_cannot_mark_requests(clean_db):
rid = request_collect(clean_db["web"])
with psycopg.connect(clean_db["web"], autocommit=True) as conn:
with pytest.raises(psycopg.errors.InsufficientPrivilege):
conn.execute("UPDATE shortstats.collect_request SET finished_at = now() WHERE request_id = %s", (rid,))
def test_insert_sends_notification(clean_db):
with psycopg.connect(clean_db["collector"], autocommit=True) as conn:
conn.execute("LISTEN shortstats_collect")
rid = request_collect(clean_db["web"])
notes = list(conn.notifies(timeout=5, stop_after=1))
assert notes and notes[0].payload == str(rid)
def test_watch_runs_on_notification(clean_db):
calls = []
stop = threading.Event()
cfg = make_cfg(clean_db["collector"])
def fake_run(c):
calls.append(time.monotonic())
# comme une vraie collecte : marque les demandes servies
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("UPDATE shortstats.collect_request SET started_at = now(), finished_at = now() "
"WHERE started_at IS NULL")
return collector.RunResult(status="ok")
t = threading.Thread(target=collector.watch, args=(cfg,), kwargs={"poll_s": 30, "stop": stop, "run_fn": fake_run},
daemon=True)
t.start()
time.sleep(0.5)
assert calls == [] # rien en attente au démarrage
sent = time.monotonic()
request_collect(clean_db["web"])
deadline = time.monotonic() + 5
while not calls and time.monotonic() < deadline:
time.sleep(0.05)
assert calls and calls[0] - sent < 3 # réveil par la notification, pas par le délai de 30 s
stop.set()
def test_watch_serves_request_waiting_at_startup_and_ignores_stale(clean_db):
request_collect(clean_db["web"], age_min=45) # trop ancienne : ignorée
calls = []
stop = threading.Event()
def fake_run(c):
calls.append(1)
stop.set()
return collector.RunResult(status="ok")
t = threading.Thread(target=collector.watch, args=(make_cfg(clean_db["collector"]),),
kwargs={"poll_s": 0.3, "stop": stop, "run_fn": fake_run}, daemon=True)
t.start()
time.sleep(1)
assert calls == []
request_collect(clean_db["web"], age_min=5)
t.join(5)
assert calls == [1]
def test_network_error_message(clean_db, monkeypatch):
monkeypatch.setattr("shortstats.youtube.time.sleep", lambda s: None)
add_channel(clean_db["web"], CHANNEL, author_id=OTHER)
def handler(request):
raise httpx.ConnectError("[Errno -3] Temporary failure in name resolution")
offline = YouTubeClient("k", "https://yt.test/youtube/v3", transport=httpx.MockTransport(handler))
res = collector.run(make_cfg(clean_db["collector"]), offline, now=NOW)
assert res.status == "error"
assert "API YouTube injoignable" in res.message and "DNS" in res.message
assert "Temporary failure in name resolution" in res.message
# -- site --------------------------------------------------------------------
def test_collect_button_api(app_client, clean_db):
c = app_client
assert c.post("/api/collect", headers={"Origin": ORIGIN}).status_code == 401
login(c)
assert "Lancer une collecte" in c.get("/").text
assert c.post("/api/collect", headers={"Origin": "https://evil.example"}).status_code == 403
r = c.post("/api/collect", headers={"Origin": ORIGIN})
assert r.status_code == 202 and r.json()["created"] is True
rid = r.json()["id"]
# second clic : la demande en cours est réutilisée
r2 = c.post("/api/collect", headers={"Origin": ORIGIN})
assert r2.status_code == 202 and r2.json() == {"id": rid, "created": False}
home = c.get("/").text
assert 'data-pending="yes"' in home and "Demandée par alice" in home
assert c.get(f"/api/collect/{rid}").json()["state"] == "waiting"
# le collecteur la sert
collector.run(make_cfg(clean_db["collector"]), client(FakeYouTube()), now=NOW)
state = c.get(f"/api/collect/{rid}").json()
assert state["state"] == "done" and state["run"]["status"] == "ok"
# trop tôt pour une nouvelle demande
r3 = c.post("/api/collect", headers={"Origin": ORIGIN})
assert r3.status_code == 429
assert c.get("/api/collect/999999").status_code == 404
def test_stale_request_is_expired_and_does_not_block(app_client, clean_db):
login(app_client)
rid = request_collect(clean_db["web"], age_min=40)
assert app_client.get(f"/api/collect/{rid}").json()["state"] == "expired"
r = app_client.post("/api/collect", headers={"Origin": ORIGIN})
assert r.status_code == 202 and r.json()["created"] is True
def test_charts_filter_and_split_by_channel_from_db(app_client, clean_db):
from .test_web import CH, OTHER as CH2, seed_videos
seed_videos(clean_db["owner"], n=20)
with psycopg.connect(clean_db["owner"], autocommit=True) as conn:
conn.execute("""INSERT INTO shortstats.channel (channel_id, author_channel_id, youtube_title)
VALUES (%s, %s, 'Seconde chaîne')""", (CH2, CH2))
conn.execute("UPDATE shortstats.video SET channel_id = %s WHERE right(video_id, 1)::int %% 2 = 1", (CH2,))
login(app_client)
cat = app_client.get("/api/catalog").json()
assert [c["name"] for c in cat["channels"]] == ["Ma chaîne", "Seconde chaîne"]
assert {c["collected"] for c in cat["channels"]} == {10}
def preview(cfg):
r = app_client.post("/api/preview", json={"config": cfg}, headers={"Origin": ORIGIN})
assert r.status_code == 200, r.text
return r.json()
both = preview({"x": "publish_date", "y": "views", "type": "line"})
assert both["n"] == 20 and both["resolved"]["split"] == "color"
assert both["spec"]["encoding"]["color"]["scale"]["domain"] == ["Ma chaîne", "Seconde chaîne"]
one = preview({"x": "publish_date", "y": "views", "type": "line", "channels": [CH2]})
assert one["n"] == 10 and one["resolved"]["split"] is None
merged = preview({"x": "publish_date", "y": "views", "type": "line", "split_channels": False})
assert merged["resolved"]["split"] is None
# enregistré tel quel
r = app_client.post("/api/charts", json={"config": {"x": "views", "y": "likes", "channels": [CH]}},
headers={"Origin": ORIGIN})
assert r.status_code == 201 and r.json()["config"]["channels"] == [CH]
rendered = app_client.get(f"/api/charts/{r.json()['id']}/render").json()
assert rendered["n"] == 10