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..9bb1e90 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 +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..afd24ab 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) diff --git a/containers/fake_camera/server.py b/containers/fake_camera/server.py index c9ad6d2..aca13b3 100644 --- a/containers/fake_camera/server.py +++ b/containers/fake_camera/server.py @@ -9,7 +9,7 @@ positioned (static) 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, finished) so tests know where the scenario is. """ import json @@ -44,9 +44,10 @@ 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() @@ -77,6 +78,7 @@ def snap(self): def status(self): with self.lock: return { + "scenario": self.scenario, "camera": self.name, "preset": self.preset, "azimuth": self.azimuths.get(self.preset), @@ -207,6 +209,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 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-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/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..43a85d7 --- /dev/null +++ b/tests/e2e/conftest.py @@ -0,0 +1,229 @@ +# 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): + if elapsed >= ENGINE_START_TIMEOUT and all( + s.get("frame") == 0 for s in camera_states() + ): + return f"pyro_camera_api never polled the fake cameras (no camera left frame 0 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..e6c629d 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,28 @@ def test_static_camera_moves_on_every_snap(tmp_path): assert cam.status()["finished"] +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 +116,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)