videogen/tests/reelforge/test_free_export_watermark.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

314 lines
12 KiB
Python

"""Tests for the MG-WATERMARK "Made with Menivor" free-tier export.
Growth gap closed 2026-11-07 (plans/menivor.md): the product already had full
watermark/endcard infrastructure (``app.domains.megaphone.endcard``,
``app.services.compose.compose_ffmpeg``) but it was wired only for Megaphone's
internal self-promo reels and paid BYO-brand logo overlays — never as a
default-on mark on real free-tier user output. ``_generate_free_export``
(app/services/reelforge.py) closes that gap by splicing the EXISTING
``endcard.CARDS["menivor"]`` card onto the full reel via the EXISTING
``compose_ffmpeg.concat_with_broll`` outro path, gated on the EXISTING
``user_entitlements.can_access_clean_result`` check.
Covered behaviours:
* A PAID owner is skipped entirely: no card rendered, no concat run, no R2
upload, "" returned.
* A FREE-tier owner gets a real card + concat + upload, with the correct
outro_path/max_broll_s (the card's own CARD_SECONDS, not the default
2.5s b-roll cap which would truncate the "Made with Menivor" text).
* A missing job row degrades to "" (never raises).
* Any failure in the render/concat/upload path is swallowed (never fails
the job) and returns "".
* One real-ffmpeg integration test: builds the actual end card and splices
it onto a synthetic reel, then ffprobes the result to prove the output
really is longer by the card's duration AND that the appended segment is
the card's near-black background (not more of the colourful main clip),
i.e. the mark is visibly present in the real output file.
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
from contextlib import contextmanager
import pytest
from app.services import reelforge
# --------------------------------------------------------------------------- #
# Fakes
# --------------------------------------------------------------------------- #
class _FakeJob:
def __init__(self, user_id: str) -> None:
self.user_id = user_id
class _FakeJobRepository:
def __init__(self, job: _FakeJob | None) -> None:
self._job = job
def get(self, job_id: str): # noqa: ANN001
return self._job
class _FakeR2:
def __init__(self) -> None:
self.uploads: list[tuple[str, str, str]] = []
def upload_file(self, local_path: str, key: str, content_type: str) -> str:
self.uploads.append((local_path, key, content_type))
return f"https://cdn.example/{key}"
def _patch_db(monkeypatch: pytest.MonkeyPatch, job: _FakeJob | None) -> None:
@contextmanager
def _fake_get_session():
yield object()
monkeypatch.setattr("app.models.db.base.get_session", _fake_get_session)
monkeypatch.setattr(
"app.models.db.repositories.JobRepository",
lambda session: _FakeJobRepository(job),
)
# --------------------------------------------------------------------------- #
# Entitlement gate
# --------------------------------------------------------------------------- #
def test_free_export_skipped_for_paid_owner(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
_patch_db(monkeypatch, _FakeJob(user_id="paid-user-1"))
monkeypatch.setattr(
"app.services.user_entitlements.can_access_clean_result", lambda uid: True
)
def _boom(*a, **k): # noqa: ANN002, ANN003
raise AssertionError("endcard.render must not be called for a paid owner")
monkeypatch.setattr("app.domains.megaphone.endcard.render", _boom)
out = reelforge._generate_free_export("jobPaid", str(tmp_path / "final.mp4"), str(tmp_path))
assert out == ""
def test_free_export_missing_job_returns_empty(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
_patch_db(monkeypatch, None)
def _boom(*a, **k): # noqa: ANN002, ANN003
raise AssertionError("can_access_clean_result must not be reached without a job")
monkeypatch.setattr("app.services.user_entitlements.can_access_clean_result", _boom)
out = reelforge._generate_free_export("jobMissing", str(tmp_path / "final.mp4"), str(tmp_path))
assert out == ""
# --------------------------------------------------------------------------- #
# Free-tier owner: real wiring (card render + concat + upload), I/O stubbed
# --------------------------------------------------------------------------- #
def test_free_export_generated_for_free_owner(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
_patch_db(monkeypatch, _FakeJob(user_id="free-user-1"))
monkeypatch.setattr(
"app.services.user_entitlements.can_access_clean_result", lambda uid: False
)
rendered: dict = {}
def _fake_render(product: str, out_path: str) -> str:
rendered["product"] = product
rendered["out_path"] = out_path
with open(out_path, "wb") as fh:
fh.write(b"card")
return out_path
monkeypatch.setattr("app.domains.megaphone.endcard.render", _fake_render)
concat_calls: dict = {}
def _fake_concat(main_path, output_file, *, outro_path=None, max_broll_s=None, **kw): # noqa: ANN001
concat_calls["main_path"] = main_path
concat_calls["output_file"] = output_file
concat_calls["outro_path"] = outro_path
concat_calls["max_broll_s"] = max_broll_s
with open(output_file, "wb") as fh:
fh.write(b"final-with-card")
return output_file
monkeypatch.setattr(
"app.services.compose.compose_ffmpeg.concat_with_broll", _fake_concat
)
fake_r2 = _FakeR2()
monkeypatch.setattr(reelforge, "_r2", lambda: fake_r2)
final_video = str(tmp_path / "final.mp4")
with open(final_video, "wb") as fh:
fh.write(b"main-reel")
out = reelforge._generate_free_export("jobFree1", final_video, str(tmp_path))
assert out == "jobs/jobFree1/free_export.mp4"
assert rendered["product"] == "menivor"
assert concat_calls["main_path"] == final_video
assert concat_calls["outro_path"] == rendered["out_path"]
# Must NOT use the default 2.5s b-roll cap — that would truncate the card.
from app.domains.megaphone import endcard as endcard_module
assert concat_calls["max_broll_s"] == endcard_module.CARD_SECONDS
assert fake_r2.uploads and fake_r2.uploads[0][1] == "jobs/jobFree1/free_export.mp4"
assert fake_r2.uploads[0][2] == "video/mp4"
def test_free_export_concat_failure_is_swallowed(
monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
_patch_db(monkeypatch, _FakeJob(user_id="free-user-2"))
monkeypatch.setattr(
"app.services.user_entitlements.can_access_clean_result", lambda uid: False
)
monkeypatch.setattr(
"app.domains.megaphone.endcard.render",
lambda product, out_path: out_path,
)
def _fail_concat(*a, **k): # noqa: ANN002, ANN003
raise RuntimeError("simulated ffmpeg concat failure")
monkeypatch.setattr(
"app.services.compose.compose_ffmpeg.concat_with_broll", _fail_concat
)
out = reelforge._generate_free_export(
"jobFreeFail", str(tmp_path / "final.mp4"), str(tmp_path)
)
assert out == ""
def test_free_export_entitlement_check_failure_still_renders(
monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
"""An unverifiable entitlement check degrades to "render the free export"
rather than raising — the job's render must never fail because billing is
flaky; worst case a paid owner transiently also gets the (unused) card.
"""
_patch_db(monkeypatch, _FakeJob(user_id="unverifiable-user"))
def _boom(uid): # noqa: ANN001
raise RuntimeError("billing lookup outage")
monkeypatch.setattr("app.services.user_entitlements.can_access_clean_result", _boom)
monkeypatch.setattr(
"app.domains.megaphone.endcard.render", lambda product, out_path: out_path
)
monkeypatch.setattr(
"app.services.compose.compose_ffmpeg.concat_with_broll",
lambda main_path, output_file, **kw: open(output_file, "wb").close() or output_file,
)
monkeypatch.setattr(reelforge, "_r2", lambda: _FakeR2())
out = reelforge._generate_free_export(
"jobUnverifiable", str(tmp_path / "final.mp4"), str(tmp_path)
)
assert out == "jobs/jobUnverifiable/free_export.mp4"
# --------------------------------------------------------------------------- #
# Real-ffmpeg integration: the mark is actually visible in the output file
# --------------------------------------------------------------------------- #
_FFMPEG = shutil.which("ffmpeg")
_FFPROBE = shutil.which("ffprobe")
def _have_media_stack() -> bool:
if not _FFMPEG or not _FFPROBE:
return False
from app.services.compose.compose_ffmpeg import ffmpeg_has_filter
required = ("scale", "crop", "concat", "anullsrc", "atrim", "aformat", "drawtext")
return all(ffmpeg_has_filter(f, _FFMPEG) for f in required)
def _run(cmd):
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
raise RuntimeError(result.stderr or result.stdout or "ffmpeg failed")
def _probe(path):
result = subprocess.run(
[_FFPROBE, "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path],
capture_output=True, text=True, check=False,
)
assert result.returncode == 0, result.stderr
return json.loads(result.stdout)
@pytest.mark.integration
@pytest.mark.skipif(
not _have_media_stack(), reason="ffmpeg/ffprobe with drawtext/concat not available"
)
def test_real_free_export_appends_visible_made_with_menivor_card(tmp_path):
"""Builds the REAL end card and splices it onto a synthetic reel, end to end,
using the exact two already-built functions the growth gap flagged
(``endcard.render`` + ``compose_ffmpeg.concat_with_broll``) — proving the
"Made with Menivor" mark really renders into real pixels, not just that the
code path is wired.
"""
from app.domains.megaphone import endcard
from app.services.compose.compose_ffmpeg import concat_with_broll
main = str(tmp_path / "main.mp4")
card = str(tmp_path / "card.mp4")
out = str(tmp_path / "free_export.mp4")
# A bright, colourful 2s "reel" (lavfi testsrc2), portrait, with audio.
_run([
_FFMPEG, "-y",
"-f", "lavfi", "-i", "testsrc2=size=1080x1920:rate=30:duration=2",
"-f", "lavfi", "-i", "sine=frequency=440:duration=2",
"-c:v", "libx264", "-c:a", "aac", "-pix_fmt", "yuv420p", "-shortest", main,
])
endcard.render("menivor", card)
assert os.path.exists(card) and os.path.getsize(card) > 0
concat_with_broll(main, out, outro_path=card, max_broll_s=endcard.CARD_SECONDS, fps=30)
assert os.path.exists(out) and os.path.getsize(out) > 0
info = _probe(out)
duration = float(info["format"]["duration"])
# main (2.0s) + card (CARD_SECONDS == 3.0s) ~= 5.0s.
assert 4.6 <= duration <= 5.6, f"unexpected duration {duration}s"
# Grab a frame from well inside the appended card segment (main ends ~2s in)
# and confirm it is near-black (the card's background), i.e. the main
# clip's bright testsrc2 pattern has genuinely ended and the card is
# really the trailing content, not a no-op.
frame_png = str(tmp_path / "card_frame.png")
_run([
_FFMPEG, "-y", "-ss", "3.5", "-i", out, "-frames:v", "1", frame_png,
])
assert os.path.exists(frame_png) and os.path.getsize(frame_png) > 0
# Average luma of that frame: the card is black with white/grey text, so
# mean brightness must be far below the bright, saturated testsrc2 frame.
probe_signal = subprocess.run(
[
_FFMPEG, "-i", out, "-ss", "3.5", "-frames:v", "1",
"-vf", "signalstats", "-f", "null", "-",
],
capture_output=True, text=True, check=False,
)
stderr = probe_signal.stderr or ""
# signalstats logs YAVG=<value> on the frame line; a near-black card frame
# should average well under mid-grey (128).
import re
match = re.search(r"YAVG:([0-9.]+)", stderr)
assert match, f"signalstats YAVG not found in: {stderr[-500:]}"
yavg = float(match.group(1))
assert yavg < 60, f"expected a near-black end-card frame, got YAVG={yavg}"