1206 lines
44 KiB
Python
1206 lines
44 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
|
|
# The number is the count of FINISHED batches — say so, or "Batches: 0"
|
|
# reads like "no batch was counted".
|
|
assert "Batches closed:" 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 src.compress import compress_in_place
|
|
|
|
job, path = _completed_job_with_output()
|
|
expected = os.path.getsize(path)
|
|
# Small file: the compressor leaves it alone, the route serves the original.
|
|
assert compress_in_place(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
|
|
frames_expected = 0
|
|
truncated = False
|
|
|
|
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
|
|
assert job.counting_polygon is not None
|
|
assert job.truck_polygon is not None
|
|
_wait_job_done(job)
|
|
|
|
|
|
def test_analyze_reads_the_calibration_once(client, buf, analyze_env, tmp_path, monkeypatch):
|
|
"""One calibration read per request — the ROI and the polygon share it."""
|
|
app_module = analyze_env
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps(ZONE_JSON))
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
|
|
calls: list[str] = []
|
|
original = app_module.get_active_zone
|
|
|
|
def counting_get_active_zone(path, preset_name=None):
|
|
calls.append(path)
|
|
return original(path, preset_name)
|
|
|
|
monkeypatch.setattr(app_module, "get_active_zone", counting_get_active_zone)
|
|
|
|
resp = client.post(
|
|
"/api/analyze",
|
|
data={"fcp_mode": "C", "video": (buf, "clip.mp4")},
|
|
content_type="multipart/form-data",
|
|
)
|
|
assert resp.status_code == 202
|
|
assert calls == [str(zones)]
|
|
_wait_job_done(app_module.job_queue.get_job(resp.get_json()["job_id"]))
|
|
|
|
|
|
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
|
|
assert job.counting_polygon is None
|
|
assert job.truck_polygon is None
|
|
_wait_job_done(job)
|
|
|
|
|
|
def test_analyze_falls_back_to_dynamic_with_corrupt_zone_file(client, buf, analyze_env, tmp_path, monkeypatch, capsys):
|
|
"""A corrupt zones.json degrades to dynamic instead of 500."""
|
|
app_module = analyze_env
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text('{"presets": {"default": ') # truncated 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 == "dynamic"
|
|
assert job.fixed_zone is None
|
|
assert job.counting_polygon is None
|
|
_wait_job_done(job)
|
|
|
|
out = capsys.readouterr().out
|
|
assert "unreadable calibration" in out
|
|
assert "dynamic" in out
|
|
|
|
|
|
def test_analyze_falls_back_to_dynamic_with_a_malformed_truck_area(client, buf, analyze_env, tmp_path, monkeypatch, capsys):
|
|
"""A calibration the ROI builder rejects degrades to dynamic instead of 500."""
|
|
app_module = analyze_env
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps({
|
|
"active_preset": "default",
|
|
"presets": {"default": {**FCP_ZONE, "truck_area": [[600, 385]]}},
|
|
}))
|
|
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 == "dynamic"
|
|
assert job.fixed_zone is None
|
|
assert job.counting_polygon is None
|
|
_wait_job_done(job)
|
|
|
|
out = capsys.readouterr().out
|
|
assert "dynamic" in out
|
|
|
|
|
|
def test_analyze_falls_back_to_dynamic_with_malformed_counting_area(client, buf, analyze_env, tmp_path, monkeypatch, capsys):
|
|
"""A structurally invalid counting_area degrades to dynamic instead of 500."""
|
|
app_module = analyze_env
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps({
|
|
"active_preset": "default",
|
|
"presets": {"default": {
|
|
**FCP_ZONE,
|
|
"counting_area": [["a", "b"], ["c", "d"], ["e", "f"]],
|
|
}},
|
|
}))
|
|
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 == "dynamic"
|
|
assert job.fixed_zone is None
|
|
assert job.counting_polygon is None
|
|
assert job.truck_polygon is None
|
|
_wait_job_done(job)
|
|
|
|
out = capsys.readouterr().out
|
|
assert "falling back to dynamic" in out
|
|
|
|
|
|
def test_upload_reuse_defaults_to_fixed_zone_mode(client, analyze_env, tmp_path, monkeypatch):
|
|
"""POST /upload/reuse uses the calibrated static zone, like /upload."""
|
|
from src.model_registry import ModelConfig
|
|
|
|
app_module = analyze_env
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps(ZONE_JSON))
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
|
|
clip = tmp_path / "clip.mp4"
|
|
clip.write_bytes(b"fake")
|
|
monkeypatch.setattr(app_module, "probe_video",
|
|
lambda p: {"width": 1280, "height": 720, "duration": 1.0})
|
|
monkeypatch.setattr(
|
|
app_module, "_parse_model_configs",
|
|
lambda form: ([ModelConfig(filename="best.pt", path="models/best.pt",
|
|
stem="best", known_classes=["sack"])], {}),
|
|
)
|
|
|
|
resp = client.post("/upload/reuse", data={"video_path": str(clip)},
|
|
content_type="multipart/form-data")
|
|
assert resp.status_code == 302
|
|
job = app_module.job_queue.get_job(resp.headers["Location"].split("/")[-1])
|
|
assert job.zone_mode == "fixed"
|
|
assert job.fixed_zone is not None
|
|
assert job.counting_polygon is not None
|
|
_wait_job_done(job)
|
|
|
|
|
|
def test_api_job_list_and_detail_report_truncation(client):
|
|
"""Both job endpoints carry the truncation flag and the expected frame count."""
|
|
import time
|
|
|
|
from app import job_queue
|
|
from src.job import JobResult, JobStatus
|
|
|
|
job = job_queue.add_job(video_path="/tmp/x.mp4", model_configs=[])
|
|
time.sleep(0.3)
|
|
with job_queue._lock:
|
|
job.status = JobStatus.COMPLETED
|
|
job.results.append(JobResult(
|
|
model_name="best.pt",
|
|
output_path="/tmp/x.mp4",
|
|
loading_count=1, unloading_count=2, net_count=-1,
|
|
batch_count=1, frame_count=40, duration_seconds=1.0,
|
|
frames_expected=100, truncated=True,
|
|
))
|
|
|
|
detail = client.get(f"/api/jobs/{job.job_id}").get_json()
|
|
assert detail["results"][0]["truncated"] is True
|
|
assert detail["results"][0]["frames_expected"] == 100
|
|
|
|
listing = client.get("/api/jobs").get_json()
|
|
entry = next(j for j in listing if j["job_id"] == job.job_id)
|
|
assert entry["results"][0]["truncated"] is True
|
|
assert entry["results"][0]["frames_expected"] == 100
|
|
|
|
|
|
def _zones_file(tmp_path, preset):
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps({"presets": {"default": preset}, "active_preset": "default"}))
|
|
return str(zones)
|
|
|
|
|
|
def test_post_zones_saves_valid_preset(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
preset = {
|
|
"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],
|
|
}
|
|
zones = _zones_file(tmp_path, preset)
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default", json={"preset": {**preset, "count_line": {"x_start": 600, "x_end": 1350, "y": 315}}})
|
|
assert resp.status_code == 200
|
|
saved = json.loads(open(zones).read())
|
|
assert saved["presets"]["default"]["count_line"]["y"] == 315
|
|
|
|
|
|
def test_post_zones_invalid_is_400_and_file_unchanged(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
preset = {
|
|
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
zones = _zones_file(tmp_path, preset)
|
|
before = open(zones).read()
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default", json={"preset": {"truck_area": [[1, 1], [1, 1], [1, 1]]}})
|
|
assert resp.status_code == 400
|
|
assert open(zones).read() == before
|
|
|
|
|
|
def test_post_zones_from_non_localhost_is_403(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10], [0, 10]]})
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default", json={"preset": {}},
|
|
environ_base={"REMOTE_ADDR": "10.1.2.3"})
|
|
assert resp.status_code == 403
|
|
|
|
|
|
def test_post_zones_reset_restores_the_default_preset(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10], [0, 10]],
|
|
"count_line": {"x_start": 1, "x_end": 2, "y": 3}})
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default/reset")
|
|
assert resp.status_code == 200
|
|
saved = json.loads(open(zones).read())
|
|
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
|
|
|
|
|
# --- fix round 1: route-level coverage for F1-F9 ---
|
|
|
|
def _route_preset(**overrides):
|
|
"""A valid preset in the native 1920x1080 zone space, with overrides applied."""
|
|
preset = {
|
|
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
|
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
|
"reference_resolution": [1920, 1080],
|
|
}
|
|
preset.update(overrides)
|
|
return preset
|
|
|
|
|
|
def test_post_zones_rejects_a_foreign_reference_resolution(client, tmp_path, monkeypatch):
|
|
"""F1: a foreign preset resolution is rejected when sent as a preset; the file must not change."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
before = open(zones).read()
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default",
|
|
json={"preset": _route_preset(reference_resolution=[640, 480])})
|
|
assert resp.status_code == 400
|
|
assert "reference_resolution" in resp.get_json()["error"]
|
|
assert open(zones).read() == before
|
|
|
|
|
|
def test_post_zones_rejects_a_non_finite_count_line(client, tmp_path, monkeypatch):
|
|
"""F2: Infinity used to reach int() and raise OverflowError (500)."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
body = ('{"preset": {"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],'
|
|
' "count_line": {"x_start": 577, "x_end": 1401, "y": Infinity}}}')
|
|
resp = client.post("/api/zones/default", data=body, content_type="application/json")
|
|
assert resp.status_code == 400
|
|
assert "count_line" in resp.get_json()["error"]
|
|
|
|
|
|
def test_post_zones_rejects_a_fractional_count_line(client, tmp_path, monkeypatch):
|
|
"""F3: bounds were checked on the truncated int, the raw float was stored."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default",
|
|
json={"preset": _route_preset(count_line={"x_start": 577, "x_end": 1920.9, "y": 330})})
|
|
assert resp.status_code == 400
|
|
assert "count_line" in resp.get_json()["error"]
|
|
|
|
|
|
def test_post_zones_stores_an_integral_float_count_line_as_an_int(client, tmp_path, monkeypatch):
|
|
"""F3: 1920.0 is an integer in disguise and must be persisted as 1920."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default",
|
|
json={"preset": _route_preset(count_line={"x_start": 577, "x_end": 1920.0, "y": 330})})
|
|
assert resp.status_code == 200
|
|
x_end = json.loads(open(zones).read())["presets"]["default"]["count_line"]["x_end"]
|
|
assert x_end == 1920
|
|
assert isinstance(x_end, int)
|
|
|
|
|
|
def test_post_zones_rejects_a_three_point_truck_area(client, tmp_path, monkeypatch):
|
|
"""F4: build_static_roi needs 4 points; 3 would degrade the job to dynamic."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default",
|
|
json={"preset": _route_preset(truck_area=[[600, 385], [609, 1076], [1404, 1078]])})
|
|
assert resp.status_code == 400
|
|
assert "truck_area" in resp.get_json()["error"]
|
|
|
|
|
|
def test_get_zone_detail_without_a_zones_file_is_404(client, tmp_path, monkeypatch):
|
|
"""F6: a missing file is a missing preset, not a server error."""
|
|
import app as app_module
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(tmp_path / "missing.json"))
|
|
resp = client.get("/api/zones/default")
|
|
assert resp.status_code == 404
|
|
assert "not found" in resp.get_json()["error"]
|
|
|
|
|
|
def test_get_zone_detail_with_a_corrupt_zones_file_is_500(client, tmp_path, monkeypatch):
|
|
"""F6: invalid JSON must answer with a message, not a traceback."""
|
|
import app as app_module
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text("{not json")
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
resp = client.get("/api/zones/default")
|
|
assert resp.status_code == 500
|
|
assert "not valid JSON" in resp.get_json()["error"]
|
|
assert "Traceback" not in resp.get_data(as_text=True)
|
|
|
|
|
|
def test_get_zone_detail_with_a_non_object_zones_file_is_500(client, tmp_path, monkeypatch):
|
|
"""F6: a JSON array is not a zone config."""
|
|
import app as app_module
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text("[1, 2, 3]")
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
resp = client.get("/api/zones/default")
|
|
assert resp.status_code == 500
|
|
assert "JSON object" in resp.get_json()["error"]
|
|
assert "Traceback" not in resp.get_data(as_text=True)
|
|
|
|
|
|
@pytest.mark.parametrize("route", ["/api/zones/default", "/api/zones/default/reset"])
|
|
@pytest.mark.parametrize("content,expect", [
|
|
("{not json", "not valid JSON"),
|
|
("[1, 2, 3]", "JSON object"),
|
|
])
|
|
def test_zone_write_routes_reject_an_unusable_zones_file(client, tmp_path, monkeypatch, route, content, expect):
|
|
"""F6: the write routes use the same guard as GET."""
|
|
import app as app_module
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(content)
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
resp = client.post(route, json={"preset": _route_preset()})
|
|
assert resp.status_code == 500
|
|
assert expect in resp.get_json()["error"]
|
|
assert "Traceback" not in resp.get_data(as_text=True)
|
|
|
|
|
|
def test_post_zones_with_a_malformed_body_is_400(client, tmp_path, monkeypatch):
|
|
"""F7: the message names the body, not a preset key."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default", data="{not json", content_type="application/json")
|
|
assert resp.status_code == 400
|
|
error = resp.get_json()["error"]
|
|
assert "body" in error.lower()
|
|
assert "truck_area" not in error
|
|
|
|
|
|
def test_post_zones_reset_drops_keys_that_are_not_in_the_default(client, tmp_path, monkeypatch):
|
|
"""F8: reset replaces the stored preset wholesale, siblings untouched."""
|
|
import app as app_module
|
|
zones = tmp_path / "zones.json"
|
|
with open(zones, "w") as f:
|
|
json.dump({"presets": {"default": {**_route_preset(), "custom_tuning": 7},
|
|
"other": _route_preset()},
|
|
"active_preset": "default"}, f)
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
resp = client.post("/api/zones/default/reset")
|
|
assert resp.status_code == 200
|
|
saved = json.loads(open(zones).read())
|
|
assert "custom_tuning" not in saved["presets"]["default"]
|
|
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
|
assert saved["presets"]["other"] == _route_preset()
|
|
assert saved["active_preset"] == "default"
|
|
|
|
|
|
def test_post_zones_from_ipv4_mapped_loopback_is_200(client, tmp_path, monkeypatch):
|
|
"""F9: ::ffff:127.0.0.1 is loopback when the server listens on IPv6."""
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default", json={"preset": _route_preset()},
|
|
environ_base={"REMOTE_ADDR": "::ffff:127.0.0.1"})
|
|
assert resp.status_code == 200
|
|
|
|
|
|
def test_post_zones_without_a_zones_file_is_404_and_creates_nothing(client, tmp_path, monkeypatch):
|
|
"""F6: the write routes refuse to create a missing zones.json."""
|
|
import app as app_module
|
|
missing = tmp_path / "missing.json"
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(missing))
|
|
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
|
|
assert resp.status_code == 404
|
|
assert not missing.exists()
|
|
|
|
|
|
def test_post_zones_reset_without_a_zones_file_is_404_and_creates_nothing(client, tmp_path, monkeypatch):
|
|
"""F6: reset refuses to create a missing zones.json either."""
|
|
import app as app_module
|
|
missing = tmp_path / "missing.json"
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(missing))
|
|
resp = client.post("/api/zones/default/reset")
|
|
assert resp.status_code == 404
|
|
assert not missing.exists()
|
|
|
|
|
|
# --- fix round 2: R1 reference_resolution, R2/R3 file handling, R4 mode ---
|
|
|
|
def test_post_zones_injects_the_analysis_space_when_the_key_is_absent(client, tmp_path, monkeypatch):
|
|
"""R1: a preset without reference_resolution defaults to native [1920, 1080] and scales cleanly."""
|
|
import app as app_module
|
|
from src.zone_config import build_static_roi
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
preset = {k: v for k, v in _route_preset().items() if k != "reference_resolution"}
|
|
# A new preset name: merging over a stored preset would keep the stored key.
|
|
resp = client.post("/api/zones/fresh", json={"preset": preset})
|
|
assert resp.status_code == 200
|
|
stored = json.loads(open(zones).read())["presets"]["fresh"]
|
|
assert stored["reference_resolution"] == [1920, 1080]
|
|
roi = build_static_roi(stored, 1280, 720)
|
|
assert (roi.x1, roi.x2) == (400, 936)
|
|
|
|
|
|
def test_post_zones_with_a_non_object_presets_is_400(client, tmp_path, monkeypatch):
|
|
"""R2: {"presets": []} used to raise TypeError inside the save."""
|
|
import app as app_module
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps({"presets": [], "active_preset": "default"}))
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
|
|
assert resp.status_code == 400
|
|
assert "presets" in resp.get_json()["error"]
|
|
assert "Traceback" not in resp.get_data(as_text=True)
|
|
assert json.loads(zones.read_text()) == {"presets": [], "active_preset": "default"}
|
|
|
|
|
|
def test_post_zones_reset_with_a_non_object_presets_is_400(client, tmp_path, monkeypatch):
|
|
"""R2: the reset route maps the same ValueError to 400."""
|
|
import app as app_module
|
|
zones = tmp_path / "zones.json"
|
|
zones.write_text(json.dumps({"presets": [], "active_preset": "default"}))
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", str(zones))
|
|
resp = client.post("/api/zones/default/reset")
|
|
assert resp.status_code == 400
|
|
assert "presets" in resp.get_json()["error"]
|
|
assert "Traceback" not in resp.get_data(as_text=True)
|
|
assert json.loads(zones.read_text()) == {"presets": [], "active_preset": "default"}
|
|
|
|
|
|
def test_post_zones_does_not_recreate_a_vanished_zones_file(client, tmp_path, monkeypatch):
|
|
"""R3: a file that vanishes between the check and the save is not recreated."""
|
|
import os
|
|
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
real_load = app_module.load_zone_config
|
|
|
|
def load_then_remove(path):
|
|
config = real_load(path)
|
|
os.remove(path)
|
|
return config
|
|
|
|
monkeypatch.setattr(app_module, "load_zone_config", load_then_remove)
|
|
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
|
|
assert resp.status_code == 404
|
|
assert "not found" in resp.get_json()["error"]
|
|
assert not os.path.exists(zones)
|
|
|
|
|
|
def test_post_zones_keeps_the_zones_file_mode(client, tmp_path, monkeypatch):
|
|
"""R4: mkstemp creates 0600; the file must not become owner-only."""
|
|
import os
|
|
|
|
import app as app_module
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
os.chmod(zones, 0o644)
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
resp = client.post("/api/zones/default", json={"preset": _route_preset()})
|
|
assert resp.status_code == 200
|
|
assert os.stat(zones).st_mode & 0o777 == 0o644
|
|
|
|
|
|
# --- Interactive zone editor (Task 5) ---
|
|
|
|
|
|
def test_calibrate_page_renders(client):
|
|
resp = client.get("/calibrate")
|
|
assert resp.status_code == 200
|
|
assert b"zoneOverlay" in resp.data
|
|
assert b"zone-json" in resp.data
|
|
|
|
|
|
def test_index_page_links_to_calibrator(client):
|
|
resp = client.get("/")
|
|
assert resp.status_code == 200
|
|
assert b'/calibrate' in resp.data
|
|
|
|
|
|
def test_api_frame_rejects_a_bad_filename(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
|
assert client.get("/api/frame?video=../etc/passwd").status_code == 400
|
|
assert client.get("/api/frame?video=missing.mp4").status_code == 404
|
|
|
|
|
|
def test_api_frame_returns_a_1280x720_jpeg(client, tmp_path, monkeypatch):
|
|
import cv2
|
|
import numpy as np
|
|
|
|
import app as app_module
|
|
|
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
|
path = tmp_path / "clip.mp4"
|
|
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10, (1920, 1080))
|
|
for _ in range(5):
|
|
writer.write(np.zeros((1080, 1920, 3), dtype=np.uint8))
|
|
writer.release()
|
|
|
|
resp = client.get("/api/frame?video=clip.mp4&t=0")
|
|
assert resp.status_code == 200
|
|
assert resp.mimetype == "image/jpeg"
|
|
img = cv2.imdecode(np.frombuffer(resp.data, dtype=np.uint8), cv2.IMREAD_COLOR)
|
|
assert img.shape[:2] == (720, 1280)
|
|
|
|
|
|
def _write_clip(path):
|
|
import cv2
|
|
import numpy as np
|
|
|
|
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10, (1920, 1080))
|
|
for _ in range(5):
|
|
writer.write(np.zeros((1080, 1920, 3), dtype=np.uint8))
|
|
writer.release()
|
|
|
|
|
|
def test_api_frame_rejects_an_unusable_time(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
|
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
|
_write_clip(tmp_path / "clip.mp4")
|
|
|
|
for bad in ("inf", "-inf", "nan", "1e999", "-1", "abc"):
|
|
resp = client.get(f"/api/frame?video=clip.mp4&t={bad}")
|
|
assert resp.status_code == 400, bad
|
|
assert resp.mimetype == "application/json"
|
|
assert resp.get_json() == {"error": "invalid t"}
|
|
|
|
|
|
def test_api_frame_error_does_not_leak_the_server_path(client, tmp_path, monkeypatch):
|
|
import app as app_module
|
|
|
|
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(tmp_path))
|
|
(tmp_path / "broken.mp4").write_bytes(b"not a video")
|
|
|
|
resp = client.get("/api/frame?video=broken.mp4&t=0")
|
|
assert resp.status_code == 500
|
|
assert resp.mimetype == "application/json"
|
|
message = resp.get_json()["error"]
|
|
assert str(tmp_path) not in message
|
|
assert "broken.mp4" in message
|
|
|
|
|
|
def test_extract_frame_jpeg_rejects_an_unusable_time(tmp_path):
|
|
from src.preview import extract_frame_jpeg
|
|
|
|
clip = tmp_path / "clip.mp4"
|
|
_write_clip(clip)
|
|
|
|
for bad in (float("inf"), float("-inf"), float("nan"), -1.0):
|
|
with pytest.raises(ValueError):
|
|
extract_frame_jpeg(str(clip), bad)
|
|
|
|
|
|
def test_open_cv_calibrator_merges_geometry_and_keeps_tuning_keys():
|
|
import importlib.util
|
|
from pathlib import Path
|
|
|
|
spec = importlib.util.spec_from_file_location(
|
|
"calibrate_zone",
|
|
Path(__file__).resolve().parents[1] / "tools" / "calibrate_zone.py",
|
|
)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
|
|
stored = {
|
|
"truck_area": [[1, 2], [3, 4], [5, 6], [7, 8]],
|
|
"counting_area": [[1, 2], [3, 4], [5, 6], [7, 8]],
|
|
"palet": [[9, 9], [8, 8], [7, 7], [6, 6]],
|
|
"count_line": {"x_start": 1, "x_end": 2, "y": 3},
|
|
"reference_resolution": [1280, 720],
|
|
"left_limit": 0.27578,
|
|
"min_valid_area": 15000,
|
|
}
|
|
config = {"active_preset": "default", "presets": {"default": dict(stored)}}
|
|
measured = {
|
|
"truck_area": [[10, 20], [30, 40], [50, 60], [70, 80]],
|
|
"counting_area": [[11, 21], [31, 41], [51, 61], [71, 81]],
|
|
"count_line": {"x_start": 100, "x_end": 200, "y": 150},
|
|
"reference_resolution": [1280, 720],
|
|
}
|
|
|
|
module.merge_preset(config, "default", measured)
|
|
|
|
preset = config["presets"]["default"]
|
|
# the measured geometry wins ...
|
|
assert preset["truck_area"] == measured["truck_area"]
|
|
assert preset["counting_area"] == measured["counting_area"]
|
|
assert preset["count_line"] == measured["count_line"]
|
|
assert preset["reference_resolution"] == [1280, 720]
|
|
# ... the tuning knobs survive
|
|
assert preset["palet"] == stored["palet"]
|
|
assert preset["left_limit"] == stored["left_limit"]
|
|
assert preset["min_valid_area"] == stored["min_valid_area"]
|
|
|
|
|
|
def test_post_zones_accepts_fcp_flat_1080p_json(client, tmp_path, monkeypatch):
|
|
"""POST /api/zones/<preset> accepts FCP's flat 1920x1080 zones.json format."""
|
|
import app as app_module
|
|
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
fcp_flat = {
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 215,
|
|
"line_x_start": 577,
|
|
"line_x_end": 1401,
|
|
}
|
|
resp = client.post("/api/zones/default", json=fcp_flat)
|
|
assert resp.status_code == 200
|
|
saved = json.loads(open(zones).read())["presets"]["default"]
|
|
assert saved["reference_resolution"] == [1920, 1080]
|
|
assert saved["truck_area"] == fcp_flat["truck"]
|
|
assert saved["counting_area"] == fcp_flat["counting"]
|
|
assert saved["palet"] == fcp_flat["palet"]
|
|
assert saved["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
|
|
|
|
|
def test_resolve_zone_auto_syncs_when_fcp_zones_updated(tmp_path, monkeypatch):
|
|
"""When FCP's zones.json is newer, app._resolve_zone refreshes preset 'default' first."""
|
|
import os
|
|
import app as app_module
|
|
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
fcp_zones = tmp_path / "fcp_zones.json"
|
|
fcp_zones.write_text(json.dumps({
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 215,
|
|
"line_x_start": 577,
|
|
"line_x_end": 1401,
|
|
}))
|
|
st = os.stat(zones)
|
|
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
monkeypatch.setenv("FCP_ZONES_PATH", str(fcp_zones))
|
|
|
|
mode, roi, preset, cpoly, tpoly = app_module._resolve_zone("fixed", "")
|
|
assert mode == "fixed"
|
|
assert preset == "default"
|
|
assert roi.line_y == 143
|
|
assert roi.line_x_start == 385
|
|
assert roi.line_x_end == 934
|
|
assert cpoly is not None and tpoly is not None
|
|
|
|
|
|
def test_cli_uses_zones_json_fixed_mode_by_default(tmp_path, monkeypatch):
|
|
"""CLI loads zones.json fixed areas by default (and auto-syncs FCP zones)."""
|
|
import os
|
|
import cli as cli_mod
|
|
from src.model_registry import ModelConfig
|
|
|
|
clip = tmp_path / "clip.mp4"
|
|
_write_clip(clip)
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
fcp_zones = tmp_path / "fcp_zones.json"
|
|
fcp_zones.write_text(json.dumps({
|
|
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
|
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
|
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
|
"line_y": 215,
|
|
"line_x_start": 577,
|
|
"line_x_end": 1401,
|
|
}))
|
|
st = os.stat(zones)
|
|
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
|
monkeypatch.setenv("FCP_ZONES_PATH", str(fcp_zones))
|
|
|
|
model_cfg = ModelConfig(
|
|
filename="best.pt", path=str(tmp_path / "best.pt"),
|
|
stem="best", known_classes=["sack"],
|
|
)
|
|
monkeypatch.setattr(cli_mod, "scan_models", lambda d: [model_cfg])
|
|
seen = {}
|
|
|
|
class _Res:
|
|
output_path = str(tmp_path / "out.mp4")
|
|
frame_count = 5
|
|
loading_count = 0
|
|
unloading_count = 0
|
|
net_count = 0
|
|
batch_count = 0
|
|
duration_seconds = 0.1
|
|
|
|
def fake_run_pipeline(**kwargs):
|
|
seen.update(kwargs)
|
|
return _Res()
|
|
|
|
monkeypatch.setattr(cli_mod, "run_pipeline", fake_run_pipeline)
|
|
|
|
cli_mod.main([
|
|
"--video", str(clip),
|
|
"--model", "best.pt",
|
|
"--zones-path", zones,
|
|
"--output", str(tmp_path / "out.mp4"),
|
|
])
|
|
assert seen["fixed_zone"] is not None
|
|
assert seen["fixed_zone"].line_y == 143
|
|
assert seen["fixed_zone"].line_x_start == 385
|
|
assert seen["counting_polygon"] is not None
|
|
assert seen["truck_polygon"] is not None
|
|
assert seen["freeze_roi"] is False
|
|
|
|
|
|
def test_post_zones_scales_legacy_720p_preset_to_1080p(client, tmp_path, monkeypatch):
|
|
"""POST /api/zones/<preset> accepts legacy [1280, 720] presets and stores [1920, 1080]."""
|
|
import app as app_module
|
|
|
|
zones = _zones_file(tmp_path, _route_preset())
|
|
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
|
legacy_preset = {
|
|
"truck_area": [[400, 194], [406, 718], [936, 718], [920, 194]],
|
|
"counting_area": [[382, 34], [390, 718], [946, 718], [932, 34]],
|
|
"count_line": {"x_start": 384, "x_end": 934, "y": 144},
|
|
"reference_resolution": [1280, 720],
|
|
}
|
|
resp = client.post("/api/zones/default", json={"preset": legacy_preset})
|
|
assert resp.status_code == 200
|
|
saved = json.loads(open(zones).read())["presets"]["default"]
|
|
assert saved["reference_resolution"] == [1920, 1080]
|
|
assert saved["count_line"] == {"x_start": 576, "x_end": 1401, "y": 216}
|