Files
MateuusandClaude Opus 5.5 84f30bbc2d CenaForge: primeira versão pública
Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz,
Clipador de lives e Publicador para YouTube, TikTok e Instagram.

Inclui a leitura das visualizações dos posts para o Dashboard e o botão
"Publicar no <rede>" nos cartões das publicações.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:35:09 -03:00

167 lines
6.8 KiB
Python

"""Retomada de live depois de reinício ou de queda da captura (bug de 16/11/2026, sessão 3 do skipnho): a 1ª
checagem logo depois do reinício falhou e a live, que estava no ar, foi direto para o processamento."""
import subprocess
from types import SimpleNamespace
import pytest
import app.worker as worker_module
from app.worker import LiveCheck
from .test_sources_and_api import env, seed_session # noqa: F401 - fixture reaproveitada
class FakeCapture:
started: list[int] = []
def __init__(self, eng, session_id, source, workdir, start_idx=0):
FakeCapture.started.append(start_idx)
self.chat = None
def start(self):
pass
@pytest.fixture
def live(env, monkeypatch): # noqa: F811
client, engine = env
sid = seed_session(engine)
engine.db.run("UPDATE sessions SET status = 'interrupted' WHERE id = ?", sid)
engine.resume_delays = (0.0,) * 7
FakeCapture.started = []
monkeypatch.setattr(worker_module, "Capture", FakeCapture)
return engine, sid
def scripted(engine, results):
calls = []
def check(url):
calls.append(url)
return results[min(len(calls), len(results)) - 1]
engine.live_check = check
return calls
def status(engine, sid):
return engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"]
def test_startup_resume_retries_until_the_check_works(live):
engine, sid = live
unknown = LiveCheck("unknown", reason="streamlink --json passou de 60 s")
calls = scripted(engine, [unknown, unknown, unknown, LiveCheck("live", {"title": "t"})])
engine.resume_interrupted([sid])
assert len(calls) == 4 and FakeCapture.started == [20] # retomou na mesma sessão, continuando a numeração
assert status(engine, sid) == "starting" # gravando de novo, não processando
def test_startup_resume_gives_up_only_after_all_attempts(live):
engine, sid = live
calls = scripted(engine, [LiveCheck("unknown", reason="erro")])
seen = []
original = engine.live_check
def check(url):
seen.append(status(engine, sid)) # enquanto tenta, a sessão continua 'interrupted'
return original(url)
engine.live_check = check
engine.resume_interrupted([sid])
assert len(calls) == len(engine.resume_delays) and set(seen) == {"interrupted"}
assert FakeCapture.started == [] and status(engine, sid) == "processing"
def test_offline_confirmed_twice_finishes_early(live):
engine, sid = live
calls = scripted(engine, [LiveCheck("offline", reason="No playable streams")])
engine.resume_interrupted([sid])
assert len(calls) == 2 and status(engine, sid) == "processing"
# "offline" isolado entre falhas de checagem não conta como confirmação
engine.db.run("UPDATE sessions SET status = 'interrupted' WHERE id = ?", sid)
off, unk = LiveCheck("offline"), LiveCheck("unknown")
calls = scripted(engine, [off, unk, off, unk, off, unk, off])
engine.resume_interrupted([sid])
assert len(calls) == 7
def test_owner_action_in_the_middle_wins(live):
engine, sid = live
def check(url):
engine.db.run("UPDATE sessions SET status = 'processing' WHERE id = ?", sid) # você clicou "Processar"
return LiveCheck("live", {"title": "t"})
engine.live_check = check
assert engine.keep_live(sid, "teste") is False
assert FakeCapture.started == [] and status(engine, sid) == "processing"
def test_capture_drop_mid_live_reconnects(live):
engine, sid = live
engine.db.run("UPDATE sessions SET status = 'recording' WHERE id = ?", sid)
scripted(engine, [LiveCheck("unknown"), LiveCheck("live", {"title": "t"})])
started = []
engine.keep_live = lambda session_id, why: started.append(why) # a thread chamaria keep_live
engine.capture_dropped(sid, got_video=True)
import time
for _ in range(50):
if started:
break
time.sleep(0.02)
assert status(engine, sid) == "interrupted" and started == ["captura caiu"]
# Retomadas seguidas sem nenhum bloco novo: desiste depois de MAX_EMPTY_RESUMES e processa.
for _ in range(worker_module.MAX_EMPTY_RESUMES):
engine.db.run("UPDATE sessions SET status = 'recording' WHERE id = ?", sid)
engine.capture_dropped(sid, got_video=False)
assert status(engine, sid) == "processing"
def _fake_run(monkeypatch, stdout=b"", stderr=b"", code=0, exc=None):
def run(*_args, **_kwargs):
if exc:
raise exc
return SimpleNamespace(stdout=stdout, stderr=stderr, returncode=code)
monkeypatch.setattr(worker_module.subprocess, "run", run)
@pytest.mark.parametrize("kwargs,state", [
({"stdout": b'{"streams": {"best": {}}, "metadata": {"title": "oi", "category": "GTA"}}'}, "live"),
({"stdout": b'{"error": "No playable streams found on this URL: https://www.twitch.tv/x"}', "code": 1}, "offline"),
({"exc": subprocess.TimeoutExpired("streamlink", 60)}, "unknown"),
({"exc": OSError("não achou")}, "unknown"),
({"stdout": b"<html>erro</html>", "stderr": b"error: rede", "code": 1}, "unknown"),
({"stdout": b'{"error": "Unable to open URL: https://gql.twitch.tv (503 Server Error)"}', "code": 1}, "unknown"),
])
def test_live_check_tells_offline_from_check_failure(env, monkeypatch, caplog, kwargs, state): # noqa: F811
_client, engine = env
from dataclasses import replace
engine.settings = replace(engine.settings, streamlink="streamlink")
_fake_run(monkeypatch, **kwargs)
result = engine.live_check("https://www.twitch.tv/x")
assert result.state == state
if state == "live":
assert result.meta["category"] == "GTA" and engine.check_live("u") == (True, "oi")
else:
assert engine.check_meta("u") is None # quem só quer saber "está ao vivo?" continua recebendo None
if state == "unknown":
assert "checagem da live" in caplog.text and result.reason # motivo registrado no log
@pytest.mark.skipif(not __import__("shutil").which("ffmpeg"), reason="FFmpeg não instalado")
def test_capture_that_stops_by_itself_goes_to_reconnect(env, tmp_path, monkeypatch): # noqa: F811
"""Captura de live que para sem stop() (aqui o "streamlink" sai na hora) não processa direto: vai para a
retomada com novas tentativas."""
import shutil
import sys
from dataclasses import replace
from app.sources import parse_source
_client, engine = env
sid = seed_session(engine)
engine.settings = replace(engine.settings, streamlink=sys.executable, ffmpeg=shutil.which("ffmpeg"))
dropped = []
monkeypatch.setattr(engine, "capture_dropped", lambda session_id, got_video: dropped.append((session_id, got_video)))
capture = worker_module.Capture(engine, sid, parse_source("https://www.twitch.tv/alanzoka"), tmp_path / "cap", start_idx=20)
capture.thread.start() # sem o chat (não abre conexão)
capture.thread.join(timeout=60)
assert dropped == [(sid, False)]