diff --git a/.github/workflows/docker-compose.yaml b/.github/workflows/docker-compose.yaml index 51f280a..64bfdd0 100644 --- a/.github/workflows/docker-compose.yaml +++ b/.github/workflows/docker-compose.yaml @@ -47,7 +47,7 @@ jobs: run: pip install -r tests/requirements.txt - name: launch tests - run: pytest tests/* + run: pytest tests --ignore=tests/e2e - name: Capture logs if: always() diff --git a/.gitignore b/.gitignore index 7cae47b..04b0484 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,10 @@ data/images/ data/models/ # Written by init_script at the end of a successful run data/.init_done +# Touched by the engine container (./data is mounted) +data/heartbeat +# Written by make e2e +e2e-artifacts/ *.pem # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/Makefile b/Makefile index e45d68a..7023777 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,7 @@ help: @echo " build Build local images in this repo" @echo " build-external Build images in sibling repos" @echo " build-all Build local and external images" + @echo " build-e2e Build only the local images the e2e needs (no notebooks)" @echo " fetch-scenario Download scenario images (SCENARIO=smoke-then-clear)" @echo " run-backend Start base services only" @echo " run-camera Start only the fake cameras, to work on pyro-engine" @@ -21,7 +22,8 @@ help: @echo " stop Stop and remove all services and volumes" @echo " ps Show compose status" @echo " logs Follow logs" - @echo " test Run pytest" + @echo " test Run the unit tests" + @echo " e2e Fresh stack, then the end-to-end tests (SCENARIO=smoke-then-clear), artifacts in e2e-artifacts/" # ------------------------------------------------------------------- # Init @@ -40,6 +42,11 @@ build: fetch-scenario docker build -f containers/notebooks/Dockerfile -t pyronear/notebooks:latest containers/notebooks/ docker build --build-context scenarios=data/scenarios -f containers/fake_camera/Dockerfile -t pyronear/fake-camera:latest containers/fake_camera/ +# Same images as `build` minus notebooks, which the e2e does not run. +build-e2e: fetch-scenario + docker build -f containers/init_script/Dockerfile -t pyronear/pyro-api-init:latest containers/init_script/ + docker build --build-context scenarios=data/scenarios -f containers/fake_camera/Dockerfile -t pyronear/fake-camera:latest containers/fake_camera/ + # ------------------------------------------------------------------- # Build images from sibling repositories # ------------------------------------------------------------------- @@ -62,11 +69,12 @@ run-backend: # Fake camera scenarios: definitions are in data/scenarios//scenario.json, # images come from the "scenarios" GitHub release. SCENARIO ?= smoke-then-clear -SCENARIOS_URL = https://github.com/pyronear/pyro-envdev/releases/download/scenarios +export SCENARIO +SCENARIOS_URL ?= https://github.com/pyronear/pyro-envdev/releases/download/scenarios # Downloads unless every camera of scenario.json already has frames. fetch-scenario: @python3 -c "import glob, json, sys; d = 'data/scenarios/$(SCENARIO)'; \ - sys.exit(any(not glob.glob(f'{d}/{c}/*.jpg') for c in json.load(open(f'{d}/scenario.json'))['cameras']))" || \ + sys.exit(any(not glob.glob(f'{d}/{c}/**/*.jpg', recursive=True) for c in json.load(open(f'{d}/scenario.json'))['cameras']))" || \ (curl -fsSL $(SCENARIOS_URL)/$(SCENARIO).zip -o /tmp/$(SCENARIO).zip && \ unzip -oq /tmp/$(SCENARIO).zip -x '*/scenario.json' -d data/scenarios && rm /tmp/$(SCENARIO).zip) @@ -122,4 +130,21 @@ logs: # ------------------------------------------------------------------- test: - pytest -s tests/* + pytest -s tests --ignore=tests/e2e -m "not integration" + +# End-to-end: fresh stack (data/ is a bind mount, so the init marker survives `down -v`), +# then the tests. Whatever fails, ps and the logs are dumped to e2e-artifacts/ and make +# exits with the failing step's code. The stack is left up for debugging, `make stop` cleans. +e2e: + $(MAKE) stop + rm -f data/.init_done + $(MAKE) init build-e2e + rm -rf e2e-artifacts && mkdir -p e2e-artifacts + @rc=0; \ + docker compose --profile front --profile engine up -d --wait || rc=$$?; \ + if [ $$rc -eq 0 ]; then \ + uv run --python 3.12 --with-requirements tests/requirements.txt pytest tests/e2e --junitxml=e2e-artifacts/junit.xml -ra --tb=short || rc=$$?; \ + fi; \ + docker compose ps -a > e2e-artifacts/ps.txt 2>&1; \ + docker compose --profile front --profile engine logs --no-color > e2e-artifacts/compose.log 2>&1; \ + exit $$rc diff --git a/README.md b/README.md index 4a6a8e1..8ed6f35 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,8 @@ make run ```bash make build -make run-all +make run +make run-engine ``` This launches everything, including the engine and the fake cameras playing the @@ -88,6 +89,14 @@ docker compose logs -f engine --- +## ๐Ÿงช End-to-end tests + +`make e2e SCENARIO=` tears the stack down, brings up a fresh one (two fake cameras playing the scenario, the real camera API, engine, pyro-api and the frontend) and runs the pytest suite in `tests/e2e/` against it. It needs Docker and [`uv`](https://docs.astral.sh/uv/), and leaves the stack running afterwards for debugging (`make stop` cleans it). + +Whatever the outcome, `e2e-artifacts/` holds `junit.xml` (which assertion failed, open it first), `compose.log` (engine, camera API and fake camera logs) and `ps.txt` (container states). A run rewrites the tracked `data/credentials.json`, since init writes the camera tokens into it: do not commit that change. Scenarios need a fresh stack, because the API groups detections of the same pose for 2 hours, which is why `make e2e` always starts from `make stop`. + +--- + ## ๐Ÿ”‘ Access * **API**: [http://localhost:5050/docs](http://localhost:5050/docs) @@ -120,8 +129,8 @@ certificate, so the real `pyro_camera_api` and `engine` run against them unchang images shown one after the other, the last image being held forever. Each preset moves to its next image on its next visit by the patrol (the first `Snap` after a `ToPos`), so the engine sees every image once per preset, in order, whatever its timing; snaps taken in place, -like the autofocus ones, see the same image. Every preset of a camera serves the same images -for now. +like the autofocus ones, see the same image. A preset can have its own images (see +Scenario format), otherwise it plays the camera's. ```bash make run-engine # engine + camera API + fake cameras @@ -133,11 +142,15 @@ Scenarios: * `smoke-then-clear` (default): real wildfire seen by both cameras, 40 frames of smoke then a clear view * `never-smoke`: both cameras hold a clear view +* `smoke-one-camera`: smoke on preset 3 of `croix-augas-01` only, every other pose clear (one alert expected) * `false-positive`: false positives from the pyro-dataset val set, YOLO fires but the temporal model rejects them (no alert expected with temporal validation) +`make fetch-scenario` downloads from the `scenarios` release by default, `SCENARIOS_URL=` points it at another release. + `GET https://localhost:8443/scenario` (8444 for `fakecam-2`) reports the camera state: -current preset and azimuth, its frame index and `finished` once every visited preset shows the -last frame. +current preset and azimuth, its frame index and `finished` once every preset declared in +`poses` shows its last frame (a preset never visited is not finished). A `presets` block gives the +visits, frame and frames of each preset. The image embeds `smoke-then-clear`, so it also runs alone, without the `data/scenarios` volume (used by pi-manager-template on a test station). @@ -157,8 +170,13 @@ data/scenarios/smoke-then-clear/ scenario.json # {"cameras": {"": {"poses": {"": }}}} croix-augas-01/ # frames of fakecam-1, in order: 000.jpg, 001.jpg, ... nemours-02/ # frames of fakecam-2 + croix-augas-01/3/ # optional: frames of preset 3 only (key of "poses"), 000.jpg, ... ``` +A preset without a folder plays the camera-level frames; a preset with neither makes the +fake camera refuse to start. `--preset 3` of `make_scenario.py` writes into `/3/` the +sequence seen on the pose whose `patrol_id` is 3 in the alert. + Camera names and presets match `data/csv/API_DATA_DEV - cameras.csv` / `poses.csv`, so the init script gives each fake camera its token and the engine finds its poses. diff --git a/containers/fake_camera/server.py b/containers/fake_camera/server.py index c9ad6d2..e5f4b65 100644 --- a/containers/fake_camera/server.py +++ b/containers/fake_camera/server.py @@ -3,13 +3,19 @@ Answers the Reolink HTTP API (``/cgi-bin/api.cgi?cmd=...``) the way the real ``pyro_camera_api`` Reolink adapter expects, serving the frames of a scenario. One process is one camera: ``SCENARIO`` and ``CAMERA`` select -``///*.jpg`` (sorted, last frame held). -Each preset moves to its next frame on its next visit: the first Snap after a -ToPos, so snaps taken in place (autofocus) see the same frame. A camera never -positioned (static) moves on every Snap. +``///``. A preset (a key of ``poses`` in +``scenario.json``) plays the frames of ``//*.jpg`` (sorted, last +frame held), or else the camera-level ``/*.jpg``, so a scenario can put +smoke on one pose only. Each preset keeps its own position: it moves to its next +frame on its next visit, the first Snap after a ToPos, so snaps taken in place +(autofocus) see the same frame. A camera never positioned (static) plays the +camera-level frames and moves on every Snap. ``GET /scenario`` is not part of the Reolink API: it reports the camera state -(preset, azimuth, frame, finished) so tests know where the scenario is. +(scenario, preset, azimuth, frame and frames of the current preset, finished, +and visits, frame and frames of every declared preset) so tests know where the +scenario is. ``finished`` means every declared preset is on its last frame, a +preset never visited counting as not finished. """ import json @@ -44,19 +50,37 @@ def reply(cmd, value=None, error=None): class Camera: - def __init__(self, scenario_dir, name): + def __init__(self, scenario_dir, name, scenario=None): meta = json.loads((scenario_dir / "scenario.json").read_text()) self.name = name + self.scenario = scenario # reported by /scenario # preset id -> real-world azimuth, informational only (see /scenario) self.azimuths = { int(k): float(v) for k, v in meta["cameras"][name]["poses"].items() } - # ponytail: every preset serves the same frames; per-preset folders if needed - self.frames = sorted((scenario_dir / name).glob("*.jpg")) - if not self.frames: + camera_dir = scenario_dir / name + # Camera-level frames: the fallback of a preset without a folder, and what a + # Snap sees before any ToPos (a static camera). + self.frames = sorted(camera_dir.glob("*.jpg")) + # preset id -> its own frames, or the camera-level ones + self.preset_frames = {} + for preset in self.azimuths: + own = sorted((camera_dir / str(preset)).glob("*.jpg")) + if not (own or self.frames): + raise SystemExit( + f"no frames for scenario {scenario or scenario_dir.name}, " + f"camera {name}, preset {preset}: expected " + f"{camera_dir / str(preset)}/*.jpg or {camera_dir}/*.jpg, " + "run `make fetch-scenario` first" + ) + self.preset_frames[preset] = own or self.frames + if not self.preset_frames and not self.frames: raise SystemExit( - f"no frames in {scenario_dir / name}, run `make fetch-scenario` first" + f"no frames in {camera_dir}, run `make fetch-scenario` first" ) + if not self.frames: + # A Snap before any ToPos has no camera-level frames: use the first preset's + self.frames = self.preset_frames[min(self.preset_frames)] self.lock = threading.Lock() self.preset = None # unknown until a ToPos; stays None on a static camera self.visits = {} # preset -> visits that took a Snap @@ -64,28 +88,48 @@ def __init__(self, scenario_dir, name): self.enabled = set(self.azimuths) self.zoom, self.focus, self.autofocus_disabled = 0, 720, 0 + def _frames(self, preset): + return self.preset_frames.get(preset, self.frames) + def _frame(self, preset): - return frame_index(self.visits.get(preset, 0), len(self.frames)) + return frame_index(self.visits.get(preset, 0), len(self._frames(preset))) + + def _on_last_frame(self, preset): + return self.visits.get(preset, 0) >= len(self._frames(preset)) def snap(self): with self.lock: if self.arrived or self.preset is None: self.visits[self.preset] = self.visits.get(self.preset, 0) + 1 self.arrived = False - return self.frames[self._frame(self.preset)].read_bytes() + return self._frames(self.preset)[self._frame(self.preset)].read_bytes() def status(self): with self.lock: return { + "scenario": self.scenario, "camera": self.name, "preset": self.preset, "azimuth": self.azimuths.get(self.preset), "frame": self._frame(self.preset), - "frames": len(self.frames), - "finished": bool(self.visits) - and all(self._frame(p) == len(self.frames) - 1 for p in self.visits), + "frames": len(self._frames(self.preset)), + "finished": self._finished(), + "presets": { + str(p): { + "visits": self.visits.get(p, 0), + "frame": self._frame(p), + "frames": len(self._frames(p)), + } + for p in sorted(self.preset_frames) + }, } + def _finished(self): + if self.preset_frames: + # Snaps before any ToPos (preset None) neither block nor trigger this + return all(self._on_last_frame(p) for p in self.preset_frames) + return bool(self.visits) and all(self._on_last_frame(p) for p in self.visits) + def command(self, cmd, param): with self.lock: if cmd == "PtzCtrl": @@ -207,6 +251,7 @@ def main(): camera = Camera( Path(os.environ.get("SCENARIOS_DIR", "/scenarios")) / scenario, os.environ["CAMERA"], + scenario, ) port = int(os.environ.get("PORT", "443")) here = Path(__file__).parent @@ -219,11 +264,11 @@ def main(): httpd.socket = context.wrap_socket(httpd.socket, server_side=True) logging.info( "fake camera %s plays scenario %s: " - "%d frames, one per preset visit, presets %s, port %d", + "one frame per preset visit, frames per preset %s, port %d", camera.name, scenario, - len(camera.frames), - sorted(camera.enabled), + {p: len(f) for p, f in sorted(camera.preset_frames.items())} + or len(camera.frames), port, ) httpd.serve_forever() diff --git a/data/scenarios/never-smoke/scenario.json b/data/scenarios/never-smoke/scenario.json index 156f4f5..eaca444 100644 --- a/data/scenarios/never-smoke/scenario.json +++ b/data/scenarios/never-smoke/scenario.json @@ -3,5 +3,10 @@ "cameras": { "croix-augas-01": {"poses": {"1": 326.5, "2": 13.2, "3": 59.8}}, "nemours-02": {"poses": {"0": 245.9, "1": 292.4, "2": 339.4, "3": 25.4}} + }, + "expected": { + "alerts": 0, + "sequences": [], + "timeout_s": 600 } } diff --git a/data/scenarios/smoke-one-camera/scenario.json b/data/scenarios/smoke-one-camera/scenario.json new file mode 100644 index 0000000..7385553 --- /dev/null +++ b/data/scenarios/smoke-one-camera/scenario.json @@ -0,0 +1,13 @@ +{ + "description": "Smoke on preset 3 of croix-augas-01 only (18 frames of prod alert 49767, then a clear view held forever), every other pose of both cameras holds a clear view. Expected: exactly one alert, from one sequence on that pose.", + "cameras": { + "croix-augas-01": {"poses": {"1": 326.5, "2": 13.2, "3": 59.8}}, + "nemours-02": {"poses": {"0": 245.9, "1": 292.4, "2": 339.4, "3": 25.4}} + }, + "expected": { + "alerts": 1, + "sequences": [{"camera": "croix-augas-01", "preset": "3", "min_detections": 7}], + "location": null, + "timeout_s": 900 + } +} diff --git a/data/scenarios/smoke-then-clear/scenario.json b/data/scenarios/smoke-then-clear/scenario.json index ae84725..94ab535 100644 --- a/data/scenarios/smoke-then-clear/scenario.json +++ b/data/scenarios/smoke-then-clear/scenario.json @@ -3,5 +3,18 @@ "cameras": { "croix-augas-01": {"poses": {"1": 326.5, "2": 13.2, "3": 59.8}}, "nemours-02": {"poses": {"0": 245.9, "1": 292.4, "2": 339.4, "3": 25.4}} + }, + "expected": { + "alerts": 5, + "sequences": [ + {"camera": "croix-augas-01", "preset": "1", "min_detections": 15}, + {"camera": "croix-augas-01", "preset": "2", "min_detections": 15}, + {"camera": "croix-augas-01", "preset": "3", "min_detections": 15}, + {"camera": "nemours-02", "preset": "0", "min_detections": 15}, + {"camera": "nemours-02", "preset": "1", "min_detections": 15}, + {"camera": "nemours-02", "preset": "2", "min_detections": 15}, + {"camera": "nemours-02", "preset": "3", "min_detections": 15} + ], + "timeout_s": 2400 } } diff --git a/docker-compose.yml b/docker-compose.yml index 774ab8d..9460f82 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,6 +2,8 @@ services: pyro_api: container_name: api image: pyronear/alert-api:latest + # No arm64 manifest on Docker Hub (Apple Silicon runs it emulated) + platform: linux/amd64 command: "sh -c 'alembic upgrade head && python app/db.py && uvicorn app.main:app --reload --host 0.0.0.0 --port 5050 --proxy-headers'" ports: - 5050:5050 @@ -164,6 +166,8 @@ services: temporal_model_api: container_name: temporal_model_api image: pyronear/temporal-model-api:latest + # No arm64 manifest on Docker Hub (Apple Silicon runs it emulated) + platform: linux/amd64 profiles: - temporal ports: @@ -213,6 +217,8 @@ services: condition: service_healthy frontend: image: pyronear/pyro-platform-react:latest + # Image is amd64 only (Apple Silicon runs it emulated) + platform: linux/amd64 profiles: - front ports: diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..f210070 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,7 @@ +[pytest] +testpaths = tests +pythonpath = . +addopts = --strict-markers +markers = + e2e: needs the whole compose stack (make e2e) + integration: needs a running service such as the fake camera or the database diff --git a/scripts/make_scenario.py b/scripts/make_scenario.py index b9f9d58..a8005aa 100644 --- a/scripts/make_scenario.py +++ b/scripts/make_scenario.py @@ -6,6 +6,14 @@ Frames are written as 000.jpg, 001.jpg, ... in time order: the alert frames of the camera named like the output folder, then the clear images. Without --alert only the clear images are written (a camera that never sees smoke). + + python scripts/make_scenario.py data/scenarios//croix-augas-01 \ + --alert data/replay_alerts/alert_49767.zip --preset 3 --frames 5 + +--preset writes the frames of one PTZ preset into // (the key of +`poses` in scenario.json, the `patrol_id` of the pose in the alert) and takes the +sequence seen on that pose. Presets without a folder play the frames of the camera +folder. The scenario.json next to the camera folders is written by hand. """ @@ -15,13 +23,20 @@ from pathlib import Path -def alert_frames(alert_zip, camera_name, count): +def alert_frames(alert_zip, camera_name, count, preset=None): zf = zipfile.ZipFile(alert_zip) alert = json.loads(zf.read("alert.json")) camera_id = next( k for k, cam in alert["cameras"].items() if cam["name"] == camera_name ) - sequence = next(s for s in alert["sequences"] if str(s["camera_id"]) == camera_id) + sequences = [s for s in alert["sequences"] if str(s["camera_id"]) == camera_id] + if preset is not None: + poses = alert["cameras"][camera_id]["poses"] + pose_ids = {p["id"] for p in poses if str(p["patrol_id"]) == preset} + sequences = [s for s in sequences if s["pose_id"] in pose_ids] + if not sequences: + raise SystemExit(f"no sequence of {camera_name} on preset {preset}") + sequence = sequences[0] detections = sorted(sequence["detections"], key=lambda d: d["recorded_at"])[:count] return [zf.read(d["image"]) for d in detections] @@ -37,6 +52,10 @@ def main(): parser.add_argument( "--frames", type=int, default=40, help="alert frames to keep (default 40)" ) + parser.add_argument( + "--preset", + help="PTZ preset (patrol_id): write //, that pose's sequence", + ) parser.add_argument( "--clear", type=Path, @@ -46,14 +65,19 @@ def main(): ) args = parser.parse_args() - frames = alert_frames(args.alert, args.out.name, args.frames) if args.alert else [] + frames = ( + alert_frames(args.alert, args.out.name, args.frames, args.preset) + if args.alert + else [] + ) frames += [path.read_bytes() for path in args.clear] - args.out.mkdir(parents=True, exist_ok=True) - for stale in args.out.glob("*.jpg"): + out = args.out / args.preset if args.preset is not None else args.out + out.mkdir(parents=True, exist_ok=True) + for stale in out.glob("*.jpg"): stale.unlink() for i, data in enumerate(frames): - (args.out / f"{i:03d}.jpg").write_bytes(data) - print(f"{len(frames)} frames written to {args.out}") + (out / f"{i:03d}.jpg").write_bytes(data) + print(f"{len(frames)} frames written to {out}") if __name__ == "__main__": diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/e2e/__init__.py b/tests/e2e/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py new file mode 100644 index 0000000..84a97c3 --- /dev/null +++ b/tests/e2e/conftest.py @@ -0,0 +1,233 @@ +# ruff: noqa: E501 +"""Fixtures for the end-to-end tests. They assume the stack is already up (make e2e) and never touch the network at import or collection time.""" + +from __future__ import annotations + +import csv +import os +import time +from datetime import datetime, timezone +from pathlib import Path + +import pytest +import requests +import urllib3 +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + +from tests.e2e.helpers import wait_until +from tests.scenario import SCENARIOS_DIR, ScenarioError, load_scenario + +ROOT = Path(__file__).resolve().parents[2] +API_URL = os.environ.get("E2E_API_URL", "http://localhost:5050").rstrip("/") +FAKECAM_URLS = [ + u.strip().rstrip("/") + for u in os.environ.get( + "E2E_FAKECAM_URLS", "https://127.0.0.1:8443,https://127.0.0.1:8444" + ).split(",") + if u.strip() +] +# Measured 2026-11-12 on emulated arm64 (e2e-step0-measurements): cameras first polled ~105 s after `up` started, first alert visible after 227 s. +ENGINE_START_TIMEOUT = float(os.environ.get("E2E_ENGINE_START_TIMEOUT", 300)) +FIRST_ALERT_TIMEOUT = float(os.environ.get("E2E_FIRST_ALERT_TIMEOUT", 600)) +# Measured settle after the cameras finish: 0 s. +SETTLE_WINDOW = float(os.environ.get("E2E_SETTLE_WINDOW", 60)) +POLL_INTERVAL = float(os.environ.get("E2E_POLL_INTERVAL", 5)) +TIMEOUT_MARGIN = 300 + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) +SESSION_START = datetime.now(timezone.utc) + + +def _scenario_name(): + return os.environ.get("SCENARIO") + + +def pytest_collection_modifyitems(config, items): + name = _scenario_name() + timeout = None + try: + expected = load_scenario(name).expected if name else None + if expected: + # The session fixtures wait up to first-alert + timeout_s + settle before the first test body runs, and that wait counts against the test that requests them. + timeout = ( + expected.timeout_s + + FIRST_ALERT_TIMEOUT + + SETTLE_WINDOW + + TIMEOUT_MARGIN + ) + except (ScenarioError, OSError, ValueError): + pass # the `scenario` fixture reports the problem with a clear message + for item in items: + if "tests/e2e/" not in item.nodeid.replace( + os.sep, "/" + ) and "tests/e2e" not in str(item.fspath): + continue + item.add_marker(pytest.mark.e2e) + if timeout and item.get_closest_marker("timeout") is None: + item.add_marker(pytest.mark.timeout(timeout)) + + +def camera_states(): + """GET /scenario of every fake camera, an {"error": ...} entry for one that does not answer.""" + states = [] + for url in FAKECAM_URLS: + try: + r = requests.get(f"{url}/scenario", verify=False, timeout=10) + r.raise_for_status() + states.append({"url": url, **r.json()}) + except (requests.RequestException, ValueError) as exc: + states.append({"url": url, "error": repr(exc)}) + return states + + +def _alert_count(api): + r = api.get(f"{API_URL}/api/v1/alerts/unlabeled/latest", timeout=30) + r.raise_for_status() + return len(r.json()) + + +@pytest.fixture(scope="session") +def scenario(): + name = _scenario_name() + if not name: + pytest.fail( + "SCENARIO is not set: run `make e2e SCENARIO=` or export SCENARIO= (see data/scenarios/)", + pytrace=False, + ) + try: + loaded = load_scenario(name) + except ScenarioError as exc: + pytest.fail(str(exc), pytrace=False) + if loaded.expected is None: + pytest.fail( + f"scenario {name!r} has no `expected` block in {SCENARIOS_DIR / name / 'scenario.json'}", + pytrace=False, + ) + for state in camera_states(): + if "error" in state: + pytest.fail( + f"fake camera {state['url']} does not answer GET /scenario: {state['error']}. Is the stack up?", + pytrace=False, + ) + if "scenario" not in state: + pytest.fail( + f"fake camera {state['url']} does not report a `scenario`: its image is older than this branch, rebuild it (make build-e2e)", + pytrace=False, + ) + if state["scenario"] != name: + pytest.fail( + f"fake camera {state['url']} plays {state['scenario']!r} but SCENARIO={name!r}", + pytrace=False, + ) + return loaded + + +def _new_session(): + session = requests.Session() + # uvicorn closes idle connections after 5 s, the same as the poll interval, so a reused connection can be dropped mid-request: retry GETs. + retry = Retry(total=3, backoff_factor=0.5, allowed_methods=["GET"]) + for prefix in ("http://", "https://"): + session.mount(prefix, HTTPAdapter(max_retries=retry)) + return session + + +@pytest.fixture(scope="session") +def api(): + user, password = os.environ.get("E2E_USER"), os.environ.get("E2E_PASSWORD") + if not user: + with open(ROOT / "data" / "csv" / "API_DATA_DEV - users.csv") as f: + row = next(r for r in csv.DictReader(f) if r["login"] == "test77") + user, password = row["login"], row["password"] + session = _new_session() + r = session.post( + f"{API_URL}/api/v1/login/creds", + data={"username": user, "password": password}, + timeout=30, + ) + assert ( + r.status_code == 200 + ), f"login as {user!r} on {API_URL} failed: {r.status_code} {r.text}" + session.headers["Authorization"] = f"Bearer {r.json()['access_token']}" + return session + + +@pytest.fixture(scope="session") +def diagnose(api): + def _diagnose(): + lines = [f" {s}" for s in camera_states()] + try: + lines.append(f" unlabeled alerts visible: {_alert_count(api)}") + except requests.RequestException as exc: + lines.append(f" alert count unavailable: {exc!r}") + return "state of the stack:\n" + "\n".join(lines) + + return _diagnose + + +@pytest.fixture(scope="session") +def first_alert(scenario, api, diagnose): + def engine_never_polled(elapsed): + states = camera_states() if elapsed >= ENGINE_START_TIMEOUT else [] + # a camera that does not answer (no "presets") is not proof of anything + if ( + states + and all("presets" in s for s in states) + and not any(p["visits"] > 0 for s in states for p in s["presets"].values()) + ): + return f"pyro_camera_api never polled the fake cameras (no preset visited after {ENGINE_START_TIMEOUT:.0f} s)" + + def latest(): + r = api.get(f"{API_URL}/api/v1/alerts/unlabeled/latest", timeout=30) + r.raise_for_status() + return r.json() + + return wait_until( + latest, + FIRST_ALERT_TIMEOUT, + POLL_INTERVAL, + "the first alert in /alerts/unlabeled/latest", + diagnose, + abort=engine_never_polled, + ) + + +def _all_alerts(api): + # /alerts/all/fromdate matches one exact day, so query the day the session started and today (they differ if the run crosses UTC midnight). + days = { + SESSION_START.date().isoformat(), + datetime.now(timezone.utc).date().isoformat(), + } + alerts = {} + for day in sorted(days): + offset = 0 + while True: + r = api.get( + f"{API_URL}/api/v1/alerts/all/fromdate", + params={"from_date": day, "limit": 100, "offset": offset}, + timeout=60, + ) + r.raise_for_status() + page = r.json() + alerts.update({a["id"]: a for a in page}) + if len(page) < 100: + break + offset += 100 + return list(alerts.values()) + + +@pytest.fixture(scope="session") +def settled_alerts(scenario, api, diagnose): + def finished(): + states = camera_states() + return bool(states) and all(s.get("finished") is True for s in states) + + wait_until( + finished, + scenario.expected.timeout_s, + POLL_INTERVAL, + f"every fake camera to report finished (scenario {scenario.name})", + diagnose, + ) + time.sleep(SETTLE_WINDOW) + return _all_alerts(api) diff --git a/tests/e2e/helpers.py b/tests/e2e/helpers.py new file mode 100644 index 0000000..2bcac91 --- /dev/null +++ b/tests/e2e/helpers.py @@ -0,0 +1,38 @@ +# ruff: noqa: E501 +from __future__ import annotations + +import time +from typing import Any, Callable, Optional + + +class WaitError(AssertionError): + pass + + +def wait_until( + fn: Callable[[], Any], + timeout: float, + interval: float, + what: str, + diagnose: Callable[[], str] = lambda: "", + abort: Optional[Callable[[float], Optional[str]]] = None, +): + """Poll fn until it returns something truthy and return it. + + On timeout, raise a WaitError saying what was awaited, the elapsed seconds, the last value fn returned and diagnose(). + abort(elapsed) may return a message to fail early, with the same details. + """ + start = time.monotonic() + last = None + while True: + last = fn() + if last: + return last + elapsed = time.monotonic() - start + reason = abort(elapsed) if abort else None + if reason or elapsed >= timeout: + head = reason or f"timed out waiting for {what}" + raise WaitError( + f"{head} (awaited: {what}; elapsed {elapsed:.0f} s of {timeout:.0f} s; last value: {last!r})\n{diagnose()}" + ) + time.sleep(interval) diff --git a/tests/e2e/test_baseline_api.py b/tests/e2e/test_baseline_api.py new file mode 100644 index 0000000..94ca860 --- /dev/null +++ b/tests/e2e/test_baseline_api.py @@ -0,0 +1,119 @@ +# ruff: noqa: E501 +from __future__ import annotations + +import json + +import pytest +import requests + +from tests.e2e.conftest import API_URL, ROOT +from tests.scenario import NOT_CHECKED, haversine_km + +JPEG_MAGIC = b"\xff\xd8\xff" + + +def _pose_ids(): + """(camera name, preset) -> pose_id, from data/credentials.json where `poses` and `pose_ids` are matched positionally.""" + creds = json.loads((ROOT / "data" / "credentials.json").read_text()) + return { + (c["name"], str(p)): pid + for c in creds.values() + for p, pid in zip(c["poses"], c["pose_ids"]) + } + + +def _sequences(alerts): + return [s for a in alerts for s in a["sequences"]] + + +def _require_alerts(scenario): + if scenario.expected.alerts == 0: + pytest.skip("scenario expects no alert") + + +def test_first_alert_appears(scenario, request): + _require_alerts(scenario) + assert request.getfixturevalue("first_alert") + + +def test_alert_count(scenario, settled_alerts): + assert len(settled_alerts) == scenario.expected.alerts, [ + a["id"] for a in settled_alerts + ] + + +def test_expected_sequences(scenario, settled_alerts, api): + if not scenario.expected.sequences: + pytest.skip("scenario lists no sequence to check") + cameras = { + c["name"]: c["id"] + for c in api.get(f"{API_URL}/api/v1/cameras/", timeout=30).json() + } + pose_ids = _pose_ids() + by_key = {(s["camera_id"], s["pose_id"]): s for s in _sequences(settled_alerts)} + problems = [] + for exp in scenario.expected.sequences: + key = (cameras.get(exp.camera), pose_ids.get((exp.camera, exp.preset))) + seq = by_key.get(key) + if seq is None: + problems.append( + f"{exp.camera} preset {exp.preset} (camera_id, pose_id)={key}: no sequence" + ) + elif seq["detections_count"] < exp.min_detections: + problems.append( + f"{exp.camera} preset {exp.preset}: {seq['detections_count']} detections, expected at least {exp.min_detections}" + ) + assert not problems, "\n".join(problems) + + +def _fetch_image(url): + r = requests.get(url, timeout=60) + assert r.status_code == 200, f"{r.status_code} for {url}" + assert r.content[:3] == JPEG_MAGIC, f"not a JPEG: {url}" + + +def test_detections_have_images(scenario, settled_alerts, api): + _require_alerts(scenario) + sequences = _sequences(settled_alerts) + assert sequences, "alerts carry no sequence" + for seq in sequences: + r = api.get( + f"{API_URL}/api/v1/sequences/{seq['id']}/detections", + params={"with_crop": "true", "limit": 100}, + timeout=60, + ) + assert r.status_code == 200, r.text + detections = r.json() + assert detections, f"sequence {seq['id']} has no detection" + for d in detections: + assert d.get( + "url" + ), f"sequence {seq['id']} detection {d.get('id')}: empty url" + assert d.get( + "crop_url" + ), f"sequence {seq['id']} detection {d.get('id')}: empty crop_url" + for d in (detections[0], detections[len(detections) // 2], detections[-1]): + _fetch_image(d["url"]) + _fetch_image(d["crop_url"]) + + +def test_location(scenario, settled_alerts): + expected = scenario.expected.location + if expected is NOT_CHECKED: + pytest.skip("scenario does not check the location") + if expected is None: + located = [ + a["id"] + for a in settled_alerts + if a.get("lat") is not None or a.get("lon") is not None + ] + assert not located, f"alerts with a position: {located}" + return + distances = { + a["id"]: haversine_km(expected.lat, expected.lon, a["lat"], a["lon"]) + for a in settled_alerts + if a.get("lat") is not None and a.get("lon") is not None + } + assert ( + distances and min(distances.values()) <= expected.tolerance_km + ), f"distance in km to ({expected.lat}, {expected.lon}) per alert: {distances}" diff --git a/tests/requirements.txt b/tests/requirements.txt index 4977cf9..750ece7 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -1,4 +1,6 @@ psycopg2-binary==2.9.9 pytest==9.0.3 +pytest-timeout==2.4.0 python-dotenv==1.2.2 boto3==1.34.90 +requests==2.34.2 diff --git a/tests/scenario.py b/tests/scenario.py new file mode 100644 index 0000000..13f7c96 --- /dev/null +++ b/tests/scenario.py @@ -0,0 +1,135 @@ +# ruff: noqa: E501 +"""Loader for data/scenarios//scenario.json, including the optional `expected` block.""" + +from __future__ import annotations + +import json +import math +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Optional + +SCENARIOS_DIR = Path(__file__).resolve().parents[1] / "data" / "scenarios" +EXPECTED_KEYS = {"alerts", "sequences", "location", "timeout_s"} +SEQUENCE_KEYS = {"camera", "preset", "min_detections"} +LOCATION_KEYS = {"lat", "lon", "tolerance_km"} +# Distinguishes "location key absent" (not checked) from `"location": null` (all alerts have no position). +NOT_CHECKED = "not_checked" + + +class ScenarioError(ValueError): + pass + + +@dataclass +class ExpectedSequence: + camera: str + preset: str + min_detections: int + + +@dataclass +class ExpectedLocation: + lat: float + lon: float + tolerance_km: float + + +@dataclass +class Expected: + alerts: int + timeout_s: int + sequences: List[ExpectedSequence] = field(default_factory=list) + # NOT_CHECKED, None (every alert has null lat/lon) or an ExpectedLocation + location: object = NOT_CHECKED + + +@dataclass +class Scenario: + name: str + description: str + cameras: Dict[str, Dict[str, float]] + expected: Optional[Expected] + + +def _unknown(where: str, got: dict, allowed: set) -> None: + extra = sorted(set(got) - allowed) + if extra: + raise ScenarioError( + f"unknown key(s) in {where}: {extra}, allowed: {sorted(allowed)}" + ) + + +def _require_number(where: str, value, kind=(int, float)) -> None: + if isinstance(value, bool) or not isinstance(value, kind): + raise ScenarioError(f"{where} must be a number, got {value!r}") + + +def _parse_expected(name: str, raw: dict, cameras: dict) -> Expected: + where = f"{name}: expected" + if not isinstance(raw, dict): + raise ScenarioError(f"{where} must be an object") + _unknown(where, raw, EXPECTED_KEYS) + for key in ("alerts", "timeout_s"): + if key not in raw: + raise ScenarioError(f"{where}.{key} is required") + _require_number(f"{where}.{key}", raw[key], int) + sequences = [] + for i, seq in enumerate(raw.get("sequences") or []): + _unknown(f"{where}.sequences[{i}]", seq, SEQUENCE_KEYS) + missing = SEQUENCE_KEYS - set(seq) + if missing: + raise ScenarioError(f"{where}.sequences[{i}] misses {sorted(missing)}") + camera, preset = seq["camera"], str(seq["preset"]) + if camera not in cameras: + raise ScenarioError( + f"{where}.sequences[{i}]: unknown camera {camera!r}, known: {sorted(cameras)}" + ) + if preset not in cameras[camera]: + raise ScenarioError( + f"{where}.sequences[{i}]: camera {camera!r} has no preset {preset!r}, known: {sorted(cameras[camera])}" + ) + _require_number( + f"{where}.sequences[{i}].min_detections", seq["min_detections"], int + ) + sequences.append(ExpectedSequence(camera, preset, seq["min_detections"])) + location: object = NOT_CHECKED + if "location" in raw: + loc = raw["location"] + if loc is None: + location = None + else: + if not isinstance(loc, dict): + raise ScenarioError(f"{where}.location must be null or an object") + _unknown(f"{where}.location", loc, LOCATION_KEYS) + missing = LOCATION_KEYS - set(loc) + if missing: + raise ScenarioError(f"{where}.location misses {sorted(missing)}") + for key in LOCATION_KEYS: + _require_number(f"{where}.location.{key}", loc[key]) + location = ExpectedLocation(loc["lat"], loc["lon"], loc["tolerance_km"]) + return Expected(raw["alerts"], raw["timeout_s"], sequences, location) + + +def load_scenario(name: str, root: Path = SCENARIOS_DIR) -> Scenario: + path = Path(root) / name / "scenario.json" + if not path.is_file(): + raise ScenarioError(f"no scenario {name!r}: {path} does not exist") + raw = json.loads(path.read_text()) + cameras = { + cam: {str(k): v for k, v in spec["poses"].items()} + for cam, spec in raw["cameras"].items() + } + expected = ( + _parse_expected(name, raw["expected"], cameras) if "expected" in raw else None + ) + return Scenario(name, raw.get("description", ""), cameras, expected) + + +def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float: + p1, p2 = math.radians(lat1), math.radians(lat2) + a = ( + math.sin((p2 - p1) / 2) ** 2 + + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2 + ) + return 6371.0088 * 2 * math.asin(math.sqrt(a)) diff --git a/tests/test_alerts.py b/tests/test_alerts.py index d60bb8e..148273c 100644 --- a/tests/test_alerts.py +++ b/tests/test_alerts.py @@ -7,6 +7,8 @@ # Load environment variables from .env file load_dotenv() +pytestmark = pytest.mark.integration + @pytest.fixture def db_connection(): diff --git a/tests/test_e2e_helpers.py b/tests/test_e2e_helpers.py new file mode 100644 index 0000000..c45dcaf --- /dev/null +++ b/tests/test_e2e_helpers.py @@ -0,0 +1,80 @@ +# ruff: noqa: E501 +from __future__ import annotations + +import http.server +import threading + +import pytest + +from tests.e2e.conftest import _new_session +from tests.e2e.helpers import WaitError, wait_until + + +def test_wait_until_returns_first_truthy_value(): + values = iter([None, 0, "ready"]) + assert wait_until(lambda: next(values), 5, 0.01, "a value") == "ready" + + +def test_wait_until_timeout_message_names_what_elapsed_last_value_and_diagnosis(): + with pytest.raises(WaitError) as exc: + wait_until( + lambda: [], + 0.2, + 0.05, + "the first alert", + diagnose=lambda: "cameras: frame 0", + ) + msg = str(exc.value) + assert "the first alert" in msg + assert "elapsed 0 s of 0 s" in msg + assert "last value: []" in msg + assert "cameras: frame 0" in msg + + +def test_wait_until_aborts_early_with_the_reason(): + with pytest.raises(WaitError) as exc: + wait_until( + lambda: None, + 60, + 0.01, + "an alert", + abort=lambda elapsed: "pyro_camera_api never polled the fake cameras (no camera left frame 0 after 300 s)", + ) + msg = str(exc.value) + assert msg.startswith( + "pyro_camera_api never polled the fake cameras (no camera left frame 0 after 300 s)" + ) + assert "awaited: an alert" in msg + + +def test_session_get_survives_a_dropped_connection(): + seen = [] + + class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_GET(self): + seen.append(1) + if len(seen) == 1: + self.close_connection = ( + True # nothing written: the client sees RemoteDisconnected + ) + return + body = b"[]" + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with _new_session() as session: # closing it frees the keep-alive handler thread + r = session.get(f"http://127.0.0.1:{server.server_port}/", timeout=5) + assert r.status_code == 200 and len(seen) >= 2 + finally: + server.shutdown() + server.server_close() diff --git a/tests/test_fake_camera.py b/tests/test_fake_camera.py index 6638aab..6eee532 100644 --- a/tests/test_fake_camera.py +++ b/tests/test_fake_camera.py @@ -5,6 +5,7 @@ import urllib.request from pathlib import Path +import pytest from dotenv import load_dotenv sys.path.insert( @@ -75,14 +76,121 @@ def test_static_camera_moves_on_every_snap(tmp_path): assert cam.status()["finished"] +def make_camera(tmp_path, poses, camera_frames=(), preset_frames=None): + """A Camera over a scenario: poses, camera-level frames, frames per preset.""" + (tmp_path / "scenario.json").write_text( + json.dumps({"cameras": {"cam": {"poses": poses}}}) + ) + (tmp_path / "cam").mkdir() + for i, data in enumerate(camera_frames): + (tmp_path / "cam" / f"{i:03d}.jpg").write_bytes(data) + for preset, frames in (preset_frames or {}).items(): + (tmp_path / "cam" / preset).mkdir() + for i, data in enumerate(frames): + (tmp_path / "cam" / preset / f"{i:03d}.jpg").write_bytes(data) + return Camera(tmp_path, "cam", "scn") + + +def visit(cam, preset): + cam.command("PtzCtrl", {"op": "ToPos", "id": preset}) + return cam.snap() + + +def test_each_preset_plays_its_own_frames(tmp_path): + cam = make_camera( + tmp_path, + {"1": 0.0, "2": 90.0, "3": 180.0}, + camera_frames=[b"shared"], + preset_frames={"2": [b"smoke0", b"smoke1", b"smoke2"]}, + ) + assert visit(cam, 1) == b"shared" + assert visit(cam, 3) == b"shared" + assert visit(cam, 2) == b"smoke0" + assert not cam.status()["finished"] + assert visit(cam, 2) == b"smoke1" + assert not cam.status()["finished"] # the others are done, preset 2 is not + assert visit(cam, 2) == b"smoke2" + assert cam.status()["finished"] + assert visit(cam, 2) == b"smoke2" # last frame held + status = cam.status() + assert (status["preset"], status["frame"], status["frames"]) == (2, 2, 3) + assert status["presets"] == { + "1": {"visits": 1, "frame": 0, "frames": 1}, + "2": {"visits": 4, "frame": 2, "frames": 3}, + "3": {"visits": 1, "frame": 0, "frames": 1}, + } + + +def test_a_preset_never_visited_is_not_finished(tmp_path): + cam = make_camera(tmp_path, {"1": 0.0, "2": 90.0}, camera_frames=[b"shared"]) + visit(cam, 1) + assert not cam.status()["finished"] + visit(cam, 2) + assert cam.status()["finished"] + + +def test_camera_level_frames_only_behave_as_before(tmp_path): + cam = make_camera( + tmp_path, + {"1": 0.0, "2": 90.0}, + camera_frames=[b"frame0", b"frame1", b"frame2"], + ) + assert [visit(cam, 1) for _ in range(4)] == [b"frame0", b"frame1", b"frame2"] + [ + b"frame2" + ] + assert visit(cam, 2) == b"frame0" + status = cam.status() + assert (status["frame"], status["frames"], status["finished"]) == (0, 3, False) + + +def test_a_snap_before_any_to_pos_does_not_change_finished(tmp_path): + cam = make_camera(tmp_path, {"1": 0.0}, camera_frames=[b"f0", b"f1"]) + cam.snap() + cam.snap() + assert not cam.status()["finished"] # does not trigger + visit(cam, 1) + assert not cam.status()["finished"] + visit(cam, 1) + assert cam.status()["finished"] + (tmp_path / "b").mkdir() + other = make_camera(tmp_path / "b", {"1": 0.0}, camera_frames=[b"f0"]) + visit(other, 1) + other.command("PtzCtrl", {"op": "Left"}) # leaves the preset + other.snap() + assert other.status()["finished"] # does not block + + +def test_a_preset_without_frames_fails_at_start(tmp_path): + with pytest.raises(SystemExit) as exc: + make_camera( + tmp_path, {"1": 0.0, "2": 90.0}, preset_frames={"1": [b"only preset 1"]} + ) + message = str(exc.value) + assert "scn" in message and "cam" in message and "preset 2" in message + + +def test_status_reports_the_scenario_name(tmp_path): + (tmp_path / "scenario.json").write_text( + json.dumps({"cameras": {"cam": {"poses": {"1": 0.0}}}}) + ) + (tmp_path / "cam").mkdir() + (tmp_path / "cam" / "000.jpg").write_bytes(b"frame0") + cam = Camera(tmp_path, "cam", "smoke-then-clear") + assert cam.status()["scenario"] == "smoke-then-clear" + assert Camera(tmp_path, "cam").status()["scenario"] is None + + +@pytest.mark.integration def test_snap_returns_a_jpeg(): assert call("Snap")[:2] == b"\xff\xd8" +@pytest.mark.integration def test_wrong_password_is_rejected(): assert call("Snap", auth="user=nobody&password=wrong&channel=0")[0]["code"] == 1 +@pytest.mark.integration def test_ptz_follows_presets(): assert ( call("PtzCtrl", {"channel": 0, "op": "ToPos", "id": 3, "speed": 50})[0]["code"] @@ -101,6 +209,7 @@ def test_ptz_follows_presets(): assert [p["id"] for p in presets if p["enable"]] == [1, 2, 3] +@pytest.mark.integration def test_zoom_focus_values(): zoom_focus = call("GetZoomFocus", {"channel": 0})[0]["value"]["ZoomFocus"] assert zoom_focus["focus"]["pos"] == 720 diff --git a/tests/test_media.py b/tests/test_media.py index 0f5a111..d753c95 100644 --- a/tests/test_media.py +++ b/tests/test_media.py @@ -6,6 +6,8 @@ # Load environment variables from .env file load_dotenv() +pytestmark = pytest.mark.integration + # Tests run on the host: prefer the public endpoint, `rustfs` is compose-only. s3_endpoint_url = (os.getenv("S3_PROXY_URL") or os.getenv("S3_ENDPOINT_URL")) + "/" s3_access_key = os.getenv("S3_ACCESS_KEY") diff --git a/tests/test_scenarios.py b/tests/test_scenarios.py new file mode 100644 index 0000000..780b504 --- /dev/null +++ b/tests/test_scenarios.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import json + +import pytest + +from tests.scenario import ( + NOT_CHECKED, + SCENARIOS_DIR, + ExpectedLocation, + ScenarioError, + haversine_km, + load_scenario, +) + +NAMES = sorted(p.parent.name for p in SCENARIOS_DIR.glob("*/scenario.json")) +CAMERAS = {"cam-a": {"poses": {"1": 10.0, "2": 20.0}}} + + +def write(tmp_path, expected, name="s"): + (tmp_path / name).mkdir() + doc = {"description": "d", "cameras": CAMERAS} + if expected is not None: + doc["expected"] = expected + (tmp_path / name / "scenario.json").write_text(json.dumps(doc)) + return load_scenario(name, root=tmp_path) + + +def test_there_are_scenarios(): + assert {"smoke-then-clear", "never-smoke"} <= set(NAMES) + + +@pytest.mark.parametrize("name", NAMES) +def test_every_shipped_scenario_loads(name): + assert load_scenario(name).cameras + + +def test_smoke_then_clear_expected(): + expected = load_scenario("smoke-then-clear").expected + assert expected.alerts == 5 and expected.timeout_s == 2400 + assert len(expected.sequences) == 7 + assert expected.location is NOT_CHECKED + + +def test_never_smoke_expected(): + expected = load_scenario("never-smoke").expected + assert (expected.alerts, expected.sequences) == (0, []) + + +def test_no_expected_block_is_allowed(tmp_path): + assert write(tmp_path, None).expected is None + + +def test_location_semantics(tmp_path): + base = {"alerts": 1, "timeout_s": 10} + assert write(tmp_path, base, "a").expected.location is NOT_CHECKED + assert write(tmp_path, {**base, "location": None}, "b").expected.location is None + loc = write( + tmp_path, {**base, "location": {"lat": 1, "lon": 2, "tolerance_km": 3}}, "c" + ).expected.location + assert loc == ExpectedLocation(1, 2, 3) + + +def test_empty_or_absent_sequences_mean_not_checked(tmp_path): + assert write(tmp_path, {"alerts": 0, "timeout_s": 10}, "a").expected.sequences == [] + assert ( + write( + tmp_path, {"alerts": 0, "timeout_s": 10, "sequences": []}, "b" + ).expected.sequences + == [] + ) + + +@pytest.mark.parametrize( + "expected, message", + [ + ({"alerts": 1, "timeout_s": 10, "typo": 1}, "unknown key"), + ({"timeout_s": 10}, "alerts is required"), + ({"alerts": 1}, "timeout_s is required"), + ( + { + "alerts": 1, + "timeout_s": 10, + "sequences": [{"camera": "nope", "preset": "1", "min_detections": 1}], + }, + "unknown camera", + ), + ( + { + "alerts": 1, + "timeout_s": 10, + "sequences": [{"camera": "cam-a", "preset": "9", "min_detections": 1}], + }, + "no preset", + ), + ( + { + "alerts": 1, + "timeout_s": 10, + "sequences": [ + {"camera": "cam-a", "preset": "1", "min_detections": 1, "x": 1} + ], + }, + "unknown key", + ), + ( + { + "alerts": 1, + "timeout_s": 10, + "sequences": [{"camera": "cam-a", "preset": "1"}], + }, + "misses", + ), + ({"alerts": 1, "timeout_s": 10, "location": {"lat": 1, "lon": 2}}, "misses"), + ( + { + "alerts": 1, + "timeout_s": 10, + "location": {"lat": 1, "lon": 2, "tolerance_km": 3, "z": 4}, + }, + "unknown key", + ), + ({"alerts": "1", "timeout_s": 10}, "must be a number"), + ], +) +def test_loader_rejects(tmp_path, expected, message): + with pytest.raises(ScenarioError, match=message): + write(tmp_path, expected) + + +def test_unknown_scenario(tmp_path): + with pytest.raises(ScenarioError, match="no scenario"): + load_scenario("nope", root=tmp_path) + + +def test_haversine(): + assert haversine_km(48.0, 2.0, 48.0, 2.0) == 0 + assert haversine_km(0, 0, 0, 1) == pytest.approx(111.19, abs=0.1)