Files
CenaForge/clipper/tests/test_monitor_pause_and_language.py
T
MateuusandClaude Opus 5.5 0567c7454a Clipador: subpáginas, jogos, idioma por canal e juiz com Gemini e IA reserva
- Clipador em subpáginas (Cortes, Sessões, Fontes, Jogos, Ajustes) com moldura comum, lista + diálogo
  dos cortes e submenu na barra lateral.
- Perfis de jogo (o que a IA sabe de cada jogo), parar pausa o monitor e idioma por fonte e por canal
  de publicação (migração v9: accounts.language).
- Juiz: Gemini CLI como terceiro provedor e IA reserva por chamada — se a IA escolhida cair por cota,
  login, chave ou rede, a próxima da ordem de Configurações → IA responde (com pausa da que caiu).
  Lê data/ai/settings.json e o cofre data/ai/vault.bin (DPAPI) escritos pelo painel; contrato em doc/ia.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 01:51:12 -03:00

171 lines
8.3 KiB
Python

"""Parar à mão pausa o monitor da fonte (reclamação de 18/11/2026: 60 s depois de "Parar" o monitor abria uma sessão
nova, porque a live continuava no ar) e idioma por fonte/sessão (transcrição e textos da IA em outro idioma)."""
from dataclasses import replace
import pytest
import app.worker as worker_module
from app.judge import output_language_note
from .test_sources_and_api import auth, env # noqa: F401 - fixture reaproveitada
URL = "https://www.twitch.tv/alanzoka"
CHANNEL = "twitch-alanzoka"
class FakeCapture:
"""Captura falsa: `stop` avisa o motor como a real faz ao terminar (sai de `captures`, senão não dá para retomar)."""
def __init__(self, eng, session_id, source, workdir, start_idx=0):
self.eng, self.session_id = eng, session_id
self.chat = None
def start(self):
pass
def stop(self):
self.eng.capture_finished(self.session_id)
@pytest.fixture
def ready(env, monkeypatch): # noqa: F811
"""Serviço com ferramentas "achadas", captura falsa e a live sempre no ar (sem Streamlink de verdade)."""
client, engine = env
monkeypatch.setattr(engine, "settings", replace(engine.settings, streamlink="streamlink", ffmpeg="ffmpeg"))
monkeypatch.setattr(worker_module, "Capture", FakeCapture)
monkeypatch.setattr(engine, "_fill_title", lambda *_a, **_k: None)
# A pasta de dados do teste fica fora do repositório: o caminho relativo da sessão não importa aqui.
monkeypatch.setattr(worker_module, "rel", lambda path: path.as_posix())
engine.check_live = lambda url: (True, "live no ar")
return client, engine
def channel(client):
return next(c for c in client.get("/v1/channels", headers=auth()).json()["channels"] if c["id"] == CHANNEL)
def test_stop_by_hand_pauses_monitor_until_relit(ready):
client, engine = ready
assert client.post("/v1/channels", json={"url": URL}, headers=auth()).status_code == 201
started = engine.monitor_once()
assert len(started) == 1
sid = started[0]
assert channel(client)["monitorPausedAt"] is None
# Parar sem corpo (painel antigo) = pausa o monitor da fonte.
assert client.post(f"/v1/sessions/{sid}/stop", headers=auth()).json() == {"ok": True}
c = channel(client)
assert c["monitor"] is True and c["monitorPausedAt"] and c["monitorPausedBySession"] == sid
assert engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"] == "stopped"
# A live continua no ar, mas o monitor NÃO abre sessão nova.
assert engine.monitor_once() == []
assert engine.db.get("SELECT COUNT(*) AS n FROM sessions")["n"] == 1
# "Religar" = PATCH monitor=true limpa a pausa; a próxima passada grava de novo.
r = client.patch(f"/v1/channels/{CHANNEL}", json={"monitor": True}, headers=auth())
assert r.json()["monitorPausedAt"] is None and r.json()["monitorPausedBySession"] is None
assert len(engine.monitor_once()) == 1
def test_stop_without_pause_keeps_monitor(ready):
client, engine = ready
client.post("/v1/channels", json={"url": URL}, headers=auth())
sid = engine.monitor_once()[0]
client.post(f"/v1/sessions/{sid}/stop", json={"pauseMonitor": False}, headers=auth())
assert channel(client)["monitorPausedAt"] is None
assert len(engine.monitor_once()) == 1 # a live segue no ar: grava de novo (você pediu assim)
def test_recording_by_link_or_resuming_relights_monitor(ready):
client, engine = ready
client.post("/v1/channels", json={"url": URL}, headers=auth())
sid = engine.monitor_once()[0]
client.post(f"/v1/sessions/{sid}/stop", headers=auth())
assert channel(client)["monitorPausedAt"]
# Gravar pelo link à mão: você ligou de propósito → a pausa some.
r = client.post("/v1/sessions", json={"url": URL}, headers=auth())
assert r.status_code == 201 and r.json()["id"] != sid
assert channel(client)["monitorPausedAt"] is None
# Parar de novo e retomar pelo painel também religa.
client.post(f"/v1/sessions/{r.json()['id']}/stop", headers=auth())
assert channel(client)["monitorPausedAt"]
assert client.post(f"/v1/sessions/{r.json()['id']}/resume", headers=auth()).status_code == 200
assert channel(client)["monitorPausedAt"] is None
def test_deleting_a_session_does_not_pause(ready):
client, engine = ready
client.post("/v1/channels", json={"url": URL}, headers=auth())
sid = engine.monitor_once()[0]
assert client.delete(f"/v1/sessions/{sid}", headers=auth()).status_code == 204
assert channel(client)["monitorPausedAt"] is None
def test_unmonitored_channel_is_not_paused(ready):
client, engine = ready
client.post("/v1/channels", json={"url": URL, "monitor": False}, headers=auth())
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
client.post(f"/v1/sessions/{sid}/stop", headers=auth())
assert channel(client)["monitorPausedAt"] is None # nada a pausar: o monitor já estava desligado
# ---------- idioma
def test_language_on_channel_and_session(ready):
client, engine = ready
default = engine.settings.language
r = client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
assert r.status_code == 201 and r.json()["language"] == "en-US"
assert client.post("/v1/channels", json={"url": "https://kick.com/gaules", "language": "xx"}, headers=auth()).status_code == 400
r2 = client.post("/v1/channels", json={"url": "https://kick.com/gaules"}, headers=auth())
assert r2.json()["language"] == default # sem idioma = padrão do serviço, já resolvido na visão
# A sessão herda o idioma da fonte; `language` explícito vence; VOD solto fica no padrão.
s = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()
assert s["language"] == "en-US"
assert engine.db.get("SELECT language FROM sessions WHERE id = ?", s["id"])["language"] == "en-US"
s2 = client.post("/v1/sessions", json={"url": "https://kick.com/gaules", "language": "es-419"}, headers=auth()).json()
assert s2["language"] == "es-419"
assert client.post("/v1/sessions", json={"url": URL, "language": "klingon"}, headers=auth()).status_code == 400
# PATCH troca ('' volta ao padrão) e não mexe quando ausente.
assert client.patch(f"/v1/channels/{CHANNEL}", json={"displayName": "Alan"}, headers=auth()).json()["language"] == "en-US"
assert client.patch(f"/v1/channels/{CHANNEL}", json={"language": ""}, headers=auth()).json()["language"] == default
assert client.get("/v1/status", headers=auth()).json()["settings"]["language"] == default
def test_language_note_reaches_the_ai_context(ready):
client, engine = ready
assert output_language_note("pt-BR") == "" and output_language_note("") == "" and output_language_note(None) == ""
assert "English (US)" in output_language_note("en-US")
client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
gringa = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
assert "Idioma de saída: English (US)" in engine.intel.context(gringa)
engine.db.run("UPDATE sessions SET language = '' WHERE id = ?", sid)
assert "Idioma de saída" not in engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
def test_transcription_uses_session_language(ready, monkeypatch):
_client, engine = ready
seen = {}
class FakeVoice:
configured = True
def transcribe(self, wav, key, language=None):
seen["language"] = language
return []
monkeypatch.setattr(engine, "voice", FakeVoice())
monkeypatch.setattr(worker_module.media, "decode_pcm", lambda *_a, **_k: b"")
monkeypatch.setattr(worker_module.media, "loudness_per_second", lambda _pcm: [])
monkeypatch.setattr(worker_module.media, "to_wav", lambda _pcm: b"")
cur = engine.db.run("INSERT INTO sessions (platform, kind, url, status, dir, started_at, language) VALUES"
" ('twitch', 'live', ?, 'processing', '', '2026-11-18T00:00:00+00:00', 'en-US')", URL)
sid = cur.lastrowid
engine.db.run("INSERT INTO segments (session_id, idx, file, start_s, end_s, wall_end) VALUES (?, 0, 'x/seg.ts', 0, 30, 0)", sid)
engine.analyze_segment(engine.db.get("SELECT * FROM segments WHERE session_id = ?", sid))
assert seen["language"] == "en-US"