move_detect/tests/test_config.py
유창욱 2ea0420de7 fix(delivery): resolve codex + workflow review findings across edge/cloud/deploy
Two independent adversarial reviews (codex CLI + a 6-dimension verification
workflow) of the delivery-hardening branch surfaced ~40 findings; this closes
the confirmed correctness/security/deploy blockers plus a codex re-review pass.

edge:
- geometry: track_displacement per-second threshold recalibrated (0.02->0.25,
  env-tunable via MOTION_THR, validated finite/positive); confidence-filter
  keypoints with a bbox-center fallback so hallucinated points don't fake motion
- fall: low-confidence frames no longer cancel an active FALLING/FALLEN incident
  (freeze + reset recovery timer so recovery needs a fresh confident streak);
  baseline height only seeded from trusted frames
- queue: PostClient.send() returns a tri-state SendResult; only definite 4xx
  count toward the poison drop cap, so a network outage (incl. 408/425/429/5xx)
  never deletes queued safety events; legacy rows persist their minted uuid
- config: reject placeholder / http / short DEVICE_SECRET at startup
- zones: warn+skip legacy pixel-space polygons that would silently match nothing

cloud:
- zone endpoints wired into P3-2b site-scope (cross-site read/write/delete
  closed) + role gate on list; catch narrowed so DB faults surface as 500
- snapshot purge keeps the DB row when unlink() fails (no untrackable PIPA orphan)
- ingest dedup path re-stores missing snapshots (+ short-write guard); UNIQUE
  (event_id, content_hash) makes recovery idempotent under retry/race
- event list cursor carries full-precision occurred_at (no float rounding at the
  page boundary); string keyset end-to-end
- SiteScope '' fails closed (only NULL is global); dashboard fetches full page cap
- runnable migration (site/event_uuid + backfill ordering + indexes); rate-limit
  reap fails open

deploy:
- offline bundle hashes EVERY file (fatal on missing/failed/injected; models in
  SBOM; arch in tarball name; REQUIRE_SIGNATURE option)
- installer verifies before any mutation, Hailo arch preflight before install,
  atomic src swap, backend reconcile preserves a working operator choice
- systemd DeviceAllow=char-dma_heap (the /dev/dma_heap/ dir form was inert)

Verified: edge pytest 165 passed / 2 skipped; cloud phpunit 109 passed / 4
skipped; deploy scripts bash -n clean. Reviewed by codex twice (findings +
fixes) with the second-pass findings folded in.
2026-07-17 19:24:42 +09:00

101 lines
4.8 KiB
Python

