"""StereoConfig 校验与 JSON 加载测试(规格 §9:配置外置、fail-fast)。""" import json from pathlib import Path import pytest from stereo_ranger import StereoConfig, load_from_json CONFIG_PATH = Path(__file__).resolve().parents[2] / "config" / "stereo_ranger.json" def _config_dict() -> dict: return json.loads(CONFIG_PATH.read_text(encoding="utf-8")) def _write(tmp_path: Path, data: dict) -> str: path = tmp_path / "stereo.json" path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") return str(path) def test_defaults_are_valid_and_domains_are_consistent(): cfg = StereoConfig() assert cfg.focal_baseline_px_m == pytest.approx(cfg.fx_px * cfg.baseline_m) assert cfg.z_min_m == pytest.approx(cfg.focal_baseline_px_m / cfg.disparity_max_px) assert cfg.z_max_m == pytest.approx(cfg.focal_baseline_px_m / cfg.disparity_min_px) assert cfg.z_error_budget_max_m == pytest.approx((cfg.max_delta_z_m * cfg.focal_baseline_px_m) ** 0.5) def test_load_from_json_matches_defaults(): assert load_from_json(str(CONFIG_PATH)) == StereoConfig() def test_missing_field_rejected(tmp_path): data = _config_dict() data.pop("baseline_m") with pytest.raises(ValueError, match="缺少配置字段"): load_from_json(_write(tmp_path, data)) def test_unknown_field_rejected(tmp_path): data = _config_dict() data["radar_fallback"] = True with pytest.raises(ValueError, match="未知配置字段"): load_from_json(_write(tmp_path, data)) @pytest.mark.parametrize( "field,value", [ ("fx_px", "960"), ("consistency_N_frames", 3.5), ("smooth_alpha", True), ], ) def test_type_error_rejected(tmp_path, field, value): data = _config_dict() data[field] = value with pytest.raises(ValueError, match="配置类型非法"): load_from_json(_write(tmp_path, data)) @pytest.mark.parametrize( "field,value", [ ("fx_px", 0.0), ("fy_px", -1.0), ("cx_px", -0.5), ("cy_px", -0.5), ("baseline_m", 0.0), ("tau_y_px", 0.0), ("tau_h_ratio", 0.0), ("disparity_min_px", 0.0), ("disparity_min_px", 60.0), ("max_delta_z_m", 0.0), ("consistency_N_frames", 0), ("consistency_M_frames", 2), ("consistency_jump_px", 0.0), ("smooth_alpha", 0.0), ("smooth_alpha", 1.5), ("jump_reset_m", 0.0), ("filter_reset_frames", 0), ("isolation_gate_px", 0.0), ], ) def test_invalid_values_rejected(field, value): with pytest.raises(ValueError, match="配置非法"): StereoConfig(**{field: value}) def test_boundary_values_accepted(): cfg = StereoConfig(disparity_min_px=3.0, disparity_max_px=3.0 + 1e-9, smooth_alpha=1.0, consistency_M_frames=3) assert cfg.z_max_m > cfg.z_min_m