move_detect/tests/test_uvc_source.py
유창욱 9386dfc580 feat(delivery): install-path fixes + cafe24 package + delivery-audit hardening
Three intertwined bodies of work developed and tested together this session.
Full test suite green: python (edge) + phpunit (cloud).

## Edge/Pi install path
- setup_online.sh: apt-lock retry (apt-daily contention), Type=exec unit +
  StartLimitIntervalSec in [Unit], journalctl-on-failure, crash-loop detection.
- onnxruntime is now best-effort (no sdist / no 32-bit-ARM wheel); [6/8] probes the
  real backend and hard-fails if none works.
- Hailo HEF auto-fetch: edge/tools/fetch_hailo_hef.py (pinned sha256, refuses to guess
  8 vs 8L, HAILO_ARCH override for serial-less boards); hailo_pose.py run() timeout fix.
- install_offline.sh: mirrors the backend gate; onnxruntime optional.

## Cafe24 cloud package (cloud/deploy/)
- build_cafe24_package.sh emits move_detect_app/ (private, one folder) + www/move_detect/
  (docroot subdir); no-dev classmap autoloader; preflight.php; hardened .htaccess.
- Subdirectory mount support: Request::baseFrom/pathFor strip the mount prefix; index.php
  walks up to find the app root; views/JS prefix every URL with APP_BASE; session cookie
  scoped to the mount.

## Delivery audit — silent-failure & correctness (docs/delivery-audit.md)
All 4 blockers + all Phase-1 silent-failure + Phase-2 HIGH correctness:
- Edge cloud clients send a custom User-Agent (cafe24 WAF blocks python-requests) and
  allow_redirects=False.
- Daemon fails loud on blank CAFE24_URL/DEVICE_SECRET; run_loop logs swallowed exceptions;
  heartbeat carries real fps + per-camera health; UvcSource reopens a dead camera;
  offline queue is size-capped and drops poison rows; TARGET_FPS/QUEUE_DB validated.
- Zone coordinates normalized 0..1 on both sides (were canvas-px vs camera-px — every zone
  misplaced); pinch zones emit PINCH/HIGH (were downgraded to WARNING).
- Fall detection uses bbox cues when keypoints are low-confidence (occluded fallen person);
  ghost incident not cancelled by a bystander; displacement normalized per-second (FPS-invariant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Xmn8KZWqiQUguEMRtn6rW
2026-07-17 09:07:33 +09:00

74 lines
2.5 KiB
Python

"""UvcSource must fail LOUD when a camera won't open, and try to REOPEN a camera that goes
dead mid-run — a USB cam on a 24/7 Pi browns out / gets unplugged, and today read() would
return (False, None) forever while the daemon looks perfectly healthy.
No hardware: a fake capture is injected via the `_open` factory."""
import pytest
from edge.adapters.uvc_source import UvcSource
class _FakeCap:
def __init__(self, frames, opened=True):
# frames: list of (ok, frame) tuples served in order; exhausted -> (False, None)
self._frames = list(frames)
self._opened = opened
self.released = 0
self.sets = 0
def isOpened(self):
return self._opened
def read(self):
return self._frames.pop(0) if self._frames else (False, None)
def set(self, *a):
self.sets += 1
def release(self):
self.released += 1
def test_open_failure_raises_loudly():
# A device that never opens must raise at construction so build_runtimes logs+skips it,
# not silently construct a dead capture.
with pytest.raises(RuntimeError, match="failed to open"):
UvcSource(0, mjpeg=False, _open=lambda dev: _FakeCap([], opened=False))
def test_read_proxies_a_live_frame():
cap = _FakeCap([(True, "frameA")])
src = UvcSource(0, mjpeg=False, _open=lambda dev: cap)
assert src.read() == (True, "frameA")
def test_dead_camera_is_reopened_after_a_threshold():
opens = []
def opener(dev):
cap = _FakeCap([], opened=True) # opens fine but delivers no frames
opens.append(cap)
return cap
src = UvcSource(0, mjpeg=False, reopen_after=3, _open=opener)
assert len(opens) == 1
for _ in range(3): # 3 consecutive dead reads -> exactly one reopen
assert src.read() == (False, None)
assert len(opens) == 2, "camera should be reopened after reopen_after failures"
assert opens[0].released == 1, "the dead capture should be released before reopening"
def test_recovery_resets_the_failure_streak():
# F, F, live, F, F with reopen_after=3 never has 3-in-a-row, so no reopen must fire.
cap = _FakeCap([(False, None), (False, None), (True, "ok"), (False, None), (False, None)])
opens = {"n": 0}
def opener(dev):
opens["n"] += 1
return cap
src = UvcSource(0, mjpeg=False, reopen_after=3, _open=opener)
assert opens["n"] == 1 # initial open only
for _ in range(5):
src.read()
assert opens["n"] == 1, "a recovered read must reset the streak so no reopen fires"