Files

198 lines
7.0 KiB
Python

"""Tests for src/config.py — root config.yaml loader."""
from __future__ import annotations
import inspect
import os
import yaml
import pytest
from src.config import CONFIG_PATH, DEFAULTS, get, load_config
from src.validation import ValidationError
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _section_keys(cfg: dict) -> dict[str, list[str]]:
return {k: sorted(v) for k, v in cfg.items()}
def test_missing_file_returns_defaults(monkeypatch, tmp_path):
"""Nonexistent CONFIG_PATH -> full default structure."""
monkeypatch.setattr("src.config.CONFIG_PATH", str(tmp_path / "nope.yaml"))
cfg = load_config()
assert cfg == DEFAULTS
assert _section_keys(cfg) == _section_keys(DEFAULTS)
def test_partial_yaml_deep_merges(tmp_path):
"""Only-specified keys override; everything else stays default."""
p = tmp_path / "config.yaml"
p.write_text("detection:\n sack_conf: 0.9\n", encoding="utf-8")
cfg = load_config(str(p))
assert cfg["detection"]["sack_conf"] == 0.9
# untouched keys keep defaults
assert cfg["detection"]["truck_conf"] == DEFAULTS["detection"]["truck_conf"]
assert cfg["iou"] == DEFAULTS["iou"]
assert cfg["roi"] == DEFAULTS["roi"]
assert cfg["stabilizer"] == DEFAULTS["stabilizer"]
assert cfg["pipeline"] == DEFAULTS["pipeline"]
# structure identical to defaults
assert _section_keys(cfg) == _section_keys(DEFAULTS)
def test_empty_file_returns_defaults(tmp_path):
p = tmp_path / "empty.yaml"
p.write_text("", encoding="utf-8")
assert load_config(str(p)) == DEFAULTS
def test_load_config_raises_on_broken_yaml(tmp_path):
bad = tmp_path / "config.yaml"
bad.write_text("detection: [unclosed\n")
with pytest.raises(Exception):
load_config(str(bad))
def test_load_config_raises_on_non_mapping_yaml(tmp_path):
bad = tmp_path / "config.yaml"
bad.write_text("- detection\n- iou\n", encoding="utf-8")
with pytest.raises(ValidationError):
load_config(str(bad))
def test_load_config_raises_on_invalid_value(tmp_path):
bad = tmp_path / "config.yaml"
bad.write_text("detection:\n sack_conf: 1.5\n", encoding="utf-8")
with pytest.raises(ValidationError):
load_config(str(bad))
def test_partial_yaml_only_box_conf_merges(tmp_path):
"""Only detection.box_conf overrides; sack_conf stays at default 0.35."""
p = tmp_path / "config.yaml"
p.write_text("detection:\n box_conf: 0.25\n", encoding="utf-8")
cfg = load_config(str(p))
assert cfg["detection"]["box_conf"] == 0.25
assert cfg["detection"]["sack_conf"] == 0.35
assert cfg["min_bbox_area"] == DEFAULTS["min_bbox_area"]
assert _section_keys(cfg) == _section_keys(DEFAULTS)
def test_repo_config_yaml_exists_and_parses():
"""Real repo config.yaml exists, parses, types sane."""
real = os.path.join(REPO_ROOT, "config.yaml")
assert os.path.isfile(real), "config.yaml missing at repo root"
cfg = load_config(real)
assert isinstance(cfg["detection"]["sack_conf"], float)
assert isinstance(cfg["detection"]["box_conf"], float)
assert isinstance(cfg["detection"]["truck_conf"], float)
# Platform-aligned detection tuning (matches karung_counter_semarang)
assert cfg["detection"]["box_conf"] == 0.35
assert cfg["detection"]["truck_conf"] == 0.45
assert cfg["iou"]["suppress_sack_box"] == 0.4
assert cfg["min_bbox_area"]["sack"] == 1500
assert cfg["min_bbox_area"]["box"] == 1000
assert cfg["min_bbox_area"]["truck"] == 5000
for key in ("detect_interval", "sup_det_interval", "truck_det_interval", "preview_every_n"):
assert isinstance(cfg["pipeline"][key], int), key
assert cfg["pipeline"][key] > 0, key
assert isinstance(cfg["stabilizer"]["max_hold"], int)
assert cfg["stabilizer"]["max_hold"] > 0
# file actually contains every default section
with open(real, encoding="utf-8") as f:
raw = yaml.safe_load(f)
assert set(raw) == set(DEFAULTS)
def test_defaults_match_the_shipped_config_yaml():
"""DEFAULTS mirror config.yaml — a checkout without config.yaml behaves the same.
Drift here means a missing config.yaml silently counts with different
thresholds than the shipped one.
"""
real = os.path.join(REPO_ROOT, "config.yaml")
assert load_config(real) == DEFAULTS
def test_defaults_are_valid():
"""The built-in defaults pass the same validation as a real config."""
from src.validation import validate_config
validate_config(DEFAULTS)
def test_get_accessor():
# DEFAULTS now mirrors the shipped config.yaml, so the accessor must
# return the same value from either source.
assert get("detection", "sack_conf") == DEFAULTS["detection"]["sack_conf"]
def test_config_path_points_at_repo_root():
assert os.path.dirname(CONFIG_PATH) == REPO_ROOT
assert os.path.basename(CONFIG_PATH) == "config.yaml"
# ── pipeline runner signature contracts ───────────────────────────────
def test_pipeline_runner_params_default_to_none():
"""sack_conf/truck_conf/detect_interval/preview_every_n default None."""
from src import pipeline as pipe_mod
for fn_name in ("run_pipeline", "run_merged_pipeline"):
sig = inspect.signature(getattr(pipe_mod, fn_name))
assert sig.parameters["sack_conf"].default is None, fn_name
assert sig.parameters["truck_conf"].default is None, fn_name
assert sig.parameters["detect_interval"].default is None, fn_name
assert sig.parameters["preview_every_n"].default is None, fn_name
assert sig.parameters["truck_det_interval"].default is None, fn_name
assert sig.parameters["output_max_height"].default is None, fn_name
def test_truck_roi_tracker_accepts_sticky_iou():
from src.truck_roi import TruckROITracker
t = TruckROITracker(frame_width=100, frame_height=100, sticky_iou=0.5)
assert t._sticky_iou == 0.5
# ── FCP parity (karung_counter_semarang) ───────────────────────────────
def test_detection_thresholds_match_fcp():
cfg = load_config()
assert cfg["detection"]["sack_conf"] == 0.35
assert cfg["detection"]["box_conf"] == 0.35
assert cfg["detection"]["truck_conf"] == 0.45
assert cfg["iou"]["sack_nms"] == 0.45
assert cfg["iou"]["box_nms"] == 0.7
assert cfg["min_bbox_area"]["sack"] == 1500
assert cfg["min_bbox_area"]["box"] == 1000
assert cfg["min_bbox_area"]["truck"] == 5000
def test_stabilizer_hold_matches_fcp():
cfg = load_config()
assert cfg["stabilizer"]["ema_alpha"] == 0.35
assert cfg["stabilizer"]["max_hold"] == 10
def test_truck_det_interval_matches_fcp():
assert load_config()["pipeline"]["truck_det_interval"] == 5
def test_batch_section_matches_fcp():
"""The batch FSM arguments come from the config (FCP config.yaml:123-124)."""
cfg = load_config()
assert cfg["batch"]["timeout_seconds"] == 20.0
assert cfg["batch"]["truck_gone_tolerance_seconds"] == 30.0
assert DEFAULTS["batch"] == cfg["batch"]