Files
poorBird/server/tests/test_conditions.py
T
Thomas KarnerandClaude Opus 5 269a6eadcb Add GET /firmware/{version}.bin, and fix test teardown (Phase 2)
The last device endpoint. With it, the whole firmware/API.md contract is
implemented apart from /stream, which is Phase 6.

The device checks three things before it erases a partition
(ota_mgr.cpp:110-128): status exactly 200, a Content-Length header at all -
it refuses chunked, because it wants to size-check first - and that length
equal to the size the envelope advertised. FileResponse gives an exact
length from the file, and the camera's :8080 Caddy block has no encode
directive, so nothing recompresses it on the way out.

A row whose file is missing, or whose file does not match its recorded size,
is 503 with a loud log rather than a quiet 404. The device would abort on the
Content-Length check anyway; failing here turns a confusing remote abort into
one clear server line.

A test walks the whole OTA handshake: heartbeat names a target, and the
relative URL it advertises is fetched the way ota_mgr builds it, base plus
url, and the bytes hash to the advertised sha256.

The admin-facing POST /firmware is not included. It needs user auth and an
admin role, neither of which exists yet (SEC-007).

Also fixes a real defect in the tests. Several put their cleanup at the end
of the test body, so a failing assertion skipped it. A deliberate mutation
made two tests fail, which left two is_target firmware rows behind, and
those rows then picked themselves as the OTA target for unrelated tests -
one broken thing looked like three. Teardown now lives in fixtures and runs
whatever happens. Re-running the same mutation now fails exactly the two
tests it should and leaves the database clean.

Tests: 148 -> 158.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:19:26 +02:00

362 lines
11 KiB
Python

