Files
feedmill-recounter/tests/test_app.py
T

453 lines
14 KiB
Python

"""Integration tests for Flask web app."""
import io
import json
import pytest
from app import app
@pytest.fixture
def client():
app.config["TESTING"] = True
with app.test_client() as client:
yield client
def test_index_page(client):
"""GET / returns 200."""
resp = client.get("/")
assert resp.status_code == 200
def test_jobs_page(client):
"""GET /jobs returns 200."""
resp = client.get("/jobs")
assert resp.status_code == 200
def test_api_models(client):
"""GET /api/models returns JSON list."""
resp = client.get("/api/models")
assert resp.status_code == 200
data = resp.get_json()
assert isinstance(data, list)
def test_api_jobs(client):
"""GET /api/jobs returns JSON list."""
resp = client.get("/api/jobs")
assert resp.status_code == 200
data = resp.get_json()
assert isinstance(data, list)
def test_upload_no_video(client):
"""POST /upload without video returns 400."""
resp = client.post("/upload")
assert resp.status_code == 400
def test_upload_invalid_extension_rejected(client):
"""POST /upload with a non-video file returns 400."""
resp = client.post(
"/upload",
data={"video": (io.BytesIO(b"not a video"), "notes.txt")},
content_type="multipart/form-data",
)
assert resp.status_code == 400
def test_status_nonexistent(client):
"""GET /status/nonexistent returns 404."""
resp = client.get("/status/nonexistent")
assert resp.status_code == 404
def test_api_job_detail_nonexistent(client):
"""GET /api/jobs/nonexistent returns 404."""
resp = client.get("/api/jobs/nonexistent")
assert resp.status_code == 404
def test_cancel_nonexistent_job(client):
"""POST /api/jobs/nonexistent/cancel returns 404."""
resp = client.post("/api/jobs/nonexistent/cancel")
assert resp.status_code == 404
data = resp.get_json()
assert data["error"] == "not found"
def test_cancel_completed_job(client):
"""POST /api/jobs/<id>/cancel returns 400 for completed job."""
from src.job import JobQueue, Job, JobStatus
from app import job_queue
job = job_queue.add_job(video_path="/tmp/test.mp4", model_configs=[])
import time
time.sleep(0.3)
# Force status to COMPLETED
with job_queue._lock:
job.status = JobStatus.COMPLETED
resp = client.post(f"/api/jobs/{job.job_id}/cancel")
assert resp.status_code == 400
data = resp.get_json()
assert "cannot cancel" in data["error"]
def test_cancel_pending_or_running_job(client):
"""POST /api/jobs/<id>/cancel returns 200 for cancellable job."""
from src.job import JobQueue, JobStatus
from app import job_queue
job = job_queue.add_job(video_path="/tmp/test.mp4", model_configs=[])
import time
time.sleep(0.1)
# Force status to RUNNING so cancel succeeds
with job_queue._lock:
job.status = JobStatus.RUNNING
resp = client.post(f"/api/jobs/{job.job_id}/cancel")
assert resp.status_code == 200
data = resp.get_json()
assert data["status"] == "cancelled"
# Verify job is now CANCELLED
fetched = job_queue.get_job(job.job_id)
assert fetched.status == JobStatus.CANCELLED
# ── Box counts in API + status page (Task 2) ────────────────────────────
def _job_with_box_results():
import time
from app import job_queue
from src.job import JobResult, JobStatus
job = job_queue.add_job(video_path="/tmp/test.mp4", model_configs=[])
time.sleep(0.3)
with job_queue._lock:
job.status = JobStatus.COMPLETED
job.results.append(JobResult(
model_name="a.pt",
output_path="/tmp/out.mp4",
loading_count=5,
unloading_count=2,
net_count=3,
batch_count=1,
frame_count=10,
duration_seconds=1.0,
box_loading_count=4,
box_unloading_count=1,
box_net_count=3,
))
return job
def test_api_job_detail_includes_box_counts(client):
"""GET /api/jobs/<id> results JSON carries box counts."""
job = _job_with_box_results()
resp = client.get(f"/api/jobs/{job.job_id}")
assert resp.status_code == 200
r = resp.get_json()["results"][0]
assert r["box_loading_count"] == 4
assert r["box_unloading_count"] == 1
assert r["box_net_count"] == 3
assert r["loading_count"] == 5
def test_status_page_renders_box_and_sack_labels(client):
"""status.html shows Sack In/Out and Box In/Out stat labels."""
job = _job_with_box_results()
resp = client.get(f"/status/{job.job_id}")
assert resp.status_code == 200
html = resp.get_data(as_text=True)
assert "Sack In" in html
assert "Sack Out" in html
assert "Box In" in html
assert "Box Out" in html
def test_api_job_detail_includes_live_box_counts(client):
"""GET /api/jobs/<id> carries live box count keys (defaults 0)."""
job = _job_with_box_results()
resp = client.get(f"/api/jobs/{job.job_id}")
assert resp.status_code == 200
data = resp.get_json()
assert data["live_box_loading"] == 0
assert data["live_box_unloading"] == 0
def test_job_defaults_live_box_counts_zero():
"""Job dataclass defaults live box counts to 0."""
from src.job import Job
job = Job(job_id="test", video_path="/tmp/x.mp4", model_configs=[])
assert job.live_box_loading == 0
assert job.live_box_unloading == 0
# ── Download progress (Task: progress bars) ──────────────────────────────
def _completed_job_with_output(content=b"video-bytes"):
import os
import time
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.COMPLETED
path = os.path.join(job.output_dir, "out.mp4")
with open(path, "wb") as fh:
fh.write(content)
return job, path
def test_download_route_sets_content_length(client):
"""GET /download/<id>/<file> sets Content-Length equal to file size."""
import os
from app import _compress_for_download
job, path = _completed_job_with_output()
expected = os.path.getsize(path)
# Small file: helper returns None, route serves the original.
assert _compress_for_download(path) is None
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 200
assert resp.headers["Content-Length"] == str(expected)
assert int(resp.headers["Content-Length"]) == expected
def test_status_page_has_download_progress_markup(client):
"""Rendered status page carries the download progress bar markup."""
job = _job_with_box_results()
resp = client.get(f"/status/{job.job_id}")
assert resp.status_code == 200
html = resp.get_data(as_text=True)
assert "data-download-progress" in html
assert "data-download-bar" in html
assert "download-progress-fill" in html
# ── MJPEG preview endpoint (mtime guard) ────────────────────────────────
def _job_with_preview(jpeg: bytes):
"""Completed job whose preview file exists with the given bytes."""
import time
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.COMPLETED
with open(job.preview_path, "wb") as fh:
fh.write(jpeg)
return job
def _cleanup_preview_job(job):
from app import job_queue
job_queue.delete_job(job.job_id)
def test_api_preview_unknown_job_returns_404(client):
"""GET /api/preview/nonexistent returns 404."""
resp = client.get("/api/preview/nonexistent")
assert resp.status_code == 404
def test_api_preview_yields_jpeg_once_when_mtime_unchanged(client, monkeypatch):
"""First frame is yielded; unchanged mtime skips the re-read/yield."""
import builtins
import app as app_mod
job = _job_with_preview(b"\xff\xd8fakejpeg\xff\xd9")
state = {"opens": 0, "sleeps": 0}
real_open = builtins.open
def counting_open(path, *args, **kwargs):
if path == job.preview_path:
state["opens"] += 1
return real_open(path, *args, **kwargs)
class _StopLoop(Exception):
pass
class _FakeTime:
def sleep(self, seconds):
state["sleeps"] += 1
if state["sleeps"] >= 2:
raise _StopLoop()
monkeypatch.setattr(app_mod, "_time", _FakeTime())
monkeypatch.setattr(app_mod, "open", counting_open, raising=False)
try:
resp = client.get(f"/api/preview/{job.job_id}")
assert resp.status_code == 200
it = iter(resp.response)
first = next(it)
assert first.startswith(b"--frame\r\nContent-Type: image/jpeg\r\n\r\n")
assert b"fakejpeg" in first
# Unchanged mtime: no second read, falls through to sleep → loop stops.
with pytest.raises(_StopLoop):
next(it)
assert state["opens"] == 1, "preview JPEG re-read despite unchanged mtime"
finally:
_cleanup_preview_job(job)
def test_api_preview_yields_again_after_mtime_change(client):
"""A newer mtime triggers a fresh read + yield."""
import os
job = _job_with_preview(b"jpeg-version-1")
try:
resp = client.get(f"/api/preview/{job.job_id}")
it = iter(resp.response)
first = next(it)
assert b"jpeg-version-1" in first
st = os.stat(job.preview_path)
with open(job.preview_path, "wb") as fh:
fh.write(b"jpeg-version-2")
os.utime(job.preview_path, (st.st_atime + 5, st.st_mtime + 5))
second = next(it)
assert b"jpeg-version-2" in second
close = getattr(resp.response, "close", None)
if close:
close()
finally:
_cleanup_preview_job(job)
# ── Zone ROI is FCP's calibration (1280x720 frame), not the clip's size ────
FCP_ZONE = {
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
"reference_resolution": [1920, 1080],
}
def test_zone_roi_is_built_at_1280x720():
"""The ROI is FCP's calibration, not the function clip's resolution."""
import app as app_module
roi = app_module._static_roi(FCP_ZONE)
assert roi.line_y == 220
assert (roi.x1, roi.x2) == (400, 936)
# ── Zone mode default: calibrated static zone (FCP parity) ───────────────
ZONE_JSON = {
"active_preset": "default",
"presets": {"default": FCP_ZONE},
}
@pytest.fixture
def buf(tmp_path):
"""A tiny valid mp4 as an in-memory upload stream."""
import cv2
import numpy as np
path = tmp_path / "tiny.mp4"
writer = cv2.VideoWriter(
str(path), cv2.VideoWriter_fourcc(*"mp4v"), 5.0, (64, 64)
)
for i in range(5):
writer.write(np.full((64, 64, 3), i * 20, dtype=np.uint8))
writer.release()
return io.BytesIO(path.read_bytes())
@pytest.fixture
def analyze_env(tmp_path, monkeypatch):
"""Isolate /api/analyze: uploads land in tmp_path, no real model runs."""
import os
import app as app_module
import src.job as job_mod
uploads = tmp_path / "uploads"
os.makedirs(uploads, exist_ok=True)
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(uploads))
class _Result:
output_path = "annotated.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
monkeypatch.setattr(job_mod, "run_pipeline", lambda **kw: _Result())
monkeypatch.setattr(job_mod, "run_merged_pipeline", lambda **kw: _Result())
return app_module
def _wait_job_done(job, timeout=10.0):
"""Block until the job leaves PENDING/RUNNING (keeps the stub in place)."""
import time
from src.job import JobStatus
deadline = time.time() + timeout
while job.status in (JobStatus.PENDING, JobStatus.RUNNING):
assert time.time() < deadline, "job never finished"
time.sleep(0.01)
def test_analyze_defaults_to_fixed_zone_mode(client, buf, analyze_env, tmp_path, monkeypatch):
"""POST /api/analyze without zone_mode uses the calibrated static zone."""
app_module = analyze_env
zones = tmp_path / "zones.json"
zones.write_text(json.dumps(ZONE_JSON))
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
resp = client.post(
"/api/analyze",
data={"fcp_mode": "C", "video": (buf, "clip.mp4")},
content_type="multipart/form-data",
)
assert resp.status_code == 202
job = app_module.job_queue.get_job(resp.get_json()["job_id"])
assert job.zone_mode == "fixed"
assert job.fixed_zone is not None
assert job.fixed_zone.fixed is True
_wait_job_done(job)
def test_analyze_falls_back_to_dynamic_without_zone_file(client, buf, analyze_env, tmp_path, monkeypatch):
"""No calibration on disk -> dynamic zone, job still accepted."""
app_module = analyze_env
monkeypatch.setattr(app_module, "ZONES_PATH", str(tmp_path / "missing.json"))
resp = client.post(
"/api/analyze",
data={"fcp_mode": "C", "video": (buf, "clip.mp4")},
content_type="multipart/form-data",
)
assert resp.status_code == 202
job = app_module.job_queue.get_job(resp.get_json()["job_id"])
assert job.zone_mode == "dynamic"
assert job.fixed_zone is None
_wait_job_done(job)