Files
Hello/server/tests/test_conditions.py
T
Thomas KarnerandClaude Opus 5 5fd3c094a4 Add POST /heartbeat and POST /status, and the shared envelope (Phase 2)
One body, two endpoints. The firmware builds the conditions payload once, in
buildConditions, and posts it to both; they differ only in the response.

  /heartbeat -> 200 and the envelope: commands, config version, firmware
  /status    -> 204 and nothing

The split is not cosmetic and is now pinned by a test. The device posts
status immediately before deep sleep, so delivering commands there would mark
them delivered to a device about to be unable to run them.

api/envelope.py holds the shared builder, because /ingest returns the same
shape and parseEnvelope handles both with one function - they must not drift.

  - Commands are marked delivered when handed over, not on ack: the ack may
    never come, since the device runs reboot and sleep_now and is gone.
    acked_at stays the separate, later signal that it actually ran.
  - Expired commands are skipped but left in place, so the admin UI can show
    that a command timed out rather than silently losing it. The worker's
    prune job is what removes them.
  - The firmware URL is deliberately relative. ota_mgr.cpp:86 appends any
    non-http url to the API base, which already ends in /api/v1, so
    /firmware/0.2.0.bin resolves to /api/v1/firmware/0.2.0.bin.
  - Being on target means the firmware key is absent, not null: naming a
    different version is itself the instruction to flash (main.cpp:104).

Recording conditions appends a device_status row and refreshes the
denormalised columns on devices. Three details worth stating:

  - A field the device omits does not erase the last good value. None means
    not sent, not zero.
  - battery.valid false means NOT MEASURED and is stored as false, so the UI
    renders an em dash instead of inventing a low-battery alarm.
  - The device's reported config_version never overwrites the server's. The
    difference between them is exactly what tells the device to GET /config.

Tests: 77 -> 99. Verified by making /status build the envelope: the contract
test fails, as intended.

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

351 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()
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, db):
"""Absent, not null: present-and-different is itself the flash instruction."""
d, auth = device
fw = Firmware(
version="0.1.0", # same as the device
file_path="/srv/poorbird/fw/0.1.0.bin",
sha256="a" * 64,
size_bytes=1148320,
is_target=True,
)
db.add(fw)
db.commit()
e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json()
assert "firmware" not in e
db.delete(db.get(Firmware, fw.id))
db.commit()
@needs_db
def test_a_different_target_is_offered_with_a_relative_url(client, device, db):
"""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
fw = Firmware(
version="0.2.0",
file_path="/srv/poorbird/fw/0.2.0.bin",
sha256="b" * 64,
size_bytes=1148320,
is_target=True,
)
db.add(fw)
db.commit()
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
db.delete(db.get(Firmware, fw.id))
db.commit()
# --- 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