import json from pathlib import Path import pytest from fastapi.testclient import TestClient from app.config import Settings from app.db import Database from app.judge import Judge, JudgeError, Verdict, _clean, build_prompt from app.main import create_app from app.scoring import ChatMessage, Word from app.sources import SourceError, parse_source from app.worker import Engine, wall_to_t KEY = "k" * 40 @pytest.mark.parametrize("url,platform,channel,kind", [ ("https://www.twitch.tv/alanzoka", "twitch", "alanzoka", "live"), ("twitch.tv/Alanzoka?x=1", "twitch", "alanzoka", "live"), ("https://www.twitch.tv/videos/123456789", "twitch", "", "vod"), ("https://kick.com/gaules", "kick", "gaules", "live"), ("https://www.youtube.com/@canal", "youtube", "@canal", "live"), ("https://youtu.be/dQw4w9WgXcQ", "youtube", "", "vod"), ("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "youtube", "", "vod"), ]) def test_parse_source(url, platform, channel, kind): source = parse_source(url) assert (source.platform, source.channel, source.kind) == (platform, channel, kind) @pytest.mark.parametrize("url", ["", "https://vimeo.com/1", "https://www.twitch.tv/directory", "ftp://twitch.tv/x"]) def test_parse_source_rejects(url): with pytest.raises(SourceError): parse_source(url) def test_wall_to_t_maps_by_segment_arrival(): # Bloco 0 (0–30 s) chegou às 1000; bloco 1 (30–60 s) chegou às 1060 (pausa de 30 s: anúncio filtrado). segments = [{"idx": 0, "start_s": 0.0, "end_s": 30.0, "wall_end": 1000.0}, {"idx": 1, "start_s": 30.0, "end_s": 60.0, "wall_end": 1060.0}] assert wall_to_t(990.0, segments) == 20.0 assert wall_to_t(960.0, segments) is None # antes de a gravação começar assert wall_to_t(1010.0, segments) == 30.0 # durante a pausa: cai no começo do bloco seguinte assert wall_to_t(1050.0, segments) == 50.0 assert wall_to_t(1065.0, segments) == 65.0 def test_judge_prompt_and_clean(): words = [Word(100.0, 100.4, "não"), Word(100.5, 101.0, "acredito")] chat = [ChatMessage(104.0, "KKKKK"), ChatMessage(105.0, "clipa")] prompt = build_prompt("alanzoka", "twitch", 90, 120, 104, words, chat, {"peakRatio": 4.2}) assert "[100s] não acredito" in prompt and "KKKKK" in prompt and "alanzoka" in prompt verdict = _clean({"keep": True, "score": 14, "start_s": 0, "end_s": 500, "title": "t", "caption": "c", "reason": "r"}, 200, 230, "m") # Padrão novo (16/11/2026): pode voltar até 2 min antes do candidato (a ação vem antes do comentário), nunca # além; duração de 60 a 90 s. assert verdict.score == 10.0 and verdict.start_s == 80 and verdict.end_s == 170 assert "Duração do corte: 60 a 90 s" in prompt and "Janela disponível: 0s a 135s" in prompt old = _clean({"keep": True, "score": 8, "start_s": 0, "end_s": 500, "title": "t", "caption": "c", "reason": "r"}, 90, 120, "m", lo=30, hi=135, min_s=15, max_s=59) assert (old.start_s, old.end_s) == (30, 89) # configuração antiga (15–59 s) continua valendo se o canal pedir longer = _clean({"keep": True, "score": 8, "start_s": 70, "end_s": 160, "title": "t", "caption": "c", "reason": "r"}, 90, 120, "m", lo=30, hi=135, max_s=90) assert (longer.start_s, longer.end_s) == (70, 135) # duração máxima configurável (até 180 s) class FakeJudge(Judge): def __init__(self, keep=True, score=8.0): super().__init__("codex", "fake", Path(".")) self.keep, self.score_value, self.calls = keep, score, 0 def ask(self, system, prompt, schema, images, **_kwargs): # Nunca chama a CLI de verdade nos testes (gastaria a cota do dono): analista, varredura e "IA sugere" # seguem o caminho de falha da IA, que o serviço já trata. raise JudgeError("IA falsa nos testes") def judge(self, prompt, start_s, end_s, images=None, **_limits): self.calls += 1 return Verdict(self.keep, self.score_value, start_s, end_s, "Título da IA", "legenda #cortes", "motivo", "fake") @pytest.fixture def env(tmp_path): settings = Settings.load(env_file=tmp_path / "none.env", service_key=KEY, data_dir=tmp_path / "data", clips_dir=tmp_path / "clips", judge_provider="codex", voice_url=None, voice_key=None) db = Database(settings.data_dir / "clipper.db") engine = Engine(settings, db, judge=FakeJudge()) app = create_app(settings, engine, start_engine=False) return TestClient(app), engine def auth(): return {"X-Service-Key": KEY} def test_auth_required(env): client, _ = env assert client.get("/health").status_code == 200 assert client.get("/v1/channels").status_code == 401 assert client.get("/v1/channels", headers={"X-Service-Key": "errada"}).status_code == 401 def test_channel_crud(env): client, _ = env r = client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth()) assert r.status_code == 201 and r.json()["id"] == "twitch-alanzoka" and r.json()["displayName"] == "alanzoka" assert client.post("/v1/channels", json={"url": "twitch.tv/alanzoka"}, headers=auth()).status_code == 409 assert client.post("/v1/channels", json={"url": "https://www.twitch.tv/videos/1"}, headers=auth()).status_code == 400 r = client.patch("/v1/channels/twitch-alanzoka", json={"monitor": False, "displayName": "Alanzoka"}, headers=auth()) assert r.json()["monitor"] is False and r.json()["displayName"] == "Alanzoka" assert client.delete("/v1/channels/twitch-alanzoka", headers=auth()).status_code == 204 assert client.get("/v1/channels", headers=auth()).json()["channels"] == [] def seed_session(engine: Engine, duration: int = 600, burst_at: int = 300) -> int: db = engine.db cur = db.run("INSERT INTO sessions (platform, kind, url, status, dir, started_at, duration_s) VALUES" " ('twitch', 'live', 'https://www.twitch.tv/alanzoka', 'processing', '', '2026-11-16T00:00:00+00:00', ?)", duration) sid = cur.lastrowid base_wall = 10_000.0 for i in range(duration // 30): db.run("INSERT INTO segments (session_id, idx, file, start_s, end_s, wall_end, analyzed, loudness_json, words_json)" " VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)", sid, i, f"x/seg_{i:05d}.ts", i * 30.0, (i + 1) * 30.0, base_wall + (i + 1) * 30.0, json.dumps([-30.0] * 30), json.dumps([[i * 30 + 1.0, i * 30 + 1.5, "fala"]])) rows = [] for t in range(duration): rows.append((sid, base_wall + t + 0.5, "u", "salve")) rows.append((sid, base_wall + t + 0.7, "u", "oi")) for s in range(8): for k in range(25): rows.append((sid, base_wall + burst_at + s + k / 25, "u", "KKKKKKK")) db.many("INSERT INTO chat (session_id, wall, user, text) VALUES (?, ?, ?, ?)", rows) return sid def test_pipeline_finds_judges_and_lists_clip(env): client, engine = env sid = seed_session(engine) session = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid) assert engine.find_new_clips(session) == 1 assert engine.find_new_clips(session) == 0 # não repete o mesmo trecho engine.judge_candidates() clip = client.get("/v1/clips", headers=auth()).json()["clips"][0] assert clip["status"] == "pending" and clip["title"] == "Título da IA" assert "twitch.tv/alanzoka" in clip["caption"] # crédito do canal sempre na legenda assert clip["judge"]["score"] == 8.0 # aprovar antes do render é recusado assert client.patch(f"/v1/clips/{clip['id']}", json={"status": "approved"}, headers=auth()).status_code == 400 # mudar o trecho volta para a fila de render r = client.patch(f"/v1/clips/{clip['id']}", json={"startS": clip["startS"] - 3}, headers=auth()) assert r.json()["status"] == "pending" tl = client.get(f"/v1/sessions/{sid}/timeline", headers=auth()).json() assert tl["durationS"] == 600 and max(tl["messagesPerS"]) >= 25 def test_judge_config_persists(env, tmp_path): client, engine = env r = client.get("/v1/judge", headers=auth()).json() assert r["provider"] == "codex" and "codex" in r["models"] r = client.put("/v1/judge", json={"provider": "claude", "model": "", "minScore": 7}, headers=auth()) assert r.status_code == 200 and r.json()["model"] == "haiku" and r.json()["minScore"] == 7 assert client.put("/v1/judge", json={"provider": "gpt", "model": ""}, headers=auth()).status_code == 422 assert client.put("/v1/judge", json={"provider": "codex", "model": "x; rm -rf"}, headers=auth()).status_code == 422 saved = {r["key"]: r["value"] for r in engine.db.all("SELECT * FROM settings")} assert saved == {"judge_provider": "claude", "judge_model": "haiku", "judge_min_score": "7.0", "judge_analyst_model": ""} def test_manual_clip_is_never_discarded(env): client, engine = env engine.judge = FakeJudge(keep=False, score=1) sid = seed_session(engine) r = client.post(f"/v1/sessions/{sid}/clips", json={"lastS": 40}, headers=auth()) assert r.status_code == 201 and r.json()["startS"] == 560 engine.judge_candidates() clip = client.get(f"/v1/clips/{r.json()['id']}", headers=auth()).json() assert clip["status"] == "pending" and (clip["startS"], clip["endS"]) == (560, 600) def test_codex_models_reads_cache(tmp_path): from app.judge import codex_models cache = tmp_path / "m.json" cache.write_text(json.dumps({"models": [{"slug": "gpt-6-luna", "display_name": "GPT-6-Luna", "visibility": "list"}, {"slug": "hidden", "visibility": "hide"}]})) assert [m["id"] for m in codex_models(cache)] == ["gpt-6-luna"] assert codex_models(tmp_path / "nao-existe.json")[0]["id"] == "gpt-6-luna" def test_codex_lean_overrides(tmp_path): from app.judge import codex_lean_overrides config = tmp_path / "config.toml" config.write_text('[mcp_servers.node_repl]\ncommand = "x"\n[mcp_servers.node_repl.env]\n' '[plugins."computer-use@openai-bundled"]\nenabled = true\n') plain = codex_lean_overrides(False, config) assert plain.count("-c") == len(plain) // 2 assert "features.shell_tool=false" in plain and "features.computer_use=false" in plain # Um servidor por nome (a subtabela .env não vira outro servidor) e o plugin presente no config. assert plain.count("mcp_servers.node_repl.enabled=false") == 1 assert 'plugins."computer-use@openai-bundled".enabled=false' in plain assert not any("unified-computer-use" in a for a in plain) # Com busca na web, as ferramentas de execução ficam (a web do Codex depende delas). searching = codex_lean_overrides(True, config) assert "features.shell_tool=false" not in searching and "features.computer_use=false" in searching assert codex_lean_overrides(False, tmp_path / "nao-existe.toml")[-1] == "features.browser_use=false" def test_judge_discard_keeps_record(env): client, engine = env engine.judge = FakeJudge(keep=False, score=3) sid = seed_session(engine) engine.find_new_clips(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)) engine.judge_candidates() clip = client.get("/v1/clips?status=discarded", headers=auth()).json()["clips"][0] assert clip["judge"]["keep"] is False r = client.post(f"/v1/clips/{clip['id']}/render", headers=auth()) assert r.json()["status"] == "pending" def test_data_and_output_dirs_can_be_isolated(tmp_path, monkeypatch): """CLIPPER_DATA_DIR/CLIPPER_OUTPUT_DIR: instância de teste isolada; padrão igual ao de antes; fora do repo = erro.""" from app.config import REPO_ROOT, ConfigError for name in ("CLIPPER_DATA_DIR", "CLIPPER_OUTPUT_DIR"): monkeypatch.delenv(name, raising=False) s = Settings.load(env_file=tmp_path / "none.env") assert s.data_dir == REPO_ROOT / "data" / "clipper" and s.clips_dir == REPO_ROOT / "output" / "clipper" monkeypatch.setenv("CLIPPER_DATA_DIR", "output/x-test/data") monkeypatch.setenv("CLIPPER_OUTPUT_DIR", str(REPO_ROOT / "output" / "x-test" / "clips")) s = Settings.load(env_file=tmp_path / "none.env") assert s.data_dir == REPO_ROOT / "output" / "x-test" / "data" assert (s.data_dir / "sessions" / "1").relative_to(REPO_ROOT).as_posix() == "output/x-test/data/sessions/1" assert s.clips_dir == REPO_ROOT / "output" / "x-test" / "clips" monkeypatch.setenv("CLIPPER_DATA_DIR", str(tmp_path / "fora")) with pytest.raises(ConfigError): Settings.load(env_file=tmp_path / "none.env") def test_list_clips_filters_by_channel_and_ids(env): """Filtros usados pelo despachante de publicação do painel: fonte (`channel`) e lista de `ids`.""" client, engine = env client.post("/v1/channels", json={"url": "https://www.twitch.tv/alanzoka"}, headers=auth()) sid = seed_session(engine) engine.db.run("UPDATE sessions SET channel_id = 'twitch-alanzoka' WHERE id = ?", sid) other = seed_session(engine) for s in (sid, other): engine.db.run("INSERT INTO clips (session_id, peak_s, start_s, end_s, score, source, status, created_at, updated_at)" " VALUES (?, 10, 0, 20, 5, 'manual', 'ready', 'x', 'x')", s) mine = client.get("/v1/clips?status=ready,approved&channel=twitch-alanzoka", headers=auth()).json()["clips"] assert [c["channelId"] for c in mine] == ["twitch-alanzoka"] all_ids = [c["id"] for c in client.get("/v1/clips", headers=auth()).json()["clips"]] picked = client.get(f"/v1/clips?ids={all_ids[0]}", headers=auth()).json()["clips"] assert [c["id"] for c in picked] == [all_ids[0]] assert client.get("/v1/clips?ids=1,abc", headers=auth()).status_code == 400