import pytest
from edge.config import (frame_interval_from_env, load_config, queue_db_path,
require_upload_config)
def test_defaults_when_env_empty():
cfg = load_config({})
assert cfg.device_id == "pi-unknown"
assert cfg.fall.prone_confirm_s == 3.0
assert cfg.fall.no_motion_s == 10.0
assert cfg.camera_id == "cam-01"
assert cfg.cafe24_url == ""
assert cfg.secret == ""
assert cfg.ghost.reappear_s == 10.0
assert cfg.zone.debounce_s == 0.75
assert cfg.engine.cooldown_s == 30.0
def test_env_overrides():
env = {
"DEVICE_ID": "pi-w1", "CAMERA_ID": "cam-9",
"CAFE24_URL": "https://x/api/events", "DEVICE_SECRET": "s",
"FALL_PRONE_S": "2.0", "FALL_NO_MOTION_S": "8",
"IMMOBILE_S": "90", "COOLDOWN_S": "45",
"GHOST_REAPPEAR_S": "7", "ZONE_DEBOUNCE_S": "1.5",
}
cfg = load_config(env)
assert cfg.device_id == "pi-w1"
assert cfg.camera_id == "cam-9"
assert cfg.fall.prone_confirm_s == 2.0
assert cfg.fall.no_motion_s == 8.0
assert cfg.immobility.immobile_s == 90.0
assert cfg.engine.cooldown_s == 45.0
assert cfg.engine.camera_id == "cam-9"
assert cfg.ghost.reappear_s == 7.0
assert cfg.zone.debounce_s == 1.5
def test_require_upload_config_rejects_blank_url_and_secret():
# A blank CAFE24_URL or DEVICE_SECRET must fail LOUD at startup. Left silent, the daemon
# runs green while every upload fails (bad URL -> requests error, caught) and the offline
# queue grows until the SD card is full.
with pytest.raises(ValueError, match="CAFE24_URL"):
require_upload_config(load_config({"DEVICE_SECRET": "s"}))
with pytest.raises(ValueError, match="DEVICE_SECRET"):
require_upload_config(load_config({"CAFE24_URL": "https://x/move_detect"}))
# Whitespace-only is still blank.
with pytest.raises(ValueError):
require_upload_config(load_config({"CAFE24_URL": " ", "DEVICE_SECRET": " "}))
def test_require_upload_config_passes_when_both_present():
# A real per-device secret is a long HMAC-derived hex string, on an https URL.
cfg = load_config({"CAFE24_URL": "https://x/move_detect",
"DEVICE_SECRET": "0123456789abcdef0123"})
require_upload_config(cfg) # must not raise
def test_require_upload_config_rejects_placeholder_and_http():
# Non-empty ship-time placeholders pass a blank check but are never a real value; a unit left
# at one uploads nothing while looking healthy. http would leak worker snapshots in plaintext.
with pytest.raises(ValueError, match="DEVICE_SECRET"):
require_upload_config(load_config({"CAFE24_URL": "https://x/move_detect",
"DEVICE_SECRET": "CHANGEME"}))
with pytest.raises(ValueError, match="CAFE24_URL"):
require_upload_config(load_config({"CAFE24_URL": "https://your-domain.example/move_detect",
"DEVICE_SECRET": "0123456789abcdef0123"}))
with pytest.raises(ValueError, match="https"):
require_upload_config(load_config({"CAFE24_URL": "http://x/move_detect",
"DEVICE_SECRET": "0123456789abcdef0123"}))
with pytest.raises(ValueError, match="too short"):
require_upload_config(load_config({"CAFE24_URL": "https://x/move_detect",
"DEVICE_SECRET": "short"}))
def test_load_config_rejects_non_finite_or_nonpositive_motion_thr():
# A 0 / NaN / inf MOTION_THR would make every track read as "still" -> constant no_motion.
for bad in ("0", "-1", "nan", "inf"):
with pytest.raises(ValueError, match="MOTION_THR"):
load_config({"MOTION_THR": bad})
# A sane value flows through to both detectors.
cfg = load_config({"MOTION_THR": "0.3"})
assert cfg.fall.motion_thr == 0.3 and cfg.immobility.motion_thr == 0.3
def test_frame_interval_defaults_and_validates():
assert frame_interval_from_env({}) == pytest.approx(1 / 12)
assert frame_interval_from_env({"TARGET_FPS": "24"}) == pytest.approx(1 / 24)
# TARGET_FPS=0 -> ZeroDivisionError today -> infinite systemd crash loop; must be rejected.
with pytest.raises(ValueError):
frame_interval_from_env({"TARGET_FPS": "0"})
with pytest.raises(ValueError):
frame_interval_from_env({"TARGET_FPS": "12fps"})
with pytest.raises(ValueError):
frame_interval_from_env({"TARGET_FPS": "-5"})
def test_queue_db_path_defaults_absolute_under_state_dir():
# A relative 'queue.db' is unwritable under the hardened unit (ProtectSystem=strict,
# WorkingDirectory read-only) -> crash loop. Default to the writable StateDirectory.
assert queue_db_path({}) == "/var/lib/move-detect/queue.db"
assert queue_db_path({"QUEUE_DB": "/custom/q.db"}) == "/custom/q.db"