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>
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""Fixtures dos testes do Publicador: tudo em tmp_path, cofre com cifrador falso, rede simulada (httpx.MockTransport)
|
||||
e navegador falso. Nenhum teste abre navegador nem fala com a internet."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.config import Settings
|
||||
from app.db import Database
|
||||
from app.main import create_app
|
||||
from app.platforms.base import PublishResult
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager
|
||||
from app.service import Publisher
|
||||
from app.vault import Vault
|
||||
from app.worker import Worker
|
||||
|
||||
KEY = "k" * 40
|
||||
|
||||
|
||||
class FakeCipher:
|
||||
"""Inverte e marca os bytes: suficiente para provar que o arquivo não fica em texto puro."""
|
||||
|
||||
def protect(self, data: bytes) -> bytes:
|
||||
return b"FAKE" + data[::-1]
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
assert data.startswith(b"FAKE")
|
||||
return data[4:][::-1]
|
||||
|
||||
|
||||
class Router:
|
||||
"""Rede simulada: registra handlers por (método, prefixo da URL) e guarda todas as requisições."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.routes: list[tuple[str, str, Callable[[httpx.Request], httpx.Response]]] = []
|
||||
self.requests: list[httpx.Request] = []
|
||||
|
||||
def add(self, method: str, prefix: str, handler: Callable[[httpx.Request], httpx.Response] | dict | list) -> None:
|
||||
if not callable(handler):
|
||||
payload = handler
|
||||
handler = lambda _req, payload=payload: httpx.Response(200, json=payload) # noqa: E731
|
||||
self.routes.insert(0, (method, prefix, handler))
|
||||
|
||||
def __call__(self, request: httpx.Request) -> httpx.Response:
|
||||
request.read()
|
||||
self.requests.append(request)
|
||||
url = str(request.url)
|
||||
for method, prefix, handler in self.routes:
|
||||
if request.method == method and url.startswith(prefix):
|
||||
return handler(request)
|
||||
return httpx.Response(599, json={"error": f"rota não simulada: {request.method} {url}"})
|
||||
|
||||
def find(self, method: str, prefix: str) -> list[httpx.Request]:
|
||||
return [r for r in self.requests if r.method == method and str(r.url).startswith(prefix)]
|
||||
|
||||
|
||||
class FakeRunner:
|
||||
"""Substitui o SessionRunner (Playwright) nos testes."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.opened: list[tuple[str, str]] = []
|
||||
self.check_reason: str | None = None
|
||||
self.result = PublishResult(None, None, False, "Publicado (sessão); link não encontrado na tela")
|
||||
self.error: Exception | None = None
|
||||
|
||||
def open_for_login(self, profile_id: str, platform: str) -> None:
|
||||
self.opened.append((profile_id, platform))
|
||||
|
||||
def check(self, profile_id: str, platform: str) -> str | None:
|
||||
return self.check_reason
|
||||
|
||||
def publish(self, spec, progress):
|
||||
progress("Enviando pelo navegador…", 0.5)
|
||||
if self.error:
|
||||
raise self.error
|
||||
return self.result
|
||||
|
||||
|
||||
class Env:
|
||||
def __init__(self, tmp_path: Path):
|
||||
self.root = tmp_path / "repo"
|
||||
self.root.mkdir()
|
||||
self.settings = Settings.load(env_file=tmp_path / "none.env", service_key=KEY,
|
||||
data_dir=self.root / "data" / "publisher", repo_root=self.root)
|
||||
self.router = Router()
|
||||
self.http = httpx.Client(transport=httpx.MockTransport(self.router))
|
||||
self.db = Database(self.settings.db_path)
|
||||
self.vault = Vault(self.settings.vault_path, cipher=FakeCipher())
|
||||
self.runner = FakeRunner()
|
||||
self.sleeps: list[float] = []
|
||||
browsers = BrowserManager(self.settings.browser_dir, BrowserInfo("chrome", "C:/fake/chrome.exe"))
|
||||
self.publisher = Publisher(self.settings, self.db, self.vault, http=self.http, browsers=browsers,
|
||||
runner=self.runner, sleep=self.sleeps.append, # type: ignore[arg-type]
|
||||
detect=lambda: BrowserInfo("chrome", "C:/fake/chrome.exe"))
|
||||
self.worker = Worker(self.db, self.publisher.execute)
|
||||
self.app = create_app(self.settings, self.publisher, start_worker=False, worker=self.worker)
|
||||
self.client = TestClient(self.app, headers={"X-Service-Key": KEY})
|
||||
|
||||
def video(self, name: str = "clip.mp4", size: int = 1000) -> Path:
|
||||
path = self.root / "output" / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(bytes(range(256)) * (size // 256) + b"x" * (size % 256))
|
||||
return path
|
||||
|
||||
def connect_profile(self, profile_id: str, mode: str = "official", secret: dict | None = None, **fields) -> None:
|
||||
platform = profile_id.rsplit("--", 1)[1]
|
||||
self.publisher._update(profile_id, mode=mode, status="connected", connected_at="2026-11-17T00:00:00Z", **fields)
|
||||
if secret is not None:
|
||||
self.vault.set(f"token:{profile_id}", secret)
|
||||
assert platform
|
||||
|
||||
def job_body(self, profile_id: str, file: Path, **extra) -> dict:
|
||||
body = {"profileId": profile_id, "platform": profile_id.rsplit("--", 1)[1], "file": str(file), "cover": None,
|
||||
"title": "Meu vídeo", "caption": "Legenda #cortes", "tags": ["cortes", "live"], "privacy": "public",
|
||||
"publishAt": None, "aiGenerated": False, "madeForKids": False, "tiktokMode": "direct"}
|
||||
body.update(extra)
|
||||
return body
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path):
|
||||
e = Env(tmp_path)
|
||||
yield e
|
||||
e.db.close()
|
||||
|
||||
|
||||
def json_body(request: httpx.Request) -> dict:
|
||||
return json.loads(request.content or b"{}")
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Rotas, chave do serviço e contrato JSON (doc/publicacao/PLANO.md §3)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.conftest import KEY
|
||||
|
||||
PID = "historias-do-litoral--youtube"
|
||||
|
||||
|
||||
def test_health_is_open_and_everything_else_needs_key(env):
|
||||
anon = TestClient(env.app)
|
||||
assert anon.get("/health").json() == {"ok": True}
|
||||
for method, path in [("get", "/v1/status"), ("get", "/v1/apps"), ("get", f"/v1/profiles/{PID}"),
|
||||
("post", "/v1/jobs"), ("get", "/v1/jobs/x")]:
|
||||
response = getattr(anon, method)(path)
|
||||
assert response.status_code == 401
|
||||
assert response.json() == {"detail": "Chave do serviço ausente ou inválida."}
|
||||
wrong = TestClient(env.app, headers={"X-Service-Key": "errada"})
|
||||
assert wrong.get("/v1/status").status_code == 401
|
||||
assert KEY # a chave certa passa (fixture)
|
||||
assert env.client.get("/v1/status").status_code == 200
|
||||
|
||||
|
||||
def test_status_shape(env):
|
||||
body = env.client.get("/v1/status").json()
|
||||
assert body == {"browser": {"found": True, "kind": "chrome", "path": "C:/fake/chrome.exe"}, "worker": "idle", "queue": 0}
|
||||
|
||||
|
||||
def test_apps_never_return_secret(env):
|
||||
apps = env.client.get("/v1/apps").json()
|
||||
assert set(apps) == {"youtube", "tiktok", "instagram"}
|
||||
assert apps["youtube"] == {"configured": False, "clientId": None,
|
||||
"redirectUri": "http://127.0.0.1:4530/oauth/callback/youtube",
|
||||
"notes": apps["youtube"]["notes"]}
|
||||
assert apps["tiktok"]["redirectUri"] == "http://127.0.0.1:4530/oauth/callback/tiktok"
|
||||
assert apps["instagram"]["redirectUri"] == ""
|
||||
|
||||
state = env.client.put("/v1/apps/youtube", json={"clientId": "id.apps.googleusercontent.com", "clientSecret": "s3cr3t"}).json()
|
||||
assert state["configured"] is True and state["clientId"] == "id.apps.googleusercontent.com"
|
||||
assert "s3cr3t" not in env.client.get("/v1/apps").text
|
||||
assert b"s3cr3t" not in env.settings.vault_path.read_bytes() # cofre cifrado em disco
|
||||
|
||||
missing = env.client.put("/v1/apps/tiktok", json={"clientId": "abc", "clientSecret": ""})
|
||||
assert missing.status_code == 400 and "Client Secret" in missing.json()["detail"]
|
||||
assert env.client.put("/v1/apps/instagram", json={"clientId": "123"}).json()["configured"] is True
|
||||
assert env.client.delete("/v1/apps/youtube").json()["configured"] is False
|
||||
assert env.client.put("/v1/apps/vimeo", json={"clientId": "x", "clientSecret": "y"}).status_code == 404
|
||||
|
||||
|
||||
def test_profile_defaults_and_validation(env):
|
||||
profile = env.client.get(f"/v1/profiles/{PID}").json()
|
||||
assert profile == {"profileId": PID, "platform": "youtube", "mode": None, "status": "disconnected",
|
||||
"displayName": None, "handle": None, "connectedAt": None, "expiresAt": None,
|
||||
"lastCheckAt": None, "lastError": None}
|
||||
bad = env.client.get("/v1/profiles/..%2F..%2Fetc--youtube")
|
||||
assert bad.status_code in (400, 404)
|
||||
assert env.client.get("/v1/profiles/canal--vimeo").status_code == 400
|
||||
mismatch = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "tiktok", "mode": "official"})
|
||||
assert mismatch.status_code == 400 and "YouTube" in mismatch.json()["detail"]
|
||||
|
||||
|
||||
def test_validation_errors_are_ptbr_strings(env):
|
||||
response = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "robô"})
|
||||
assert response.status_code == 422
|
||||
detail = response.json()["detail"]
|
||||
assert isinstance(detail, str) and detail.startswith("Pedido inválido") and "modo" in detail
|
||||
assert "falta o campo" in env.client.post("/v1/jobs", json={}).json()["detail"]
|
||||
|
||||
|
||||
def test_official_connect_requires_app(env):
|
||||
response = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "official"})
|
||||
assert response.status_code == 400
|
||||
assert "Apps das redes" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_instagram_official_asks_for_token(env):
|
||||
pid = "canal--instagram"
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": "instagram", "mode": "official"}).json()
|
||||
assert body["next"]["kind"] == "paste_token" and "token" in body["next"]["help"]
|
||||
assert body["profile"]["status"] == "connecting" and body["profile"]["mode"] == "official"
|
||||
assert env.client.post(f"/v1/profiles/{PID}/token", json={"accessToken": "x" * 30}).status_code == 400
|
||||
|
||||
|
||||
def test_session_connect_check_and_disconnect(env):
|
||||
pid = "canal--tiktok"
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": "tiktok", "mode": "session"}).json()
|
||||
assert body["next"]["kind"] == "browser_opened" and "Já entrei" in body["next"]["help"]
|
||||
assert body["profile"]["status"] == "connecting" and env.runner.opened == [(pid, "tiktok")]
|
||||
|
||||
env.runner.check_reason = "a rede mostrou a tela de login"
|
||||
profile = env.client.post(f"/v1/profiles/{pid}/session/check").json()
|
||||
assert profile["status"] == "needs_login" and "tela de login" in profile["lastError"]
|
||||
assert profile["lastCheckAt"]
|
||||
|
||||
env.runner.check_reason = None
|
||||
profile = env.client.post(f"/v1/profiles/{pid}/session/check").json()
|
||||
assert profile["status"] == "connected" and profile["lastError"] is None and profile["connectedAt"]
|
||||
|
||||
reopened = env.client.post(f"/v1/profiles/{pid}/session/open").json()
|
||||
assert reopened["next"]["kind"] == "browser_opened" and reopened["profile"]["status"] == "connected"
|
||||
|
||||
browser_dir = env.settings.browser_dir / pid
|
||||
browser_dir.mkdir(parents=True)
|
||||
(browser_dir / "Cookies").write_text("x")
|
||||
env.vault.set(f"token:{pid}", {"accessToken": "a"})
|
||||
gone = env.client.delete(f"/v1/profiles/{pid}").json()
|
||||
assert gone["status"] == "disconnected" and gone["mode"] is None
|
||||
assert not browser_dir.exists() and env.vault.get(f"token:{pid}") is None
|
||||
|
||||
|
||||
def test_session_check_requires_session_mode(env):
|
||||
response = env.client.post(f"/v1/profiles/{PID}/session/check")
|
||||
assert response.status_code == 400 and "Sessão logada" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_job_lifecycle_routes(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
video = env.video()
|
||||
created = env.client.post("/v1/jobs", json=env.job_body(PID, video))
|
||||
assert created.status_code == 201
|
||||
job = created.json()
|
||||
assert set(job) == {"jobId", "profileId", "platform", "status", "step", "progress", "remoteId", "url", "draft",
|
||||
"error", "createdAt", "updatedAt"}
|
||||
assert job["status"] == "queued" and job["progress"] == 0 and job["draft"] is False
|
||||
assert env.client.get(f"/v1/jobs/{job['jobId']}").json()["jobId"] == job["jobId"]
|
||||
assert env.client.get("/v1/status").json()["queue"] == 1
|
||||
canceled = env.client.post(f"/v1/jobs/{job['jobId']}/cancel").json()
|
||||
assert canceled["status"] == "canceled"
|
||||
again = env.client.post(f"/v1/jobs/{job['jobId']}/cancel")
|
||||
assert again.status_code == 409 and "na fila" in again.json()["detail"]
|
||||
assert env.client.get("/v1/jobs/nao-existe").status_code == 404
|
||||
|
||||
|
||||
def test_job_refuses_paths_outside_root(env, tmp_path):
|
||||
env.connect_profile(PID, mode="session")
|
||||
outside = tmp_path / "fora.mp4"
|
||||
outside.write_bytes(b"x" * 10)
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, outside))
|
||||
assert response.status_code == 400 and "pasta de saída do CenaForge" in response.json()["detail"]
|
||||
sneaky = str(env.root / "output" / ".." / ".." / "fora.mp4")
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, sneaky)).status_code == 400
|
||||
relative = env.client.post("/v1/jobs", json=env.job_body(PID, "output/clip.mp4"))
|
||||
assert relative.status_code == 400 and "absoluto" in relative.json()["detail"]
|
||||
video = env.video()
|
||||
bad_cover = env.client.post("/v1/jobs", json=env.job_body(PID, video, cover=str(outside)))
|
||||
assert bad_cover.status_code == 400
|
||||
missing = env.client.post("/v1/jobs", json=env.job_body(PID, str(env.root / "output" / "sumiu.mp4")))
|
||||
assert missing.status_code == 400 and "não existe" in missing.json()["detail"]
|
||||
wrong_ext = env.root / "output" / "a.exe"
|
||||
wrong_ext.write_bytes(b"MZ")
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, wrong_ext)).status_code == 400
|
||||
|
||||
|
||||
def test_job_requires_connected_profile_and_youtube_title(env):
|
||||
video = env.video()
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, video))
|
||||
assert response.status_code == 409 and "não está conectado" in response.json()["detail"]
|
||||
env.connect_profile(PID, mode="session")
|
||||
long_title = env.client.post("/v1/jobs", json=env.job_body(PID, video, title="x" * 101))
|
||||
assert long_title.status_code == 400 and "100" in long_title.json()["detail"]
|
||||
# TikTok/Instagram ignoram o título: não há limite de 100 para eles.
|
||||
env.connect_profile("canal--tiktok", mode="session")
|
||||
ok = env.client.post("/v1/jobs", json=env.job_body("canal--tiktok", video, title="x" * 300))
|
||||
assert ok.status_code == 201
|
||||
@@ -0,0 +1,323 @@
|
||||
"""Navegador do modo sessão: detecção, argumentos (sem burla de detecção), portas e apagar perfil.
|
||||
Nenhum navegador é aberto: o Popen é falso."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import BROWSER_PORT_RANGE
|
||||
from app.platforms.base import PublishError
|
||||
from app.platforms.session import common
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager, detect_browser, launch_args
|
||||
|
||||
|
||||
def _exe(base: Path, *parts: str) -> Path:
|
||||
path = base.joinpath(*parts)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"")
|
||||
return path
|
||||
|
||||
|
||||
def test_detect_prefers_chrome_then_edge(tmp_path):
|
||||
env = {"PROGRAMFILES": str(tmp_path / "pf"), "PROGRAMFILES(X86)": str(tmp_path / "pf86"),
|
||||
"LOCALAPPDATA": str(tmp_path / "local")}
|
||||
no_registry = lambda exe: None # noqa: E731
|
||||
edge = _exe(tmp_path / "pf86", "Microsoft", "Edge", "Application", "msedge.exe")
|
||||
assert detect_browser(env=env, registry=no_registry) == BrowserInfo("msedge", str(edge))
|
||||
chrome = _exe(tmp_path / "local", "Google", "Chrome", "Application", "chrome.exe")
|
||||
assert detect_browser(env=env, registry=no_registry) == BrowserInfo("chrome", str(chrome))
|
||||
assert detect_browser(override=str(edge)) == BrowserInfo("msedge", str(edge))
|
||||
assert detect_browser(override=str(tmp_path / "nao-existe.exe")) is None
|
||||
|
||||
|
||||
def test_detect_uses_registry(tmp_path):
|
||||
chrome = _exe(tmp_path, "custom", "chrome.exe")
|
||||
found = detect_browser(env={}, registry=lambda exe: str(chrome) if exe == "chrome.exe" else None)
|
||||
assert found == BrowserInfo("chrome", str(chrome))
|
||||
|
||||
|
||||
def test_launch_args_are_plain_and_visible(tmp_path):
|
||||
args = launch_args(BrowserInfo("chrome", "chrome.exe"), tmp_path / "p", 4541, "https://studio.youtube.com/")
|
||||
assert args[0] == "chrome.exe" and f"--user-data-dir={tmp_path / 'p'}" in args
|
||||
assert "--remote-debugging-port=4541" in args and "--no-first-run" in args
|
||||
joined = " ".join(args).lower()
|
||||
for forbidden in ("headless", "automationcontrolled", "stealth", "enable-automation", "disable-blink-features"):
|
||||
assert forbidden not in joined
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
pid = 1
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.args = args[0]
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
|
||||
def test_open_picks_port_in_range_and_reuses_window(tmp_path, monkeypatch):
|
||||
launched = []
|
||||
manager = BrowserManager(tmp_path / "browser", BrowserInfo("chrome", "chrome.exe"), start_reaper=False,
|
||||
popen=lambda args, **kw: launched.append(args) or FakeProcess(args))
|
||||
monkeypatch.setattr(manager, "_wait_cdp", lambda port, user_dir, process=None: None)
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: True)
|
||||
port = manager.open("canal--youtube", "https://x")
|
||||
assert BROWSER_PORT_RANGE[0] <= port <= BROWSER_PORT_RANGE[1]
|
||||
assert manager.open("canal--youtube", "https://x") == port and len(launched) == 1
|
||||
other = manager.open("canal--tiktok", "https://y")
|
||||
assert other != port and (tmp_path / "browser" / "canal--tiktok").is_dir()
|
||||
|
||||
|
||||
def test_open_without_browser_explains(tmp_path):
|
||||
with pytest.raises(PublishError, match="Chrome"):
|
||||
BrowserManager(tmp_path, None).open("canal--youtube", "https://x")
|
||||
|
||||
|
||||
def test_remove_profile_only_inside_browser_dir(tmp_path):
|
||||
manager = BrowserManager(tmp_path / "browser", None)
|
||||
target = tmp_path / "browser" / "canal--youtube"
|
||||
target.mkdir(parents=True)
|
||||
(target / "Cookies").write_text("x")
|
||||
manager.remove_profile("canal--youtube")
|
||||
assert not target.exists()
|
||||
with pytest.raises(PublishError):
|
||||
manager.remove_profile("../fora")
|
||||
|
||||
|
||||
class FakeLocator:
|
||||
def __init__(self, present):
|
||||
self.present = present
|
||||
|
||||
@property
|
||||
def first(self):
|
||||
return self
|
||||
|
||||
def nth(self, i):
|
||||
return self
|
||||
|
||||
def count(self):
|
||||
return 1 if self.present else 0
|
||||
|
||||
def is_visible(self):
|
||||
return self.present
|
||||
|
||||
|
||||
class FakePage:
|
||||
def __init__(self, url, texts=()):
|
||||
self.url, self.texts = url, texts
|
||||
|
||||
def get_by_role(self, role, name):
|
||||
return FakeLocator(any(name.search(t) for t in self.texts))
|
||||
|
||||
def get_by_text(self, pattern):
|
||||
return FakeLocator(any(pattern.search(t) for t in self.texts))
|
||||
|
||||
def get_by_label(self, pattern):
|
||||
return FakeLocator(False)
|
||||
|
||||
def get_by_placeholder(self, pattern):
|
||||
return FakeLocator(False)
|
||||
|
||||
def locator(self, css):
|
||||
return FakeLocator(False)
|
||||
|
||||
|
||||
def test_detect_block_login_and_captcha():
|
||||
assert common.detect_block(FakePage("https://accounts.google.com/v3/signin/identifier")) is not None
|
||||
assert common.detect_block(FakePage("https://www.instagram.com/challenge/123/")) is not None
|
||||
assert "verificação" in common.detect_block(FakePage("https://www.tiktok.com/x", ["Verify it's you"]))
|
||||
login = [("role", "button", r"^(Entrar|Log in)$")]
|
||||
assert "login" in common.detect_block(FakePage("https://www.tiktok.com/tiktokstudio/upload", ["Entrar"]), login)
|
||||
assert common.detect_block(FakePage("https://www.tiktok.com/tiktokstudio/upload", ["Publicar"]), login) is None
|
||||
err = common.needs_login("a rede pediu login")
|
||||
assert err.kind == "needs_login" and "Já entrei" in err.message
|
||||
|
||||
|
||||
class FakeListPage:
|
||||
"""Lista "Publicações" do Studio: o link só aparece depois de algumas leituras (a lista demora a carregar)."""
|
||||
|
||||
def __init__(self, href, ready_after=2, url="https://www.tiktok.com/tiktokstudio/upload"):
|
||||
self.href, self.ready_after, self.url, self.reads, self.visited = href, ready_after, url, 0, []
|
||||
|
||||
def evaluate(self, script, key):
|
||||
self.reads += 1
|
||||
return self.href if self.reads > self.ready_after and key else None
|
||||
|
||||
def goto(self, url, wait_until=None):
|
||||
self.visited.append(url)
|
||||
self.url = url
|
||||
|
||||
|
||||
def test_tiktok_link_waits_for_the_list_and_matches_caption():
|
||||
from app.platforms.session import tiktok_studio
|
||||
|
||||
assert tiktok_studio.caption_key("#corte Ele pediu pra todo mundo só olhar o loot #x @y") == "Ele pediu pra todo mundo"
|
||||
# O vídeo só aparece depois de 7 leituras: a 1ª carga (5 leituras) não vê ⇒ recarrega a lista e acha na 2ª.
|
||||
page = FakeListPage("https://www.tiktok.com/@vortplay/video/7709179978520284437", ready_after=7)
|
||||
steps = []
|
||||
url = tiktok_studio.find_video_url(page, "Ele pediu pra todo mundo só olhar o loot", sleep=lambda s: None,
|
||||
progress=lambda text, p: steps.append(text))
|
||||
assert url.endswith("/video/7709179978520284437")
|
||||
assert page.visited == [tiktok_studio.CONTENT_URL, tiktok_studio.CONTENT_URL] # abriu a lista e recarregou
|
||||
assert "2 de 12" in steps[-1]
|
||||
never = FakeListPage(None, ready_after=0)
|
||||
assert tiktok_studio.find_video_url(never, "outro vídeo", sleep=lambda s: None, attempts=3) is None
|
||||
assert len(never.visited) == 3 # uma carga por tentativa
|
||||
|
||||
|
||||
class TipPage:
|
||||
"""Página com um aviso de novidade ("Entendi") por cima: cliques em outros elementos falham até fechar."""
|
||||
|
||||
def __init__(self):
|
||||
self.tip_open = True
|
||||
self.clicked = []
|
||||
|
||||
def get_by_role(self, role, name):
|
||||
page = self
|
||||
|
||||
class Tip:
|
||||
first = None
|
||||
|
||||
def count(self):
|
||||
return 1 if page.tip_open and name.search("Entendi") else 0
|
||||
|
||||
def is_visible(self):
|
||||
return self.count() > 0
|
||||
|
||||
def nth(self, i):
|
||||
return self
|
||||
|
||||
def click(self, timeout=None):
|
||||
page.tip_open = False
|
||||
page.clicked.append("Entendi")
|
||||
|
||||
tip = Tip()
|
||||
tip.first = tip
|
||||
return tip
|
||||
|
||||
|
||||
class CoveredField:
|
||||
def __init__(self, page):
|
||||
self.page = page
|
||||
|
||||
def click(self, timeout=None):
|
||||
if self.page.tip_open:
|
||||
raise TimeoutError("Locator.click: Timeout 8000ms exceeded")
|
||||
self.page.clicked.append("campo")
|
||||
|
||||
|
||||
def test_click_through_closes_tip_and_retries():
|
||||
page = TipPage()
|
||||
common.click_through(CoveredField(page), sleep=lambda s: None)
|
||||
assert page.clicked == ["Entendi", "campo"]
|
||||
assert common.dismiss_tips(page, sleep=lambda s: None) == 0 # nada mais aberto
|
||||
no_tip = TipPage()
|
||||
no_tip.tip_open = False
|
||||
|
||||
class Broken:
|
||||
page = no_tip
|
||||
|
||||
def click(self, timeout=None):
|
||||
raise TimeoutError("site mudou")
|
||||
|
||||
with pytest.raises(TimeoutError): # sem aviso para fechar: o erro original aparece
|
||||
common.click_through(Broken(), sleep=lambda s: None)
|
||||
|
||||
|
||||
def test_browser_error_text_explains_common_failures():
|
||||
from app.platforms.session.runner import browser_error_text
|
||||
|
||||
assert "aviso do site" in browser_error_text("Locator.click: Timeout 30000ms exceeded")
|
||||
assert "grande demais" in browser_error_text("Cannot transfer files larger than 50Mb to a browser")
|
||||
assert "fechada" in browser_error_text("Target page, context or browser has been closed")
|
||||
assert "travou" in browser_error_text("algo inesperado")
|
||||
|
||||
|
||||
def test_instagram_links_and_hashtag_suggestions():
|
||||
from app.platforms.session import instagram_web as ig
|
||||
|
||||
# A grade do perfil usa /<conta>/reel/<código>/; o link direto, /reel/<código>/.
|
||||
assert ig.MEDIA.search("https://www.instagram.com/vortplay27/reel/DAbC12_x/").group(1) == "DAbC12_x"
|
||||
assert ig.MEDIA.search("https://www.instagram.com/reel/DAbC12_x/").group(1) == "DAbC12_x"
|
||||
assert ig.MEDIA.search("https://www.instagram.com/vortplay27/") is None
|
||||
|
||||
class Keyboard:
|
||||
def __init__(self):
|
||||
self.typed = []
|
||||
|
||||
def insert_text(self, text):
|
||||
self.typed.append(text)
|
||||
|
||||
class Page:
|
||||
keyboard = Keyboard()
|
||||
|
||||
page = Page()
|
||||
# Legenda terminando em #tag: um espaço fecha a lista de sugestões (que trocou "#teste" por "#testemunho").
|
||||
assert ig.close_suggestions(page, "Ensaio #teste", sleep=lambda s: None) is True and page.keyboard.typed == [" "]
|
||||
assert ig.close_suggestions(page, "Ensaio\n\n🎥 Créditos: https://x", sleep=lambda s: None) is False
|
||||
assert ig.close_suggestions(page, "", sleep=lambda s: None) is False
|
||||
|
||||
|
||||
def test_buttons_of_the_flow_are_searched_inside_the_dialog():
|
||||
"""No feed cada post tem um botão "Compartilhar": o do fluxo precisa estar preso ao diálogo de criação."""
|
||||
from app.platforms.session import instagram_web as ig
|
||||
|
||||
for key in ("share", "next"):
|
||||
assert all(c[0] == "css" and "div[role='dialog']" in c[1] for c in ig.SELECTORS[key])
|
||||
|
||||
|
||||
def test_selectors_are_isolated_per_network():
|
||||
from app.platforms.session import instagram_web, tiktok_studio, youtube_studio
|
||||
|
||||
for module in (youtube_studio, tiktok_studio, instagram_web):
|
||||
assert module.SELECTORS["login"] and module.SELECTORS["file_input"]
|
||||
assert "VALIDADOS COM UMA CONTA REAL" in (module.__doc__ or "")
|
||||
|
||||
|
||||
class StudioDone:
|
||||
"""Botão Publicar do Studio: some (caixa fecha) depois de `closes_after` cliques; `enabled` controla o estado."""
|
||||
|
||||
def __init__(self, closes_after=1, enabled=True):
|
||||
self.clicks, self.closes_after, self.enabled = 0, closes_after, enabled
|
||||
self.page = TipPage()
|
||||
self.page.tip_open = False
|
||||
|
||||
def evaluate(self, script):
|
||||
return self.enabled
|
||||
|
||||
def is_visible(self):
|
||||
return self.clicks < self.closes_after
|
||||
|
||||
def click(self, timeout=None):
|
||||
self.clicks += 1
|
||||
|
||||
|
||||
def test_youtube_confirms_when_upload_box_closes_and_retries_once():
|
||||
from app.platforms.session import youtube_studio as yt
|
||||
|
||||
no_dialog = TipPage()
|
||||
no_dialog.tip_open = False
|
||||
no_dialog.get_by_text = lambda pattern: FakeLocator(False)
|
||||
# Caixa fechou depois do 1º clique: publicado, sem 2º clique.
|
||||
done = StudioDone(closes_after=1)
|
||||
done.click()
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None) is True and done.clicks == 1
|
||||
# O 1º clique sumiu (caixa continua com o botão liberado): clica de novo UMA vez e confirma.
|
||||
done = StudioDone(closes_after=2)
|
||||
done.click()
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None) is True and done.clicks == 2
|
||||
# Nunca fecha: no máximo um clique extra, e devolve False (o painel oferece "Já saiu: informar o link").
|
||||
done = StudioDone(closes_after=99)
|
||||
done.click()
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None, checks=20) is False and done.clicks == 2
|
||||
# Botão desativado (vídeo ainda subindo): não clica.
|
||||
done = StudioDone(closes_after=99, enabled=False)
|
||||
assert yt.wait_enabled(done, sleep=lambda s: None, checks=3) is False
|
||||
assert yt.confirm_published(no_dialog, done, sleep=lambda s: None, checks=20) is False and done.clicks == 0
|
||||
# A caixa "Short publicado" confirma mesmo com o botão ainda na tela.
|
||||
shown = TipPage()
|
||||
shown.tip_open = False
|
||||
shown.get_by_text = lambda pattern: FakeLocator(bool(pattern.search("Short publicado")))
|
||||
assert yt.confirm_published(shown, StudioDone(closes_after=99), sleep=lambda s: None) is True
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Correções das revisões: idempotência por clientRef, pastas permitidas, janela/porta CDP do modo sessão,
|
||||
capturas de tela, permissões (icacls) e PKCE fora do disco."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import acl
|
||||
from app.db import Database
|
||||
from app.paths import IMAGE_EXT, VIDEO_EXT, PathRefused, inside_root
|
||||
from app.platforms.base import JobSpec, PublishError, PublishResult
|
||||
from app.platforms.session import common, runner as runner_mod
|
||||
from app.platforms.session.browser import BrowserInfo, BrowserManager, _Window, owns_port
|
||||
|
||||
PID = "canal--youtube"
|
||||
|
||||
|
||||
# ---------- 1. idempotência
|
||||
|
||||
def test_client_ref_returns_existing_job(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
video = env.video()
|
||||
first = env.client.post("/v1/jobs", json=env.job_body(PID, video, clientRef="painel-42"))
|
||||
assert first.status_code == 201
|
||||
# Mesmo clientRef: 200 com o MESMO job, sem revalidar (o arquivo pode até ter sumido e o perfil caído).
|
||||
video.unlink()
|
||||
env.publisher._update(PID, status="needs_login")
|
||||
again = env.client.post("/v1/jobs", json=env.job_body(PID, video, clientRef="painel-42", title="outro"))
|
||||
assert again.status_code == 200 and again.json()["jobId"] == first.json()["jobId"]
|
||||
assert env.db.get("SELECT COUNT(*) AS n FROM jobs")["n"] == 1
|
||||
# Sem clientRef: comportamento antigo (valida e cria)
|
||||
env.publisher._update(PID, status="connected")
|
||||
other = env.client.post("/v1/jobs", json=env.job_body(PID, env.video()))
|
||||
assert other.status_code == 201 and other.json()["jobId"] != first.json()["jobId"]
|
||||
assert env.client.post("/v1/jobs", json=env.job_body(PID, env.video(), clientRef="x" * 81)).status_code == 422
|
||||
|
||||
|
||||
def test_client_ref_column_is_unique(env):
|
||||
env.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at, client_ref) "
|
||||
"VALUES ('a', 'p', 'youtube', '{}', 'queued', 'x', 'x', 'r1')")
|
||||
with pytest.raises(Exception):
|
||||
env.db.run("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at, client_ref) "
|
||||
"VALUES ('b', 'p', 'youtube', '{}', 'queued', 'x', 'x', 'r1')")
|
||||
assert env.db.get("PRAGMA user_version")["user_version"] == 2
|
||||
|
||||
|
||||
def test_migration_from_v1_keeps_jobs(tmp_path):
|
||||
import sqlite3
|
||||
|
||||
from app.db import SCHEMA, _split
|
||||
|
||||
path = tmp_path / "old.db"
|
||||
conn = sqlite3.connect(path)
|
||||
for statement in _split(SCHEMA[0]):
|
||||
conn.execute(statement)
|
||||
conn.execute("PRAGMA user_version = 1")
|
||||
conn.execute("INSERT INTO jobs (job_id, profile_id, platform, input_json, status, created_at, updated_at) "
|
||||
"VALUES ('j', 'p', 'youtube', '{}', 'done', 'x', 'x')")
|
||||
conn.execute("INSERT INTO oauth_states VALUES ('s', 'youtube', 'p', 'verificador-em-claro', 0, 9e12, 0)")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
db = Database(path)
|
||||
try:
|
||||
assert db.get("SELECT client_ref FROM jobs WHERE job_id = 'j'") == {"client_ref": None}
|
||||
assert db.get("SELECT verifier FROM oauth_states")["verifier"] == ""
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------- 4. só pastas de saída
|
||||
|
||||
def _file(root: Path, *parts: str) -> Path:
|
||||
path = root.joinpath(*parts)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"x")
|
||||
return path
|
||||
|
||||
|
||||
def test_paths_only_output_folders(tmp_path):
|
||||
root = tmp_path / "repo"
|
||||
for folder in ("output/clipper", "output/documentary", "stories/minha", "assets/library"):
|
||||
assert inside_root(str(_file(root, folder, "v.mp4")), root, VIDEO_EXT, "vídeo").is_file()
|
||||
assert inside_root(str(_file(root, "assets", "capa.png")), root, IMAGE_EXT, "capa")
|
||||
for bad in (("data", "publisher", "v.mp4"), ("data", "clipper", "v.mp4"), ("panel", "v.mp4"), ("v.mp4",),
|
||||
("outputx", "v.mp4")):
|
||||
with pytest.raises(PathRefused):
|
||||
inside_root(str(_file(root, *bad)), root, VIDEO_EXT, "vídeo")
|
||||
with pytest.raises(PathRefused, match="data/"):
|
||||
inside_root(str(_file(root, "data", "publisher", "vault.png")), root, IMAGE_EXT, "capa")
|
||||
# ".." não escapa para data/
|
||||
sneaky = os.path.join(str(root), "output", "..", "data", "publisher", "v.mp4")
|
||||
with pytest.raises(PathRefused):
|
||||
inside_root(sneaky, root, VIDEO_EXT, "vídeo")
|
||||
|
||||
|
||||
def test_job_route_refuses_data_folder(env):
|
||||
env.connect_profile(PID, mode="session")
|
||||
inside_data = _file(env.root, "data", "publisher", "x.mp4")
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, inside_data))
|
||||
assert response.status_code == 400 and "data/" in response.json()["detail"]
|
||||
|
||||
|
||||
# ---------- 6. PKCE fora do disco
|
||||
|
||||
def test_restart_mid_oauth_asks_to_connect_again(env):
|
||||
env.client.put("/v1/apps/youtube", json={"clientId": "id", "clientSecret": "s"})
|
||||
body = env.client.post(f"/v1/profiles/{PID}/connect", json={"platform": "youtube", "mode": "official"}).json()
|
||||
state = body["next"]["url"].split("state=")[1].split("&")[0]
|
||||
env.publisher._verifiers.clear() # "reiniciou"
|
||||
from fastapi.testclient import TestClient
|
||||
page = TestClient(env.app).get(f"/oauth/callback/youtube?state={state}&code=c")
|
||||
assert page.status_code == 400 and "reiniciado" in page.text
|
||||
|
||||
|
||||
# ---------- 5. capturas de tela
|
||||
|
||||
class ShotPage:
|
||||
def __init__(self, url="https://studio.youtube.com/x"):
|
||||
self.url = url
|
||||
self.calls = []
|
||||
|
||||
def screenshot(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
Path(kwargs["path"]).write_bytes(b"png")
|
||||
|
||||
# o detect_block olha a página; aqui nada bloqueia
|
||||
def get_by_role(self, *a, **k):
|
||||
return _Absent()
|
||||
|
||||
get_by_text = get_by_label = get_by_placeholder = locator = get_by_role
|
||||
|
||||
|
||||
class _Absent:
|
||||
first = property(lambda self: self)
|
||||
|
||||
def count(self):
|
||||
return 0
|
||||
|
||||
|
||||
def test_screenshot_is_viewport_only_and_skips_login(tmp_path):
|
||||
page = ShotPage()
|
||||
shot = common.screenshot(page, tmp_path, "falha")
|
||||
assert shot and shot.is_file() and page.calls[0]["full_page"] is False
|
||||
login = ShotPage("https://accounts.google.com/v3/signin/identifier")
|
||||
assert common.screenshot(login, tmp_path, "login") is None and login.calls == []
|
||||
|
||||
|
||||
def test_prune_old_screenshots(tmp_path):
|
||||
old, new = tmp_path / "velha.png", tmp_path / "nova.png"
|
||||
old.write_bytes(b"x")
|
||||
new.write_bytes(b"x")
|
||||
eight_days = time.time() - 8 * 86400
|
||||
os.utime(old, (eight_days, eight_days))
|
||||
assert common.prune_screenshots(tmp_path) == 1
|
||||
assert not old.exists() and new.exists()
|
||||
assert common.prune_screenshots(tmp_path / "nao-existe") == 0
|
||||
|
||||
|
||||
# ---------- 2. janela/porta CDP
|
||||
|
||||
def _devtools(user_dir: Path, port: int, browser_id: str = "abc") -> None:
|
||||
user_dir.mkdir(parents=True, exist_ok=True)
|
||||
(user_dir / "DevToolsActivePort").write_text(f"{port}\n/devtools/browser/{browser_id}\n", encoding="utf-8")
|
||||
|
||||
|
||||
def test_owns_port_checks_profile_file_and_browser_id(tmp_path, monkeypatch):
|
||||
ours = {"Browser": "Chrome/150", "webSocketDebuggerUrl": "ws://127.0.0.1:4541/devtools/browser/abc"}
|
||||
_devtools(tmp_path, 4541)
|
||||
assert owns_port(tmp_path, 4541, ours)
|
||||
assert not owns_port(tmp_path, 4542, ours) # arquivo aponta para outra porta
|
||||
other = {"Browser": "Chrome/150", "webSocketDebuggerUrl": "ws://127.0.0.1:4541/devtools/browser/zzz"}
|
||||
assert not owns_port(tmp_path, 4541, other) # outro navegador na mesma porta
|
||||
assert not owns_port(tmp_path / "vazio", 4541, ours) # perfil sem DevToolsActivePort
|
||||
monkeypatch.setattr("app.platforms.session.browser.cdp_version", lambda port: None)
|
||||
assert not owns_port(tmp_path, 4541) # porta não responde
|
||||
|
||||
|
||||
def test_owns_port_without_devtools_file_uses_window_mark(tmp_path, monkeypatch):
|
||||
"""Chrome 157+ com porta fixa não grava DevToolsActivePort: vale a marca do Publicador + o PID que escuta."""
|
||||
from app.platforms.session import browser as browser_module
|
||||
|
||||
ours = {"Browser": "Chrome/157", "webSocketDebuggerUrl": "ws://127.0.0.1:4540/devtools/browser/abc"}
|
||||
browser_module.write_window_mark(tmp_path, 777, 4540)
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 777 if port == 4540 else None)
|
||||
monkeypatch.setattr(browser_module, "process_exe_name", lambda pid: "chrome.exe")
|
||||
assert owns_port(tmp_path, 4540, ours)
|
||||
assert browser_module.active_port(tmp_path) == 4540
|
||||
assert not owns_port(tmp_path, 4541, ours) # a marca aponta para outra porta
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 999)
|
||||
assert not owns_port(tmp_path, 4540, ours) # outro processo escutando na porta
|
||||
monkeypatch.setattr(browser_module, "listener_pid", lambda port: 777)
|
||||
monkeypatch.setattr(browser_module, "process_exe_name", lambda pid: "python.exe")
|
||||
assert not owns_port(tmp_path, 4540, ours) # PID reaproveitado por outro programa
|
||||
assert not owns_port(tmp_path / "vazio", 4540, ours) # perfil sem marca nem DevToolsActivePort
|
||||
|
||||
|
||||
def test_wait_cdp_explains_when_profile_window_is_already_open(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: False)
|
||||
exited = AliveProcess()
|
||||
exited.exited = True # o Chrome entregou a URL para a janela que já estava aberta e saiu
|
||||
with pytest.raises(PublishError, match="Já existe uma janela"):
|
||||
manager._wait_cdp(4540, tmp_path, exited, timeout_s=2)
|
||||
|
||||
|
||||
class AliveProcess:
|
||||
pid = 1
|
||||
|
||||
def __init__(self):
|
||||
self.exited = False
|
||||
|
||||
def poll(self):
|
||||
return 0 if self.exited else None
|
||||
|
||||
def wait(self, timeout=None):
|
||||
self.exited = True
|
||||
return 0
|
||||
|
||||
|
||||
def test_open_refuses_port_that_is_not_ours(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
manager._windows["canal--youtube"] = _Window(AliveProcess(), 4541, tmp_path / "canal--youtube")
|
||||
monkeypatch.setattr("app.platforms.session.browser.owns_port", lambda user_dir, port, version=None: False)
|
||||
with pytest.raises(PublishError, match="não responde como o nosso navegador"):
|
||||
manager.open("canal--youtube", "https://x")
|
||||
|
||||
|
||||
def test_idle_windows_are_closed(tmp_path, monkeypatch):
|
||||
manager = BrowserManager(tmp_path, BrowserInfo("chrome", "chrome.exe"), start_reaper=False)
|
||||
closed = []
|
||||
monkeypatch.setattr(manager, "close", lambda pid, graceful=True: closed.append(pid) or manager._windows.pop(pid))
|
||||
now = time.time()
|
||||
manager._windows["a--youtube"] = _Window(AliveProcess(), 4540, tmp_path / "a", 300, now - 301)
|
||||
manager._windows["b--youtube"] = _Window(AliveProcess(), 4541, tmp_path / "b", 900, now - 301) # login: 15 min
|
||||
manager._windows["c--youtube"] = _Window(AliveProcess(), 4542, tmp_path / "c", 300, now - 999)
|
||||
with manager.in_use("c--youtube"):
|
||||
assert manager.close_idle(now) == ["a--youtube"] # c está ocupado; b ainda no prazo do login
|
||||
assert closed == ["a--youtube"]
|
||||
|
||||
|
||||
class FakeBrowsers:
|
||||
def __init__(self):
|
||||
self.closed, self.opened = [], []
|
||||
|
||||
def open(self, profile_id, url, for_login=False):
|
||||
self.opened.append((profile_id, for_login))
|
||||
return 4541
|
||||
|
||||
def is_open(self, profile_id):
|
||||
return False
|
||||
|
||||
def close(self, profile_id, graceful=True):
|
||||
self.closed.append(profile_id)
|
||||
|
||||
def in_use(self, profile_id):
|
||||
from contextlib import nullcontext
|
||||
return nullcontext()
|
||||
|
||||
|
||||
def _runner(tmp_path, monkeypatch, outcome):
|
||||
browsers = FakeBrowsers()
|
||||
runner = runner_mod.SessionRunner(browsers, tmp_path, sleep=lambda s: None) # type: ignore[arg-type]
|
||||
|
||||
def fake_with_page(port, fn, keep_page, label):
|
||||
fn(object())
|
||||
|
||||
monkeypatch.setattr(runner, "_with_page", fake_with_page)
|
||||
fake = runner_mod.Uploader(PID.split("--")[1], "https://x", lambda page, sleep: outcome.get("reason"),
|
||||
lambda page, spec, progress, sleep: outcome["upload"]())
|
||||
monkeypatch.setitem(runner_mod.UPLOADERS, "youtube", fake)
|
||||
return runner, browsers
|
||||
|
||||
|
||||
def test_window_closes_after_successful_check_but_not_when_login_missing(tmp_path, monkeypatch):
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"reason": None})
|
||||
assert runner.check(PID, "youtube") is None and browsers.closed == [PID]
|
||||
assert browsers.opened == [(PID, True)]
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"reason": "tela de login"})
|
||||
assert runner.check(PID, "youtube") == "tela de login" and browsers.closed == []
|
||||
|
||||
|
||||
def test_window_closes_after_each_publish(tmp_path, monkeypatch):
|
||||
spec = JobSpec("j", PID, "youtube", Path("v.mp4"), None, "t", "c")
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": lambda: PublishResult("1", None)})
|
||||
assert runner.publish(spec, lambda s, p: None).remote_id == "1" and browsers.closed == [PID]
|
||||
|
||||
def fail():
|
||||
raise PublishError("Não achei o botão.")
|
||||
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": fail})
|
||||
with pytest.raises(PublishError):
|
||||
runner.publish(spec, lambda s, p: None)
|
||||
assert browsers.closed == [PID]
|
||||
|
||||
def login():
|
||||
raise PublishError("entre de novo", "needs_login")
|
||||
|
||||
runner, browsers = _runner(tmp_path, monkeypatch, {"upload": login})
|
||||
with pytest.raises(PublishError):
|
||||
runner.publish(spec, lambda s, p: None)
|
||||
assert browsers.closed == [] # fica aberta para o usuário entrar (o fechamento por ociosidade cuida depois)
|
||||
|
||||
|
||||
# ---------- 3. permissões
|
||||
|
||||
def test_icacls_args():
|
||||
assert acl.icacls_args(Path("C:/x"), "S-1-5-21-1", True) == [
|
||||
"icacls", str(Path("C:/x")), "/inheritance:r", "/grant:r", "*S-1-5-21-1:(OI)(CI)F"]
|
||||
assert acl.icacls_args(Path("C:/x/.env"), "S-1-5-21-1", False)[-1] == "*S-1-5-21-1:F"
|
||||
|
||||
|
||||
def test_restrict_uses_current_user(tmp_path, monkeypatch):
|
||||
calls = []
|
||||
|
||||
class Done:
|
||||
returncode = 0
|
||||
stdout = stderr = ""
|
||||
|
||||
monkeypatch.setattr(acl, "current_user_sid", lambda: "S-1-5-21-9")
|
||||
assert acl.restrict_to_current_user(tmp_path, run=lambda args, **kw: calls.append(args) or Done())
|
||||
assert calls == [["icacls", str(tmp_path), "/inheritance:r", "/grant:r", "*S-1-5-21-9:(OI)(CI)F"]]
|
||||
monkeypatch.setattr(acl, "current_user_sid", lambda: None)
|
||||
assert acl.restrict_to_current_user(tmp_path) is False
|
||||
|
||||
|
||||
def test_text_has_no_human_mimicry_wording():
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
for path in list((root / "app").rglob("*.py")) + [root / "README.md"]:
|
||||
assert "ritmo humano" not in path.read_text(encoding="utf-8"), path
|
||||
@@ -0,0 +1,157 @@
|
||||
"""OAuth: state de uso único com validade, PKCE (base64url no Google, HEX no TikTok), troca do code e refresh."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import time
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.platforms.base import challenge_s256_base64url, challenge_s256_hex, make_verifier
|
||||
|
||||
YT = "canal--youtube"
|
||||
TT = "canal--tiktok"
|
||||
|
||||
|
||||
def _configure(env, platform):
|
||||
env.client.put(f"/v1/apps/{platform}", json={"clientId": f"{platform}-id", "clientSecret": f"{platform}-secret"})
|
||||
|
||||
|
||||
def _connect(env, pid, platform):
|
||||
body = env.client.post(f"/v1/profiles/{pid}/connect", json={"platform": platform, "mode": "official"}).json()
|
||||
assert body["next"]["kind"] == "open_url"
|
||||
return parse_qs(urlparse(body["next"]["url"]).query), body
|
||||
|
||||
|
||||
def test_pkce_helpers():
|
||||
verifier = make_verifier()
|
||||
assert 43 <= len(verifier) <= 128
|
||||
digest = hashlib.sha256(verifier.encode()).digest()
|
||||
assert challenge_s256_hex(verifier) == digest.hex()
|
||||
assert len(challenge_s256_hex(verifier)) == 64 and all(c in "0123456789abcdef" for c in challenge_s256_hex(verifier))
|
||||
assert challenge_s256_base64url(verifier) == base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def test_youtube_full_flow(env):
|
||||
_configure(env, "youtube")
|
||||
query, body = _connect(env, YT, "youtube")
|
||||
assert body["profile"]["status"] == "connecting"
|
||||
assert query["redirect_uri"] == ["http://127.0.0.1:4530/oauth/callback/youtube"]
|
||||
assert query["code_challenge_method"] == ["S256"] and query["access_type"] == ["offline"]
|
||||
assert "youtube.upload" in query["scope"][0]
|
||||
state = query["state"][0]
|
||||
assert env.db.get("SELECT verifier FROM oauth_states WHERE state = ?", state)["verifier"] == "" # nunca no disco
|
||||
verifier = env.publisher._verifiers[state]
|
||||
assert query["code_challenge"] == [challenge_s256_base64url(verifier)]
|
||||
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token",
|
||||
{"access_token": "ya29.a", "expires_in": 3599, "refresh_token": "1//r"})
|
||||
env.router.add("GET", "https://www.googleapis.com/youtube/v3/channels",
|
||||
{"items": [{"id": "UC1", "snippet": {"title": "Histórias do Litoral", "customUrl": "@litoral"}}]})
|
||||
browser = TestClient(env.app) # o navegador do usuário não manda a chave do serviço
|
||||
page = browser.get(f"/oauth/callback/youtube?state={state}&code=4/abc")
|
||||
assert page.status_code == 200 and 'lang="pt-BR"' in page.text
|
||||
assert "Pode fechar esta aba e voltar ao painel." in page.text and "@litoral" in page.text
|
||||
|
||||
sent = parse_qs(env.router.find("POST", "https://oauth2.googleapis.com/token")[0].content.decode())
|
||||
assert sent["code_verifier"] == [verifier] and sent["grant_type"] == ["authorization_code"]
|
||||
assert sent["client_secret"] == ["youtube-secret"]
|
||||
profile = env.client.get(f"/v1/profiles/{YT}").json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral"
|
||||
assert profile["displayName"] == "Histórias do Litoral" and profile["expiresAt"] is None
|
||||
assert env.vault.get(f"token:{YT}")["refreshToken"] == "1//r"
|
||||
|
||||
# uso único
|
||||
again = browser.get(f"/oauth/callback/youtube?state={state}&code=4/abc")
|
||||
assert again.status_code == 400 and "já foi usado" in again.text
|
||||
|
||||
|
||||
def test_state_expired_wrong_platform_and_denied(env):
|
||||
_configure(env, "youtube")
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
state = query["state"][0]
|
||||
browser = TestClient(env.app)
|
||||
assert "não é válido" in browser.get(f"/oauth/callback/tiktok?state={state}&code=x").text
|
||||
assert "não é válido" in browser.get("/oauth/callback/youtube?state=inventado&code=x").text
|
||||
env.db.run("UPDATE oauth_states SET expires_at = ? WHERE state = ?", time.time() - 1, state)
|
||||
expired = browser.get(f"/oauth/callback/youtube?state={state}&code=x")
|
||||
assert expired.status_code == 400 and "expirou" in expired.text
|
||||
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
denied = browser.get(f"/oauth/callback/youtube?state={query['state'][0]}&error=access_denied")
|
||||
assert denied.status_code == 400 and "não autorizou" in denied.text
|
||||
assert env.client.get(f"/v1/profiles/{YT}").json()["status"] == "error"
|
||||
|
||||
|
||||
def test_google_invalid_grant_marks_error(env):
|
||||
_configure(env, "youtube")
|
||||
query, _ = _connect(env, YT, "youtube")
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token",
|
||||
lambda r: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
page = TestClient(env.app).get(f"/oauth/callback/youtube?state={query['state'][0]}&code=x")
|
||||
assert page.status_code == 400 and "In production" in page.text
|
||||
|
||||
|
||||
def test_tiktok_hex_challenge_and_callback(env):
|
||||
_configure(env, "tiktok")
|
||||
query, _ = _connect(env, TT, "tiktok")
|
||||
assert query["client_key"] == ["tiktok-id"]
|
||||
assert query["scope"] == ["user.info.basic,video.upload,video.publish"]
|
||||
assert query["redirect_uri"] == ["http://127.0.0.1:4530/oauth/callback/tiktok"]
|
||||
state = query["state"][0]
|
||||
assert env.db.get("SELECT verifier FROM oauth_states WHERE state = ?", state)["verifier"] == "" # nunca no disco
|
||||
verifier = env.publisher._verifiers[state]
|
||||
assert query["code_challenge"] == [hashlib.sha256(verifier.encode()).hexdigest()]
|
||||
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/oauth/token/", {
|
||||
"access_token": "act.1", "expires_in": 7200, "open_id": "o1", "refresh_token": "rft.1",
|
||||
"refresh_expires_in": 15552000, "scope": "user.info.basic,video.upload,video.publish", "token_type": "Bearer"})
|
||||
env.router.add("GET", "https://open.tiktokapis.com/v2/user/info/", {"data": {"user": {"display_name": "Litoral"}}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/",
|
||||
{"data": {"creator_username": "litoral", "creator_nickname": "Litoral"}, "error": {"code": "ok"}})
|
||||
page = TestClient(env.app).get(f"/oauth/callback/tiktok?state={state}&code=c*1!")
|
||||
assert page.status_code == 200, page.text
|
||||
sent = parse_qs(env.router.find("POST", "https://open.tiktokapis.com/v2/oauth/token/")[0].content.decode())
|
||||
assert sent["code_verifier"] == [verifier] and sent["client_key"] == ["tiktok-id"] and sent["code"] == ["c*1!"]
|
||||
profile = env.client.get(f"/v1/profiles/{TT}").json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral" and profile["expiresAt"]
|
||||
|
||||
|
||||
def test_tiktok_refresh_is_rotated_and_saved(env):
|
||||
_configure(env, "tiktok")
|
||||
env.connect_profile(TT, secret={"accessToken": "old", "accessExpiresAt": time.time() - 10,
|
||||
"refreshToken": "rft.old", "refreshExpiresAt": time.time() + 1000})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/oauth/token/", {
|
||||
"access_token": "act.new", "expires_in": 7200, "open_id": "o1", "refresh_token": "rft.new",
|
||||
"refresh_expires_in": 15552000})
|
||||
token = env.publisher._token_provider(TT, "tiktok")(False)
|
||||
assert token == "act.new"
|
||||
sent = parse_qs(env.router.requests[-1].content.decode())
|
||||
assert sent["grant_type"] == ["refresh_token"] and sent["refresh_token"] == ["rft.old"]
|
||||
saved = env.vault.get(f"token:{TT}")
|
||||
assert saved["refreshToken"] == "rft.new" and saved["accessToken"] == "act.new"
|
||||
# access ainda válido: não renova de novo
|
||||
assert env.publisher._token_provider(TT, "tiktok")(False) == "act.new"
|
||||
assert len(env.router.requests) == 1
|
||||
|
||||
|
||||
def test_expired_refresh_marks_profile_expired(env):
|
||||
_configure(env, "tiktok")
|
||||
env.connect_profile(TT, secret={"accessToken": "old", "accessExpiresAt": 0, "refreshToken": "r",
|
||||
"refreshExpiresAt": time.time() - 1}, expires_at="2020-01-01T00:00:00Z")
|
||||
assert env.client.get(f"/v1/profiles/{TT}").json()["status"] == "expired"
|
||||
|
||||
|
||||
def test_youtube_refresh_invalid_grant_is_expired(env):
|
||||
_configure(env, "youtube")
|
||||
env.connect_profile(YT, secret={"accessToken": "a", "accessExpiresAt": 0, "refreshToken": "r"})
|
||||
env.router.add("POST", "https://oauth2.googleapis.com/token", lambda r: httpx.Response(400, json={"error": "invalid_grant"}))
|
||||
video = env.video()
|
||||
env.client.post("/v1/jobs", json=env.job_body(YT, video))
|
||||
env.worker.run_once()
|
||||
job = env.db.get("SELECT * FROM jobs")
|
||||
assert job["status"] == "needs_login" and "Conecte o YouTube de novo" in job["error"]
|
||||
assert env.client.get(f"/v1/profiles/{YT}").json()["status"] == "expired"
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Números dos posts (dashboard): leitura de contagens, YouTube público, linha do TikTok Studio e API do Instagram."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.platforms.session import stats as session_stats
|
||||
from app.platforms.stats import parse_count, youtube_from_html
|
||||
|
||||
|
||||
def test_parse_count_reads_how_networks_show_numbers():
|
||||
assert parse_count("1.499") == 1499 and parse_count("1,499") == 1499 and parse_count("31") == 31
|
||||
assert parse_count("1,2 mil") == 1200 and parse_count("5,2\xa0mil") == 5200 and parse_count("1.2K") == 1200
|
||||
assert parse_count("3,4 mi") == 3_400_000 and parse_count("3.4M") == 3_400_000 and parse_count("0") == 0
|
||||
assert parse_count("Todos") is None and parse_count("") is None and parse_count("17 de nov, 15:50") is None
|
||||
|
||||
|
||||
def test_youtube_public_page():
|
||||
html = '..."videoDetails":{"viewCount":"1234"}..."likeCount":"56"..."contextualInfo":{"runs":[{"text":"7"}]}'
|
||||
stats = youtube_from_html("abc123", html)
|
||||
assert (stats.views, stats.likes, stats.comments) == (1234, 56, 7)
|
||||
assert youtube_from_html("abc123", "<html>consent</html>") is None
|
||||
|
||||
|
||||
def test_tiktok_studio_row():
|
||||
# Texto real de uma linha do Studio (17/11/2026).
|
||||
text = ("00:26\nA conversa sobre descanso vira... #skipnho 🎥 Créditos: https://twitch.tv/skipnho\n17 de nov, 15:50\n"
|
||||
"Todos\n2\n1\n0")
|
||||
stats = session_stats.tiktok_row_stats("https://www.tiktok.com/@vortplay/video/7709214727859146005", text)
|
||||
assert (stats.remote_id, stats.views, stats.likes, stats.comments) == ("7709214727859146005", 2, 1, 0)
|
||||
assert session_stats.tiktok_row_stats("https://www.tiktok.com/@vortplay/video/1", "Processando\nTodos") is None
|
||||
|
||||
|
||||
def test_instagram_graphql_media():
|
||||
payload = {"data": {"edges": [{"node": {"media": {"code": "Df2gT_ztuds", "play_count": 1499, "view_count": None,
|
||||
"like_count": 25, "comment_count": 1}}},
|
||||
{"node": {"media": {"code": "Df2m7MGNR0T", "play_count": 31, "like_count": 2,
|
||||
"comment_count": 0}}},
|
||||
{"node": {"code": "semNumero"}}]}}
|
||||
found = {}
|
||||
session_stats.instagram_media(payload, found)
|
||||
assert set(found) == {"Df2gT_ztuds", "Df2m7MGNR0T"}
|
||||
assert (found["Df2gT_ztuds"].views, found["Df2gT_ztuds"].likes, found["Df2gT_ztuds"].comments) == (1499, 25, 1)
|
||||
@@ -0,0 +1,271 @@
|
||||
"""Montagem das requisições de envio de cada API (rede simulada com httpx.MockTransport)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.platforms import tiktok_api, youtube_api
|
||||
from app.platforms.base import PublishError
|
||||
from app.platforms.instagram_api import InstagramApi
|
||||
from app.platforms.tiktok_api import UNAUDITED, chunk_plan
|
||||
|
||||
YT, TT, IG = "canal--youtube", "canal--tiktok", "canal--instagram"
|
||||
VALID = {"accessToken": "tok", "accessExpiresAt": time.time() + 3600, "refreshToken": "r",
|
||||
"refreshExpiresAt": time.time() + 10_000_000}
|
||||
|
||||
|
||||
def _run(env, pid, **extra):
|
||||
video = env.video(size=1000)
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(pid, video, **extra))
|
||||
assert response.status_code == 201, response.text
|
||||
assert env.worker.run_once()
|
||||
return env.client.get(f"/v1/jobs/{response.json()['jobId']}").json()
|
||||
|
||||
|
||||
# ---------- YouTube
|
||||
|
||||
def _youtube(env):
|
||||
env.client.put("/v1/apps/youtube", json={"clientId": "id", "clientSecret": "sec"})
|
||||
env.connect_profile(YT, secret=dict(VALID))
|
||||
|
||||
|
||||
def test_youtube_resumable_upload_in_chunks(env, monkeypatch):
|
||||
_youtube(env)
|
||||
monkeypatch.setattr(youtube_api, "CHUNK", 400)
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos",
|
||||
lambda r: httpx.Response(200, headers={"Location": "https://upload.example/session/1"}))
|
||||
ranges = iter(["bytes=0-399", "bytes=0-799"])
|
||||
|
||||
def put(request):
|
||||
if request.headers["content-range"].endswith("999/1000"):
|
||||
return httpx.Response(201, json={"id": "VID123"})
|
||||
return httpx.Response(308, headers={"Range": next(ranges)})
|
||||
|
||||
env.router.add("PUT", "https://upload.example/session/1", put)
|
||||
job = _run(env, YT, aiGenerated=True, tags=["#cortes", "live, top"], title="Título <legal>")
|
||||
assert job["status"] == "done", job
|
||||
assert job["remoteId"] == "VID123" and job["url"] == "https://youtu.be/VID123" and job["progress"] == 1
|
||||
|
||||
start = env.router.find("POST", "https://www.googleapis.com/upload/youtube/v3/videos")[0]
|
||||
assert parse_qs(start.url.query.decode()) == {"uploadType": ["resumable"], "part": ["snippet,status"]}
|
||||
assert start.headers["authorization"] == "Bearer tok"
|
||||
assert start.headers["x-upload-content-length"] == "1000"
|
||||
body = json.loads(start.content)
|
||||
assert body["status"] == {"privacyStatus": "public", "selfDeclaredMadeForKids": False, "containsSyntheticMedia": True}
|
||||
assert body["snippet"]["title"] == "Título ‹legal›" and body["snippet"]["tags"] == ["cortes", "live top"]
|
||||
puts = env.router.find("PUT", "https://upload.example/session/1")
|
||||
assert [p.headers["content-range"] for p in puts] == ["bytes 0-399/1000", "bytes 400-799/1000", "bytes 800-999/1000"]
|
||||
assert sum(len(p.content) for p in puts) == 1000
|
||||
|
||||
|
||||
def test_youtube_schedule_forces_private(env):
|
||||
spec_body = youtube_api.YouTubeApi(None, "i", "s", "r").video_body # type: ignore[arg-type]
|
||||
from app.platforms.base import JobSpec
|
||||
from pathlib import Path
|
||||
spec = JobSpec("j", YT, "youtube", Path("x.mp4"), None, "t", "c", privacy="public",
|
||||
publish_at="2026-12-01T15:00:00Z", made_for_kids=True)
|
||||
status = spec_body(spec)["status"]
|
||||
assert status["privacyStatus"] == "private" and status["publishAt"] == "2026-12-01T15:00:00Z"
|
||||
assert status["selfDeclaredMadeForKids"] is True
|
||||
|
||||
|
||||
def test_youtube_quota_error_is_human(env):
|
||||
_youtube(env)
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos", lambda r: httpx.Response(
|
||||
403, json={"error": {"errors": [{"reason": "quotaExceeded"}], "message": "quota"}}))
|
||||
job = _run(env, YT)
|
||||
assert job["status"] == "failed" and "cota diária" in job["error"]
|
||||
|
||||
|
||||
def test_youtube_cover_after_processing(env):
|
||||
_youtube(env)
|
||||
cover = env.root / "output" / "capa.jpg"
|
||||
cover.parent.mkdir(parents=True, exist_ok=True)
|
||||
cover.write_bytes(b"\xff\xd8jpg")
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/videos",
|
||||
lambda r: httpx.Response(200, headers={"Location": "https://upload.example/s"}))
|
||||
env.router.add("PUT", "https://upload.example/s", lambda r: httpx.Response(200, json={"id": "V1"}))
|
||||
states = iter(["processing", "succeeded"])
|
||||
env.router.add("GET", "https://www.googleapis.com/youtube/v3/videos",
|
||||
lambda r: httpx.Response(200, json={"items": [{"processingDetails": {"processingStatus": next(states)}}]}))
|
||||
env.router.add("POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set", {"items": []})
|
||||
job = _run(env, YT, cover=str(cover))
|
||||
assert job["status"] == "done" and "capa não foi aplicada" not in job["step"]
|
||||
thumb = env.router.find("POST", "https://www.googleapis.com/upload/youtube/v3/thumbnails/set")[0]
|
||||
assert thumb.headers["content-type"] == "image/jpeg" and thumb.content == b"\xff\xd8jpg"
|
||||
assert env.sleeps == [15] # esperou o processamento uma vez
|
||||
|
||||
|
||||
# ---------- TikTok
|
||||
|
||||
def _tiktok(env, options=("PUBLIC_TO_EVERYONE", "SELF_ONLY")):
|
||||
env.client.put("/v1/apps/tiktok", json={"clientId": "ck", "clientSecret": "cs"})
|
||||
env.connect_profile(TT, secret=dict(VALID))
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/", {
|
||||
"data": {"creator_username": "litoral", "creator_nickname": "Litoral", "privacy_level_options": list(options),
|
||||
"comment_disabled": False, "duet_disabled": False, "stitch_disabled": True,
|
||||
"max_video_post_duration_sec": 600}, "error": {"code": "ok"}})
|
||||
env.router.add("PUT", "https://upload.tiktok.example/", lambda r: httpx.Response(201))
|
||||
|
||||
|
||||
def test_chunk_plan_rules():
|
||||
mb = 1024 * 1024
|
||||
assert chunk_plan(3 * mb) == (3 * mb, 1)
|
||||
assert chunk_plan(64 * mb) == (64 * mb, 1)
|
||||
size, count = chunk_plan(100 * mb)
|
||||
assert (size, count) == (32 * mb, 3) and 100 * mb - size * (count - 1) <= 128 * mb
|
||||
|
||||
|
||||
def test_tiktok_direct_post(env):
|
||||
_tiktok(env)
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", {
|
||||
"data": {"publish_id": "p1", "upload_url": "https://upload.tiktok.example/u"}, "error": {"code": "ok"}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", {
|
||||
"data": {"status": "PUBLISH_COMPLETE", "publicaly_available_post_id": [7311]}, "error": {"code": "ok"}})
|
||||
job = _run(env, TT, aiGenerated=True, caption="Olha isso #fy")
|
||||
assert job["status"] == "done", job
|
||||
assert job["url"] == "https://www.tiktok.com/@litoral/video/7311" and job["draft"] is False
|
||||
|
||||
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/")[0].content)
|
||||
assert init["source_info"] == {"source": "FILE_UPLOAD", "video_size": 1000, "chunk_size": 1000, "total_chunk_count": 1}
|
||||
assert init["post_info"]["privacy_level"] == "PUBLIC_TO_EVERYONE" and init["post_info"]["is_aigc"] is True
|
||||
assert init["post_info"]["title"] == "Olha isso #fy"
|
||||
put = env.router.find("PUT", "https://upload.tiktok.example/")[0]
|
||||
assert put.headers["content-range"] == "bytes 0-999/1000" and put.headers["content-type"] == "video/mp4"
|
||||
status = env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/")[0]
|
||||
assert json.loads(status.content) == {"publish_id": "p1"} and status.headers["authorization"] == "Bearer tok"
|
||||
|
||||
|
||||
def test_tiktok_multi_chunk_put(env, monkeypatch):
|
||||
_tiktok(env)
|
||||
monkeypatch.setattr(tiktok_api.TikTokApi, "single_max", 300)
|
||||
monkeypatch.setattr(tiktok_api.TikTokApi, "chunk", 300)
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/", {
|
||||
"data": {"publish_id": "p2", "upload_url": "https://upload.tiktok.example/u2"}, "error": {"code": "ok"}})
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", {
|
||||
"data": {"status": "SEND_TO_USER_INBOX"}, "error": {"code": "ok"}})
|
||||
job = _run(env, TT, tiktokMode="draft")
|
||||
assert job["status"] == "done" and job["draft"] is True and job["url"] is None
|
||||
assert "caixa de entrada" in job["step"]
|
||||
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/")[0].content)
|
||||
assert init == {"source_info": {"source": "FILE_UPLOAD", "video_size": 1000, "chunk_size": 300, "total_chunk_count": 3}}
|
||||
ranges = [p.headers["content-range"] for p in env.router.find("PUT", "https://upload.tiktok.example/")]
|
||||
assert ranges == ["bytes 0-299/1000", "bytes 300-599/1000", "bytes 600-999/1000"] # último leva o resto
|
||||
assert not env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/creator_info/query/")
|
||||
|
||||
|
||||
def test_tiktok_unaudited_message(env):
|
||||
_tiktok(env, options=["SELF_ONLY"])
|
||||
job = _run(env, TT, privacy="public")
|
||||
assert job["status"] == "failed" and job["error"] == UNAUDITED
|
||||
assert "Somente eu" in UNAUDITED and "Rascunho" in UNAUDITED
|
||||
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", lambda r: httpx.Response(
|
||||
403, json={"error": {"code": "unaudited_client_can_only_post_to_private_accounts", "message": "x"}}))
|
||||
_tiktok(env)
|
||||
job = _run(env, TT, privacy="public")
|
||||
assert job["status"] == "failed" and job["error"].startswith(UNAUDITED)
|
||||
|
||||
|
||||
def test_tiktok_private_without_public_link(env):
|
||||
_tiktok(env)
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/", {
|
||||
"data": {"publish_id": "p3", "upload_url": "https://upload.tiktok.example/u3"}, "error": {"code": "ok"}})
|
||||
statuses = iter(["PROCESSING_UPLOAD", "PUBLISH_COMPLETE"])
|
||||
env.router.add("POST", "https://open.tiktokapis.com/v2/post/publish/status/fetch/", lambda r: httpx.Response(
|
||||
200, json={"data": {"status": next(statuses)}, "error": {"code": "ok"}}))
|
||||
job = _run(env, TT, privacy="private")
|
||||
assert job["status"] == "done" and "Somente eu" in job["step"] and job["url"] is None
|
||||
init = json.loads(env.router.find("POST", "https://open.tiktokapis.com/v2/post/publish/video/init/")[0].content)
|
||||
assert init["post_info"]["privacy_level"] == "SELF_ONLY"
|
||||
|
||||
|
||||
def test_tiktok_creator_info_route(env):
|
||||
_tiktok(env)
|
||||
info = env.client.get(f"/v1/profiles/{TT}/tiktok/creator-info").json()
|
||||
assert info == {"nickname": "Litoral", "privacyOptions": ["PUBLIC_TO_EVERYONE", "SELF_ONLY"], "maxDurationS": 600,
|
||||
"commentDisabled": False, "duetDisabled": False, "stitchDisabled": True}
|
||||
assert env.client.get(f"/v1/profiles/{YT}/tiktok/creator-info").status_code == 409
|
||||
|
||||
|
||||
# ---------- Instagram
|
||||
|
||||
GRAPH = "https://graph.instagram.com/v24.0"
|
||||
|
||||
|
||||
def test_instagram_paste_token(env):
|
||||
env.router.add("GET", f"{GRAPH}/me", {"user_id": "1784", "username": "litoral", "name": "Litoral",
|
||||
"account_type": "MEDIA_CREATOR"})
|
||||
profile = env.client.post(f"/v1/profiles/{IG}/token", json={"accessToken": "IGAA" + "x" * 40}).json()
|
||||
assert profile["status"] == "connected" and profile["handle"] == "@litoral" and profile["expiresAt"]
|
||||
assert env.vault.get(f"token:{IG}")["igUserId"] == "1784"
|
||||
|
||||
env.router.add("GET", f"{GRAPH}/me", {"user_id": "1", "username": "pessoal", "account_type": "PERSONAL"})
|
||||
refused = env.client.post(f"/v1/profiles/{IG}/token", json={"accessToken": "IGAA" + "y" * 40})
|
||||
assert refused.status_code == 400 and "Profissional" in refused.json()["detail"]
|
||||
|
||||
|
||||
def test_instagram_reel_upload(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time()})
|
||||
env.router.add("POST", f"{GRAPH}/1784/media", {"id": "C1", "uri": "https://rupload.facebook.com/ig-api-upload/v24.0/C1"})
|
||||
env.router.add("POST", "https://rupload.facebook.com/ig-api-upload/v24.0/C1", {"success": True})
|
||||
statuses = iter(["IN_PROGRESS", "FINISHED"])
|
||||
env.router.add("GET", f"{GRAPH}/C1", lambda r: httpx.Response(200, json={"status_code": next(statuses)}))
|
||||
env.router.add("POST", f"{GRAPH}/1784/media_publish", {"id": "M9"})
|
||||
env.router.add("GET", f"{GRAPH}/M9", {"permalink": "https://www.instagram.com/reel/abc/"})
|
||||
job = _run(env, IG, aiGenerated=True, caption="Legenda #reels")
|
||||
assert job["status"] == "done", job
|
||||
assert job["remoteId"] == "M9" and job["url"] == "https://www.instagram.com/reel/abc/"
|
||||
|
||||
form = parse_qs(env.router.find("POST", f"{GRAPH}/1784/media")[0].content.decode())
|
||||
assert form["media_type"] == ["REELS"] and form["upload_type"] == ["resumable"]
|
||||
assert form["caption"] == ["Legenda #reels"] and form["is_ai_generated"] == ["true"]
|
||||
upload = env.router.find("POST", "https://rupload.facebook.com/")[0]
|
||||
assert upload.headers["authorization"] == "OAuth igtok" and upload.headers["offset"] == "0"
|
||||
assert upload.headers["file_size"] == "1000" and len(upload.content) == 1000
|
||||
publish = parse_qs(env.router.find("POST", f"{GRAPH}/1784/media_publish")[0].content.decode())
|
||||
assert publish["creation_id"] == ["C1"]
|
||||
assert env.sleeps == [InstagramApi.poll_s]
|
||||
|
||||
|
||||
def test_instagram_rupload_refused_explains_fb_login(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time()})
|
||||
env.router.add("POST", f"{GRAPH}/1784/media", {"id": "C1"})
|
||||
env.router.add("POST", "https://rupload.facebook.com/", lambda r: httpx.Response(
|
||||
400, json={"error": {"code": 1, "message": "unsupported"}}))
|
||||
job = _run(env, IG)
|
||||
assert job["status"] == "failed" and "Facebook Login for Business" in job["error"]
|
||||
|
||||
|
||||
def test_instagram_refreshes_token_close_to_expiry(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "old", "accessExpiresAt": time.time() + 5 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time() - 50 * 86400})
|
||||
env.router.add("GET", "https://graph.instagram.com/refresh_access_token",
|
||||
{"access_token": "new", "token_type": "bearer", "expires_in": 5184000})
|
||||
env.publisher.maintenance()
|
||||
assert env.vault.get(f"token:{IG}")["accessToken"] == "new"
|
||||
sent = env.router.find("GET", "https://graph.instagram.com/refresh_access_token")[0]
|
||||
assert sent.url.params["grant_type"] == "ig_refresh_token" and sent.url.params["access_token"] == "old"
|
||||
|
||||
|
||||
def test_instagram_expired_token_code_190(env):
|
||||
env.connect_profile(IG, secret={"accessToken": "igtok", "accessExpiresAt": time.time() + 50 * 86400,
|
||||
"igUserId": "1784", "obtainedAt": time.time()})
|
||||
env.router.add("POST", f"{GRAPH}/1784/media", lambda r: httpx.Response(
|
||||
400, json={"error": {"code": 190, "message": "Error validating access token"}}))
|
||||
job = _run(env, IG)
|
||||
assert job["status"] == "needs_login"
|
||||
assert env.client.get(f"/v1/profiles/{IG}").json()["status"] == "expired"
|
||||
|
||||
|
||||
def test_publish_error_kinds():
|
||||
assert PublishError("x").kind == "failed"
|
||||
with pytest.raises(PublishError):
|
||||
raise PublishError("y", "needs_login")
|
||||
@@ -0,0 +1,38 @@
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from app.vault import DpapiCipher, Vault, VaultError
|
||||
from tests.conftest import FakeCipher
|
||||
|
||||
|
||||
def test_vault_roundtrip_with_fake_cipher(tmp_path):
|
||||
vault = Vault(tmp_path / "vault.bin", cipher=FakeCipher())
|
||||
assert vault.get("token:x") is None
|
||||
vault.set("token:x", {"accessToken": "segredo-123", "refreshToken": "r1"})
|
||||
vault.update("token:x", refreshToken="r2")
|
||||
assert vault.get("token:x") == {"accessToken": "segredo-123", "refreshToken": "r2"}
|
||||
assert b"segredo-123" not in (tmp_path / "vault.bin").read_bytes()
|
||||
reopened = Vault(tmp_path / "vault.bin", cipher=FakeCipher())
|
||||
assert reopened.get("token:x")["refreshToken"] == "r2"
|
||||
reopened.delete("token:x")
|
||||
assert reopened.keys() == []
|
||||
|
||||
|
||||
def test_vault_refuses_garbage(tmp_path):
|
||||
(tmp_path / "vault.bin").write_bytes(b"FAKE{nao-e-json")
|
||||
with pytest.raises(VaultError):
|
||||
Vault(tmp_path / "vault.bin", cipher=FakeCipher()).get("x")
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "win32", reason="DPAPI só existe no Windows")
|
||||
def test_real_dpapi_roundtrip(tmp_path):
|
||||
cipher = DpapiCipher()
|
||||
blob = cipher.protect(b"token-de-verdade")
|
||||
assert b"token-de-verdade" not in blob
|
||||
assert cipher.unprotect(blob) == b"token-de-verdade"
|
||||
vault = Vault(tmp_path / "vault.bin") # cifrador real (padrão)
|
||||
vault.set("app:youtube", {"clientSecret": "abc"})
|
||||
assert Vault(tmp_path / "vault.bin").get("app:youtube") == {"clientSecret": "abc"}
|
||||
with pytest.raises(VaultError):
|
||||
cipher.unprotect(b"\x01\x02\x03 nao e dpapi")
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Máquina de estados do job e worker persistente."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.db import INTERRUPTED, Database
|
||||
from app.platforms.base import PublishError, PublishResult
|
||||
from app.worker import Worker
|
||||
|
||||
PID = "canal--instagram"
|
||||
|
||||
|
||||
def _queue(env, **extra):
|
||||
env.connect_profile(PID, mode="session")
|
||||
response = env.client.post("/v1/jobs", json=env.job_body(PID, env.video(), **extra))
|
||||
assert response.status_code == 201
|
||||
return response.json()["jobId"]
|
||||
|
||||
|
||||
def _job(env, job_id):
|
||||
return env.client.get(f"/v1/jobs/{job_id}").json()
|
||||
|
||||
|
||||
def test_queued_running_done(env):
|
||||
job_id = _queue(env)
|
||||
seen = []
|
||||
|
||||
def execute(row, progress):
|
||||
seen.append(_job(env, job_id)["status"])
|
||||
progress("Enviando…", 0.5)
|
||||
return PublishResult("R1", "https://exemplo/R1", False, "Publicado")
|
||||
|
||||
worker = Worker(env.db, execute)
|
||||
assert worker.run_once() is True
|
||||
assert seen == ["running"]
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "done" and job["progress"] == 1 and job["remoteId"] == "R1" and job["step"] == "Publicado"
|
||||
assert worker.run_once() is False # fila vazia
|
||||
|
||||
|
||||
def test_failures_and_needs_login(env):
|
||||
env.runner.error = PublishError("É preciso entrar de novo: captcha.", "needs_login")
|
||||
job_id = _queue(env)
|
||||
env.worker.run_once()
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "needs_login" and "captcha" in job["error"]
|
||||
profile = env.client.get(f"/v1/profiles/{PID}").json()
|
||||
assert profile["status"] == "needs_login"
|
||||
|
||||
# perfil precisando de login: o próximo job nem tenta o navegador
|
||||
env.publisher._update(PID, status="connected")
|
||||
env.runner.error = PublishError("Não achei o botão Publicar.")
|
||||
job_id = env.client.post("/v1/jobs", json=env.job_body(PID, env.video())).json()["jobId"]
|
||||
env.worker.run_once()
|
||||
assert _job(env, job_id)["status"] == "failed" and _job(env, job_id)["error"] == "Não achei o botão Publicar."
|
||||
|
||||
env.runner.error = RuntimeError("bug")
|
||||
job_id = env.client.post("/v1/jobs", json=env.job_body(PID, env.video())).json()["jobId"]
|
||||
env.worker.run_once()
|
||||
assert _job(env, job_id)["status"] == "failed" and "Erro inesperado" in _job(env, job_id)["error"]
|
||||
|
||||
|
||||
def test_session_job_uses_runner_without_link(env):
|
||||
job_id = _queue(env)
|
||||
env.worker.run_once()
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "done" and job["remoteId"] is None and job["url"] is None
|
||||
assert "link não encontrado" in job["step"]
|
||||
|
||||
|
||||
def test_disconnected_profile_and_deleted_file(env):
|
||||
job_id = _queue(env)
|
||||
env.client.delete(f"/v1/profiles/{PID}")
|
||||
assert _job(env, job_id)["status"] == "canceled" # desconectar cancela o que estava na fila
|
||||
|
||||
job_id = _queue(env)
|
||||
video = env.root / "output" / "clip.mp4"
|
||||
video.unlink()
|
||||
env.worker.run_once()
|
||||
job = _job(env, job_id)
|
||||
assert job["status"] == "failed" and "não existe" in job["error"]
|
||||
|
||||
|
||||
def test_canceled_job_is_not_run(env):
|
||||
job_id = _queue(env)
|
||||
env.client.post(f"/v1/jobs/{job_id}/cancel")
|
||||
called = []
|
||||
Worker(env.db, lambda row, progress: called.append(row)).run_once()
|
||||
assert called == [] and _job(env, job_id)["status"] == "canceled"
|
||||
|
||||
|
||||
def test_running_job_becomes_failed_on_restart(env):
|
||||
job_id = _queue(env)
|
||||
env.db.run("UPDATE jobs SET status = 'running' WHERE job_id = ?", job_id)
|
||||
env.db.close()
|
||||
db = Database(env.settings.db_path) # "subida" do serviço
|
||||
try:
|
||||
assert db.interrupted_on_start == [job_id]
|
||||
row = db.get("SELECT * FROM jobs WHERE job_id = ?", job_id)
|
||||
assert row["status"] == "failed" and row["error"] == INTERRUPTED and "tente de novo" in INTERRUPTED
|
||||
finally:
|
||||
db.close()
|
||||
env.db = Database(env.settings.db_path) # a fixture fecha este
|
||||
|
||||
|
||||
def test_jobs_run_in_order_one_at_a_time(env):
|
||||
first = _queue(env)
|
||||
second = env.client.post("/v1/jobs", json=env.job_body(PID, env.video())).json()["jobId"]
|
||||
order = []
|
||||
worker = Worker(env.db, lambda row, progress: order.append(row["job_id"]) or PublishResult("x", None))
|
||||
worker.run_once()
|
||||
assert order == [first] and _job(env, second)["status"] == "queued"
|
||||
worker.run_once()
|
||||
assert order == [first, second]
|
||||
|
||||
|
||||
def test_worker_thread_starts_and_stops(env):
|
||||
job_id = _queue(env)
|
||||
done = []
|
||||
worker = Worker(env.db, lambda row, progress: done.append(1) or PublishResult("x", None), idle_wait_s=0.05)
|
||||
worker.start()
|
||||
worker.wake()
|
||||
import time
|
||||
deadline = time.time() + 5
|
||||
while not done and time.time() < deadline:
|
||||
time.sleep(0.05)
|
||||
worker.stop()
|
||||
assert done and _job(env, job_id)["status"] == "done"
|
||||
Reference in New Issue
Block a user