Files
feedmill-recounter/tests/test_download_compress.py
jetson d3d58ffcde fix: harden the output lifecycle (range requests, temp files, job gate)
Review of the compression branch (ce93c68..d7c1415): one Important and the
cheap real Minors, each with a RED test first.

- app.py: drop the manual Content-Length override - it broke ranged
  requests (206 announcing the full length while sending a slice).
  send_file sets it and the 206/Content-Range itself.
- app.py: the download route serves video extensions only, never the temp
  of an encode in flight.
- src/compress.py: the encode temp is unique per attempt (mkstemp), is
  validated (playable video) and fsynced before it replaces the original;
  a failing os.replace keeps the original and cleans the temp up instead
  of raising into the route. The compressed video keeps the source mode.
- src/compress.py: a stale temp of a killed encode is swept after 2 h
  instead of the 5-day video expiry.
- src/job.py: cancelled and failed jobs are not re-encoded; the job shows
  "Compressing..." while the encode runs.
- ERD.md: the $OUTPUT_DIR/*_compressed.mp4 row is gone.

328 tests pass (was 319).
2026-10-28 15:47:28 +07:00

201 lines
6.9 KiB
Python

"""Tests for the download route and the in-place compression it triggers."""
import os
import shutil
import subprocess
import threading
import time
import pytest
from unittest import mock
import app as app_module
import src.compress as compress_module
from src.compress import compress_in_place
# ── the route ─────────────────────────────────────────────────────────────
@pytest.fixture
def client():
from app import app
app.config["TESTING"] = True
with app.test_client() as c:
yield c
def _job_with_file(status="COMPLETED", name="out.mp4", content=b"video-bytes"):
from app import job_queue
from src.job import JobStatus
job = job_queue.add_job(video_path="/tmp/test.mp4", model_configs=[])
time.sleep(0.3)
with job_queue._lock:
job.status = JobStatus[status]
path = os.path.join(job.output_dir, name)
with open(path, "wb") as fh:
fh.write(content)
return job, path
def _completed_job_with_file(name="out.mp4", content=b"video-bytes"):
return _job_with_file("COMPLETED", name, content)
def test_download_route_serves_the_video(client):
job, _path = _completed_job_with_file()
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 200
assert resp.data == b"video-bytes"
def test_download_route_serves_the_plain_name(client):
"""The client never sees a '_compressed' file name."""
job, _path = _completed_job_with_file()
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 200
disposition = resp.headers.get("Content-Disposition", "")
assert "_compressed" not in disposition
assert "out.mp4" in disposition
def test_download_route_compresses_a_big_file_in_place(client):
"""An oversized download is shrunk and served under its own name."""
job, path = _completed_job_with_file(content=b"x" * 300_000)
def fake_run(cmd, **kwargs):
with open(cmd[-1], "wb") as fh:
fh.write(b"compressed")
return subprocess.CompletedProcess(cmd, 0)
# the route calls the real compressor; only the cap is lowered so the
# test file counts as oversized
real_compress = compress_module.compress_in_place
def small_cap(file_path):
return real_compress(file_path, max_bytes=1024)
with mock.patch.object(app_module, "compress_in_place", small_cap), \
mock.patch.object(compress_module, "probe_video", return_value={"duration": 2.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=fake_run):
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 200
assert resp.data == b"compressed"
# one file in the job dir, the compressed one
assert sorted(os.listdir(job.output_dir)) == ["out.mp4"]
def test_download_route_409_when_job_running(client):
"""No downloads while the job is still writing its output."""
job, _path = _job_with_file("RUNNING")
with mock.patch.object(app_module, "compress_in_place") as m:
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 409
m.assert_not_called()
def test_download_route_409_when_job_pending(client):
job, _path = _job_with_file("PENDING")
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 409
def test_download_route_404_when_the_file_is_gone(client):
job, path = _completed_job_with_file()
os.remove(path)
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 404
def test_download_route_rejects_a_non_video_filename(client):
"""The route serves videos only - never a temp file or a stray file."""
job, _path = _completed_job_with_file()
# a temp of an encode in flight, and a stray file, both in the job dir
tmp = os.path.join(job.output_dir, "out.mp4.compress.tmp")
with open(tmp, "wb") as fh:
fh.write(b"partial")
stray = os.path.join(job.output_dir, "notes.txt")
with open(stray, "wb") as fh:
fh.write(b"text")
for name in ("out.mp4.compress.tmp", "notes.txt"):
resp = client.get(f"/download/{job.job_id}/{name}")
assert resp.status_code == 404, name
def test_range_request_gets_the_right_content_length(client):
"""A ranged request must announce the length of the body it sends."""
job, _path = _completed_job_with_file(content=b"x" * 10_000)
resp = client.get(
f"/download/{job.job_id}/out.mp4",
headers={"Range": "bytes=0-999"},
)
assert resp.status_code == 206
assert resp.headers["Content-Length"] == "1000"
assert len(resp.data) == 1000
# ── one encode for concurrent downloads ──────────────────────────────────
def test_concurrent_downloads_encode_once(tmp_path):
"""Two threads on the same file share one encode."""
f = tmp_path / "big.mp4"
f.write_bytes(b"x" * 300_000)
calls = []
def slow_run(cmd, **kwargs):
calls.append(cmd)
time.sleep(0.3)
with open(cmd[-1], "wb") as fh:
fh.write(b"compressed")
return subprocess.CompletedProcess(cmd, 0)
results = []
def worker():
results.append(compress_in_place(str(f), max_bytes=200_000))
with mock.patch.object(compress_module, "probe_video", return_value={"duration": 2.0}), \
mock.patch.object(compress_module.subprocess, "run", side_effect=slow_run):
threads = [threading.Thread(target=worker) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join(timeout=30)
assert len(calls) == 1
assert f.read_bytes() == b"compressed"
assert results[0] == str(f)
# ── real ffmpeg smoke test ───────────────────────────────────────────────
@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed")
def test_real_ffmpeg_smoke(tmp_path):
"""A real encode lands under the byte cap and replaces the source."""
src = tmp_path / "tiny.mp4"
# lossless source so it is genuinely larger than max_bytes
subprocess.run(
["ffmpeg", "-y",
"-f", "lavfi", "-i", "testsrc=duration=2:size=320x240:rate=10",
"-f", "lavfi", "-i", "sine=frequency=440:duration=2",
"-c:v", "libx264", "-qp", "0", "-preset", "veryfast",
"-c:a", "aac", "-b:a", "128k", "-shortest", str(src)],
check=True, capture_output=True, stdin=subprocess.DEVNULL,
)
max_bytes = 60_000
assert os.path.getsize(src) > max_bytes, "source must exceed cap to compress"
out = compress_in_place(str(src), max_bytes=max_bytes)
assert out == str(src)
assert os.path.getsize(out) <= max_bytes
assert list(tmp_path.glob("*.compress.tmp")) == []
assert [p.name for p in tmp_path.iterdir()] == ["tiny.mp4"]