"""POST /api/v1/heartbeat and POST /api/v1/status.
One body, two endpoints. The tests that matter most are the ones pinning the
difference between them, because the split exists for a reason that is not
obvious from the payload.
"""
from __future__ import annotations
import secrets
from datetime import UTC, datetime, timedelta
import pytest
from conftest import needs_db
from sqlalchemy import select
from poorbird.api.deps import hash_credential, new_credential
from poorbird.models.devices import Device, DeviceCommand, DeviceStatus, Firmware
@pytest.fixture
def db():
from poorbird.db import SessionLocal
with SessionLocal() as session:
yield session
@pytest.fixture
def device(db):
"""A live, enrolled device, removed again afterwards."""
token = new_credential()
d = Device(
device_uid=secrets.token_hex(6),
name="test-cam",
token_hash=hash_credential(token),
fw_version="0.1.0",
enabled=True,
)
db.add(d)
db.commit()
db.refresh(d)
yield d, {"Authorization": f"Bearer {token}"}
db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id))
db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id))
db.delete(db.get(Device, d.id))
db.commit()
@pytest.fixture
def firmware(db):
"""Create firmware rows that are removed even when the test fails.
Teardown has to live in a fixture, not at the end of the test body: a
failing assertion skips the rest of the function, and a leftover
is_target row then picks itself as the OTA target for every later test.
"""
created: list[Firmware] = []
def make(version: str, *, is_target: bool = True) -> Firmware:
row = Firmware(
version=version,
file_path=f"/srv/poorbird/fw/{version}.bin",
sha256="a" * 64,
size_bytes=1148320,
is_target=is_target,
)
db.add(row)
db.commit()
db.refresh(row)
created.append(row)
return row
yield make
for row in created:
existing = db.get(Firmware, row.id)
if existing is not None:
db.delete(existing)
db.commit()
def body(reason: str = "periodic", **over) -> dict:
b = {
"reason": reason,
"fw_version": "0.1.0",
"config_version": 8,
"power": {"awake_ms": 91204, "boot_count": 37, "wake_cause": "radar"},
"battery": {"valid": True, "mv": 3912, "pct": 74},
"counters": {"captured_today": 412, "delivered_today": 407, "day_index": 20716},
"camera": {"profile": "day", "ready": True},
"night": {"is_night": False},
"stream": {"active": False},
"radar": {"baud": 256000, "uart_ok": True},
"system": {"rssi": -61, "ip": "192.168.1.88", "free_heap": 184320},
"time_synced": True,
"device_time": "2026-09-20T14:31:07Z",
}
b.update(over)
return b
# --- the split between the two endpoints ------------------------------------
@needs_db
def test_heartbeat_returns_the_envelope(client, device):
_, auth = device
r = client.post("/api/v1/heartbeat", json=body(), headers=auth)
assert r.status_code == 200
e = r.json()
assert e["server_time"] > 1_700_000_000_000
assert "config_version" in e
assert e["commands"] == []
@needs_db
def test_status_returns_204_and_no_body(client, device):
_, auth = device
r = client.post("/api/v1/status", json=body("before_sleep"), headers=auth)
assert r.status_code == 204
assert r.content == b""
@needs_db
def test_status_does_not_hand_out_commands(client, device, db):
"""The whole reason the two endpoints exist.
The device posts status immediately before deep sleep. Delivering commands
there would mark them delivered to a device about to be unable to run them.
"""
d, auth = device
db.add(DeviceCommand(device_id=d.id, type="capture_now"))
db.commit()
assert client.post("/api/v1/status", json=body("before_sleep"), headers=auth).status_code == 204
cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id))
db.refresh(cmd)
assert cmd.delivered_at is None, "status must not claim commands"
# ... but the next heartbeat still gets it.
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert [c["type"] for c in e["commands"]] == ["capture_now"]
# --- commands ---------------------------------------------------------------
@needs_db
def test_heartbeat_claims_commands_and_marks_them_delivered(client, device, db):
d, auth = device
db.add(DeviceCommand(device_id=d.id, type="reboot"))
db.commit()
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert [c["type"] for c in e["commands"]] == ["reboot"]
cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id))
db.refresh(cmd)
assert cmd.delivered_at is not None
# Not handed out twice.
again = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert again["commands"] == []
@needs_db
def test_expired_commands_are_not_delivered_but_are_kept(client, device, db):
"""Kept so the admin UI can show that a command timed out."""
d, auth = device
db.add(
DeviceCommand(
device_id=d.id,
type="capture_now",
expires_at=datetime.now(UTC) - timedelta(minutes=1),
)
)
db.commit()
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert e["commands"] == []
assert db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) is not None
@needs_db
def test_commands_come_back_in_creation_order(client, device, db):
d, auth = device
for t in ("wake_and_hold", "capture_now", "reboot"):
db.add(DeviceCommand(device_id=d.id, type=t))
db.commit() # distinct created_at
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert [c["type"] for c in e["commands"]] == ["wake_and_hold", "capture_now", "reboot"]
@needs_db
def test_one_devices_commands_do_not_leak_to_another(client, device, db):
d, auth = device
other = Device(device_uid=secrets.token_hex(6), name="other")
db.add(other)
db.commit()
db.add(DeviceCommand(device_id=other.id, type="reboot"))
db.commit()
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert e["commands"] == []
db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == other.id))
db.delete(db.get(Device, other.id))
db.commit()
# --- firmware target --------------------------------------------------------
@needs_db
def test_firmware_key_is_absent_when_the_device_is_on_target(client, device, firmware):
"""Absent, not null: present-and-different is itself the flash instruction."""
d, auth = device
firmware("0.1.0") # same version the device reports
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert "firmware" not in e
@needs_db
def test_a_different_target_is_offered_with_a_relative_url(client, device, firmware):
"""ota_mgr.cpp appends a non-http url to the API base, which already ends
in /api/v1 -- so this must not carry the prefix itself."""
d, auth = device
firmware("0.2.0")
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert e["firmware"]["version"] == "0.2.0"
assert e["firmware"]["url"] == "/firmware/0.2.0.bin"
assert not e["firmware"]["url"].startswith("/api/v1")
assert e["firmware"]["size"] == 1148320
# --- telemetry recording ----------------------------------------------------
@needs_db
def test_a_row_is_appended_per_report(client, device, db):
d, auth = device
client.post("/api/v1/heartbeat", json=body(), headers=auth)
client.post("/api/v1/status", json=body("after_event"), headers=auth)
rows = db.scalars(
select(DeviceStatus).where(DeviceStatus.device_id == d.id).order_by(DeviceStatus.at)
).all()
assert [r.reason for r in rows] == ["periodic", "after_event"]
assert rows[0].battery_mv == 3912
assert rows[0].rssi == -61
assert rows[0].day_index == 20716
assert rows[0].free_heap == 184320
@needs_db
def test_unknown_fields_survive_in_raw(client, device, db):
d, auth = device
client.post("/api/v1/heartbeat", json=body(quantum_flux=42), headers=auth)
row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id))
assert row.raw["quantum_flux"] == 42
@needs_db
def test_last_known_conditions_are_denormalised_onto_the_device(client, device, db):
d, auth = device
client.post("/api/v1/heartbeat", json=body(), headers=auth)
db.refresh(d)
assert d.battery_mv == 3912
assert d.battery_pct == 74
assert d.battery_valid is True
assert d.rssi == -61
assert d.last_seen_at is not None
@needs_db
def test_a_field_the_device_omits_does_not_erase_the_last_good_value(client, device, db):
"""None means 'not sent', not 'zero'."""
d, auth = device
client.post("/api/v1/heartbeat", json=body(), headers=auth)
client.post("/api/v1/heartbeat", json=body(battery={}, system={}), headers=auth)
db.refresh(d)
assert d.battery_mv == 3912
assert d.rssi == -61
@needs_db
def test_battery_valid_false_is_recorded_as_false(client, device, db):
"""false means NOT MEASURED. It must reach the UI as false, not as missing."""
d, auth = device
client.post("/api/v1/heartbeat", json=body(battery={"valid": False}), headers=auth)
db.refresh(d)
assert d.battery_valid is False
row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id))
assert row.battery_valid is False
@needs_db
def test_the_device_is_marked_asleep_when_it_says_it_is_going_quiet(client, device, db):
d, auth = device
client.post("/api/v1/heartbeat", json=body(), headers=auth)
db.refresh(d)
assert d.awake is True
client.post("/api/v1/status", json=body("before_night_sleep"), headers=auth)
db.refresh(d)
assert d.awake is False
@needs_db
def test_the_devices_reported_config_version_does_not_overwrite_the_servers(client, device, db):
"""The difference between the two is exactly what tells the device to
GET /config. Letting the report win would erase the instruction."""
d, auth = device
d.config_version = 9
db.commit()
e = client.post("/api/v1/heartbeat", json=body(config_version=3), headers=auth).json()
db.refresh(d)
assert d.config_version == 9
assert e["config_version"] == 9
row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id))
assert row.config_version == 3 # what the device said, kept as telemetry
# --- auth -------------------------------------------------------------------
@needs_db
@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"])
def test_both_endpoints_require_a_bearer_token(client, path):
assert client.post(path, json=body()).status_code == 401
@needs_db
@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"])
def test_a_disabled_device_is_refused(client, device, db, path):
d, auth = device
d.enabled = False
db.commit()
assert client.post(path, json=body(), headers=auth).status_code == 403
@needs_db
@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"])
def test_an_unknown_reason_is_422(client, device, path):
_, auth = device
assert client.post(path, json=body("whenever"), headers=auth).status_code == 422