Files
feedmill-recounter/tests/test_job.py
T
jetson e963ba0cb4 feat: append source clip name to annotated output filename
Output was a fixed name (merged_annotated.mp4) so every download looked
the same. The source clip name is now appended at the back:
merged_annotated_rekap_2026-10-27.mp4

- src/naming.py: annotated_output_name() + source_stem(); client upload
  name wins, stored file name is the fallback (reuse endpoint), unsafe
  chars replaced, stem capped at 80 chars
- src/job.py: Job.source_stem + add_job(source_stem=...); both output
  paths go through the helper
- app.py: capture the sanitized client filename before the collision
  suffix is added
- cli.py: same helper for the CLI output name

Verified live on .93: POST /api/analyze with 'rekap 2026-10-27.mp4' ->
output/job-e0409b05/merged_annotated_rekap_2026-10-27.mp4, download 200.
2026-10-27 11:26:07 +07:00

486 lines
16 KiB
Python

# tests/test_job.py
"""Tests for job queue (src/job.py)."""
import pytest
from src.job import JobQueue, Job, JobStatus
def test_job_initial_status():
"""New job starts in PENDING status."""
job = Job(
job_id="test-1",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
assert job.status == JobStatus.PENDING
def test_job_has_latest_frame():
"""Job dataclass has latest_frame field defaulting to None."""
job = Job(
job_id="test-1",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
assert job.latest_frame is None
def test_job_latest_frame_settable():
"""Job.latest_frame can be set to bytes."""
job = Job(
job_id="test-1",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
job.latest_frame = b"\xff\xd8\xff\xe0"
assert job.latest_frame == b"\xff\xd8\xff\xe0"
def test_queue_add_job():
"""Adding a job returns the job with PENDING status."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
assert job.job_id.startswith("job-")
assert job.status in (JobStatus.PENDING, JobStatus.RUNNING, JobStatus.COMPLETED)
def test_queue_get_job():
"""get_job returns the job by ID."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
fetched = q.get_job(job.job_id)
assert fetched is not None
assert fetched.job_id == job.job_id
def test_queue_get_nonexistent():
"""get_job returns None for unknown ID."""
q = JobQueue(output_dir="/tmp/output")
assert q.get_job("nope") is None
def test_queue_list_jobs():
"""list_jobs returns all jobs."""
q = JobQueue(output_dir="/tmp/output")
q.add_job(video_path="/tmp/a.mp4", model_configs=[])
q.add_job(video_path="/tmp/b.mp4", model_configs=[])
jobs = q.list_jobs()
assert len(jobs) >= 2
def test_queue_cancel_pending():
"""Canceling a pending job sets status to CANCELLED."""
q = JobQueue(output_dir="/tmp/output")
# Add job without starting (simulate by adding then immediately canceling)
# Since add_job starts a thread, we test cancel on a job we control
job = q.add_job(video_path="/nonexistent.mp4", model_configs=[])
# Wait briefly for thread to start
import time
time.sleep(0.1)
assert q.cancel_job(job.job_id) in (True, False) # may have already started
def test_job_empty_config_completes():
"""add_job with [] model_configs completes with COMPLETED + empty results."""
import time
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
deadline = time.time() + 5.0
while time.time() < deadline:
fetched = q.get_job(job.job_id)
if fetched is not None and fetched.status == JobStatus.COMPLETED:
break
time.sleep(0.05)
fetched = q.get_job(job.job_id)
assert fetched is not None
assert fetched.status == JobStatus.COMPLETED
assert fetched.results == []
def test_queue_status_counts():
"""status_counts returns correct tally."""
q = JobQueue(output_dir="/tmp/output")
j1 = q.add_job(video_path="/nonexistent1.mp4", model_configs=[])
j2 = q.add_job(video_path="/nonexistent2.mp4", model_configs=[])
import time
time.sleep(0.5) # let them fail quickly
counts = q.status_counts()
assert isinstance(counts, dict)
# At least some count should be populated
assert sum(counts.values()) >= 2
# ── Box count propagation to JobResult (Task 2) ─────────────────────────
def test_job_result_box_fields_default_zero():
"""JobResult has box fields defaulting to 0."""
from src.job import JobResult
r = 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,
)
assert (r.box_loading_count, r.box_unloading_count, r.box_net_count) == (0, 0, 0)
def test_job_result_box_fields_accept_values():
from src.job import JobResult
r = 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,
)
assert (r.box_loading_count, r.box_unloading_count, r.box_net_count) == (4, 1, 3)
def test_run_job_single_model_propagates_box_counts(tmp_path, monkeypatch):
"""_run_job single-model branch copies box counts from PipelineResult."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
fake = PipelineResult(
output_path=str(tmp_path / "out.mp4"),
frame_count=10,
loading_count=5,
unloading_count=2,
batch_count=1,
duration_seconds=1.0,
model_name="a.pt",
class_filter=None,
box_loading_count=4,
box_unloading_count=1,
)
monkeypatch.setattr(job_mod, "run_pipeline", lambda **kwargs: fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-t2-single",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "box", "truck"])
],
output_dir=str(tmp_path / "job-t2-single"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
r = job.results[0]
assert r.loading_count == 5
assert r.box_loading_count == 4
assert r.box_unloading_count == 1
assert r.box_net_count == 3
def test_run_job_merged_propagates_box_counts(tmp_path, monkeypatch):
"""_run_job merged branch copies box counts from MergedPipelineResult."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult
fake = MergedPipelineResult(
output_path=str(tmp_path / "merged.mp4"),
frame_count=10,
loading_count=9,
unloading_count=4,
batch_count=2,
duration_seconds=2.0,
model_names=["a.pt", "b.pt"],
class_filter=None,
box_loading_count=6,
box_unloading_count=2,
)
monkeypatch.setattr(job_mod, "run_merged_pipeline", lambda **kwargs: fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-t2-merged",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "box", "truck"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack", "box"]),
],
output_dir=str(tmp_path / "job-t2-merged"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
r = job.results[0]
assert r.box_loading_count == 6
assert r.box_unloading_count == 2
assert r.box_net_count == 4
# ── output_max_height plumbing ──────────────────────────────────────────
def test_job_output_max_height_default_none():
"""Job.output_max_height defaults to None."""
job = Job(
job_id="test-oh",
video_path="/tmp/test.mp4",
model_configs=[],
output_dir="/tmp/output",
)
assert job.output_max_height is None
def test_queue_add_job_output_max_height():
"""add_job passes output_max_height through to the Job."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[],
output_max_height=720)
assert job.output_max_height == 720
def test_queue_add_job_output_max_height_default():
"""add_job without output_max_height keeps None."""
q = JobQueue(output_dir="/tmp/output")
job = q.add_job(video_path="/tmp/test.mp4", model_configs=[])
assert job.output_max_height is None
def _fake_single_job(tmp_path, output_max_height, monkeypatch):
import src.job as job_mod
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
seen = {}
def fake_run_pipeline(**kwargs):
seen.update(kwargs)
return PipelineResult(
output_path=str(tmp_path / "out.mp4"),
frame_count=10,
loading_count=1,
unloading_count=0,
batch_count=1,
duration_seconds=1.0,
model_name="a.pt",
class_filter=None,
)
monkeypatch.setattr(job_mod, "run_pipeline", fake_run_pipeline)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-oh-single",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "truck"])
],
output_dir=str(tmp_path / "job-oh-single"),
output_max_height=output_max_height,
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
return job, seen
def test_run_job_single_passes_output_max_height(tmp_path, monkeypatch):
"""_run_job single branch forwards output_max_height=720 to run_pipeline."""
job, seen = _fake_single_job(tmp_path, 720, monkeypatch)
assert job.status == JobStatus.COMPLETED
assert seen.get("output_max_height") == 720
def test_run_job_single_output_max_height_none(tmp_path, monkeypatch):
"""_run_job single branch forwards output_max_height=None."""
job, seen = _fake_single_job(tmp_path, None, monkeypatch)
assert job.status == JobStatus.COMPLETED
assert seen.get("output_max_height") is None
def test_run_job_merged_passes_output_max_height(tmp_path, monkeypatch):
"""_run_job merged branch forwards output_max_height to run_merged_pipeline."""
import src.job as job_mod
from src.job import Job, JobQueue, JobStatus
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult
seen = {}
def fake_run_merged(**kwargs):
seen.update(kwargs)
return MergedPipelineResult(
output_path=str(tmp_path / "merged.mp4"),
frame_count=10,
loading_count=3,
unloading_count=1,
batch_count=1,
duration_seconds=1.0,
model_names=["a.pt", "b.pt"],
class_filter=None,
)
monkeypatch.setattr(job_mod, "run_merged_pipeline", fake_run_merged)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-oh-merged",
video_path="/tmp/test.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack", "truck"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack"]),
],
output_dir=str(tmp_path / "job-oh-merged"),
output_max_height=720,
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert job.status == JobStatus.COMPLETED
assert seen.get("output_max_height") == 720
# ── Orphan registration (jobs lost across restart) ────────────────────
def test_orphan_output_dirs_registered_on_init(tmp_path):
"""Stale output/job-* dirs re-attach as COMPLETED jobs so UI can delete them."""
import os
import time as _time
stale = tmp_path / "job-abcd1234"
stale.mkdir()
(stale / "merged_annotated.mp4").write_bytes(b"video")
old = _time.time() - 3600
os.utime(stale, (old, old))
q = JobQueue(output_dir=str(tmp_path))
job = q.get_job("job-abcd1234")
assert job is not None
assert job.status == JobStatus.COMPLETED
assert job.output_dir == str(stale)
# And the normal delete flow frees the storage
assert q.delete_job("job-abcd1234") is True
assert not stale.exists()
def test_fresh_output_dir_skipped(tmp_path):
"""Dirs younger than the grace window may belong to a live job — not registered."""
fresh = tmp_path / "job-99999999"
fresh.mkdir() # mtime = now
q = JobQueue(output_dir=str(tmp_path))
assert q.get_job("job-99999999") is None
assert fresh.exists()
def test_orphan_registration_off(tmp_path):
"""register_orphans=False leaves disk state alone (used by tests/tools)."""
import os
import time as _time
stale = tmp_path / "job-abcd1234"
stale.mkdir()
old = _time.time() - 3600
os.utime(stale, (old, old))
q = JobQueue(output_dir=str(tmp_path), register_orphans=False)
assert q.get_job("job-abcd1234") is None
# ── Output naming (source clip name appended) ─────────────────────────
def test_single_model_output_name_uses_source_stem(tmp_path, monkeypatch):
"""Annotated file name carries the source clip name."""
import os
import src.job as job_mod
from src.job import Job, JobQueue
from src.model_registry import ModelConfig
from src.pipeline import PipelineResult
seen = {}
def fake(**kwargs):
seen.update(kwargs)
return PipelineResult(
output_path=kwargs["output_path"], frame_count=10, loading_count=0,
unloading_count=0, batch_count=0, duration_seconds=1.0,
model_name="a.pt", class_filter=None,
)
monkeypatch.setattr(job_mod, "run_pipeline", fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-nm-single",
video_path="/tmp/clip_1.mp4",
model_configs=[ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"),
stem="a", known_classes=["sack"])],
output_dir=str(tmp_path / "job-nm-single"),
source_stem="clip",
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert os.path.basename(seen["output_path"]) == "a_annotated_clip.mp4"
def test_merged_output_name_falls_back_to_stored_file_name(tmp_path, monkeypatch):
"""Without a client name the stored file name is used."""
import os
import src.job as job_mod
from src.job import Job, JobQueue
from src.model_registry import ModelConfig
from src.pipeline import MergedPipelineResult
seen = {}
def fake(**kwargs):
seen.update(kwargs)
return MergedPipelineResult(
output_path=kwargs["output_path"], frame_count=10, loading_count=0,
unloading_count=0, batch_count=0, duration_seconds=1.0,
model_names=["a.pt"], class_filter=None,
)
monkeypatch.setattr(job_mod, "run_merged_pipeline", fake)
q = JobQueue(output_dir=str(tmp_path))
job = Job(
job_id="job-nm-merged",
video_path="/tmp/clip_1.mp4",
model_configs=[
ModelConfig(filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
known_classes=["sack"]),
ModelConfig(filename="b.pt", path=str(tmp_path / "b.pt"), stem="b",
known_classes=["sack"]),
],
output_dir=str(tmp_path / "job-nm-merged"),
)
q._jobs[job.job_id] = job
q._run_job(job.job_id)
assert os.path.basename(seen["output_path"]) == "merged_annotated_clip_1.mp4"