Files
feedmill-recounter/tests/test_api_analyze.py
T

349 lines
11 KiB
Python

"""Tests for POST /api/analyze — machine-facing upload endpoint.
Route logic (auth, busy guard, fcp_mode → stems, 202 shape) is tested with
_save_and_queue stubbed; the shared save/transcode path is /upload's, covered
by manual smoke tests (real ffmpeg on real video).
"""
import io
import pytest
from app import app
@pytest.fixture
def client():
app.config["TESTING"] = True
with app.test_client() as client:
yield client
@pytest.fixture
def stub_queue(monkeypatch):
"""Replace _save_and_queue; record calls, return fake job."""
import app as app_module
calls = []
class _FakeJob:
job_id = "job-deadbeef"
def fake_save_and_queue(video, model_configs, class_filters,
output_height, zone_mode, zone_preset):
calls.append({
"model_configs": model_configs,
"class_filters": class_filters,
"output_height": output_height,
"zone_mode": zone_mode,
"zone_preset": zone_preset,
})
return _FakeJob()
monkeypatch.setattr(app_module, "_save_and_queue", fake_save_and_queue)
return calls
def _post(client, data=None, headers=None):
return client.post(
"/api/analyze",
data=data or {},
content_type="multipart/form-data",
headers=headers,
)
# ── validation (JSON 400s, never HTML) ─────────────────────────────────
def test_analyze_no_video_returns_json_400(client, stub_queue):
resp = _post(client, data={"fcp_mode": "C"})
assert resp.status_code == 400
assert resp.get_json()["error"] == "No video uploaded"
def test_analyze_bad_extension_rejected(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "notes.txt"),
"fcp_mode": "C",
})
assert resp.status_code == 400
assert "Invalid" in resp.get_json()["error"]
def test_analyze_unknown_fcp_mode_rejected(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "Z",
})
assert resp.status_code == 400
assert "fcp_mode" in resp.get_json()["error"]
def test_analyze_requires_model_selection(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
})
assert resp.status_code == 400
assert "model" in resp.get_json()["error"].lower()
# ── happy path: fcp_mode resolution + 202 shape ────────────────────────
def test_analyze_fcp_mode_c_resolves_stems_and_returns_202(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
})
assert resp.status_code == 202
body = resp.get_json()
assert body["job_id"] == "job-deadbeef"
assert body["status_url"] == "/api/jobs/job-deadbeef"
stems = [c.stem for c in stub_queue[0]["model_configs"]]
assert stems == [
"v4-best",
"yolo11n-bbox-100ep-sack+box-20260909-best",
]
assert stub_queue[0]["zone_mode"] == "fixed"
def test_analyze_fcp_mode_a_single_model(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "A",
})
assert resp.status_code == 202
stems = [c.stem for c in stub_queue[0]["model_configs"]]
assert stems == ["v4-best"]
def test_analyze_explicit_stems_alternative_to_fcp_mode(client, stub_queue):
"""model_stems path used when fcp_mode absent (fcp_mode wins if both sent)."""
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"model_stems": ["best"],
})
assert resp.status_code == 202
stems = [c.stem for c in stub_queue[0]["model_configs"]]
assert stems == ["best"]
def test_analyze_zone_mode_fixed_passthrough(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
"zone_mode": "freeze",
"output_height": "720",
})
assert resp.status_code == 202
assert stub_queue[0]["zone_mode"] == "freeze"
assert stub_queue[0]["output_height"] == "720"
# ── busy guard (GPU OOM protection) ────────────────────────────────────
def test_analyze_busy_returns_409(client, stub_queue):
import app as app_module
from src.job import JobStatus
job = app_module.job_queue.add_job(
video_path="/tmp/x.mp4", model_configs=[]
)
import time
time.sleep(0.1)
with app_module.job_queue._lock:
job.status = JobStatus.RUNNING
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
})
assert resp.status_code == 409
body = resp.get_json()
assert body["error"] == "busy"
assert any(j["job_id"] == job.job_id for j in body["active"])
# ── optional API-key auth ──────────────────────────────────────────────
def test_analyze_open_when_key_env_unset(client, stub_queue, monkeypatch):
monkeypatch.delenv("RECOUNTER_API_KEY", raising=False)
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
})
assert resp.status_code == 202
def test_analyze_401_when_key_required_and_header_missing(
client, stub_queue, monkeypatch
):
monkeypatch.setenv("RECOUNTER_API_KEY", "sekret")
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
})
assert resp.status_code == 401
assert resp.get_json()["error"] == "unauthorized"
def test_analyze_401_on_wrong_key(client, stub_queue, monkeypatch):
monkeypatch.setenv("RECOUNTER_API_KEY", "sekret")
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
}, headers={"X-API-Key": "wrong"})
assert resp.status_code == 401
def test_analyze_202_on_correct_key(client, stub_queue, monkeypatch):
monkeypatch.setenv("RECOUNTER_API_KEY", "sekret")
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
}, headers={"X-API-Key": "sekret"})
assert resp.status_code == 202
# ── single-model class-filter fix (src/job.py stem key) ───────────────
def test_single_model_job_filter_looked_up_by_stem(monkeypatch):
"""job._run_job passes filter by stem, not filename (regression)."""
import app as app_module
from src.job import JobStatus
from src.model_registry import ModelConfig
captured = {}
def fake_run_pipeline(**kwargs):
captured.update(kwargs)
class _R:
output_path = "x.mp4"
loading_count = 0
unloading_count = 0
net_count = 0
batch_count = 0
frame_count = 0
duration_seconds = 0.0
box_loading_count = 0
box_unloading_count = 0
box_net_count = 0
return _R()
import src.job as job_mod
monkeypatch.setattr(job_mod, "run_pipeline", fake_run_pipeline)
cfg = ModelConfig(
filename="fake-stem.pt", path="/tmp/fake-stem.pt",
stem="fake-stem", known_classes=["sack"],
)
job = app_module.job_queue.add_job(
video_path="/tmp/x.mp4",
model_configs=[cfg],
class_filters={"fake-stem": ["sack", "box"]},
)
import time
time.sleep(0.5)
with app_module.job_queue._lock:
job.status = JobStatus.CANCELLED # keep worker from re-running
assert captured["class_filter"] == ["sack", "box"]
# ── review fixes: per-mode class filters mirroring FCP engines ─────────
def test_fcp_mode_b_filters_mirror_fcp_engines(client, stub_queue):
"""FCP B = v4-best truck-only + yolo11n sack+box (engine classes)."""
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "B",
})
assert resp.status_code == 202
assert stub_queue[0]["class_filters"] == {
"v4-best": ["truck"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["sack", "box"],
}
def test_fcp_mode_c_filters_mirror_fcp_engines(client, stub_queue):
"""FCP C = v4-best truck+sack, yolo11n box-only (no sack double count)."""
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
})
assert resp.status_code == 202
assert stub_queue[0]["class_filters"] == {
"v4-best": ["truck", "sack"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["box"],
}
def test_fcp_mode_d_three_engines(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "D",
})
assert resp.status_code == 202
stems = [c.stem for c in stub_queue[0]["model_configs"]]
assert stems == ["v4-best", "best", "yolo11n-bbox-100ep-sack+box-20260909-best"]
assert stub_queue[0]["class_filters"] == {
"v4-best": ["truck"],
"best": ["sack"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["box"],
}
# ── review fix: busy-check + enqueue must be atomic (no 202/202 race) ──
def test_concurrent_submits_second_gets_409(monkeypatch):
"""Two overlapping POSTs must not both be accepted (one-GPU guard)."""
import time
import threading
import app as app_module
from src.job import JobStatus
def slow_save(video, model_configs, class_filters,
output_height, zone_mode, zone_preset):
time.sleep(0.4) # simulate save+transcode window
job = app_module.job_queue.add_job(
video_path="/tmp/x.mp4", model_configs=[]
)
with app_module.job_queue._lock:
job.status = JobStatus.RUNNING
class _J:
job_id = job.job_id
return _J()
monkeypatch.setattr(app_module, "_save_and_queue", slow_save)
app.config["TESTING"] = True
codes = []
def post():
with app.test_client() as c:
r = c.post(
"/api/analyze",
data={"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C"},
content_type="multipart/form-data",
)
codes.append(r.status_code)
t1 = threading.Thread(target=post)
t2 = threading.Thread(target=post)
t1.start()
time.sleep(0.15) # t1 is now inside slow_save (before job registered? no—
# lock held from busy-check through enqueue, so t2 must wait or be refused)
t2.start()
t1.join(10)
t2.join(10)
assert sorted(codes) == [202, 409], f"got {codes}"