Files
ledgrab/server/tests/test_preferences_notifications_api.py
T
alexei.dolgolyov 8aa3a323d6 feat(notifications): device event notifications (snack + Web Notifications)
Surface device connection state changes (configured target online/offline)
and discovery events (new WLED on LAN, new serial port, devices that
disappear) through a configurable per-event channel matrix:
none / snack / OS / both.

- Backend: long-running mDNS browser + 10 s serial poller in
  core/devices/discovery_watcher.py, gated by user pref. Reuses the
  existing device_health_changed event for online/offline transitions.
  New GET/PUT /api/v1/preferences/notifications endpoint with Pydantic v2
  schema (channel matrix + background-discovery flag + grace/debounce).
  13 new tests, full suite still 899 passing.
- Frontend: features/notifications-watcher.ts with startup-grace +
  flap-debounce + bulk-coalesce pipeline. Web Notifications API for the
  OS channel (no platform-specific code, works in PWA shell).
  New "Notifications" tab in Settings with 4 IconSelect rows + bg toggle
  + permission row + test button. en/ru/zh translations.

Defaults: device_offline=both (urgent), online/discovered=snack, lost=none,
background discovery on. Already-configured devices are filtered from
discovery events to avoid double-notifications.
2026-04-25 17:49:20 +03:00

121 lines
4.2 KiB
Python

"""Tests for /api/v1/preferences/notifications endpoints."""
import pytest
from ledgrab.config import get_config
@pytest.fixture(scope="module")
def client():
"""TestClient with auth header — same pattern as test_preferences_api.py."""
from fastapi.testclient import TestClient
from ledgrab.main import app
api_key = next(iter(get_config().auth.api_keys.values()), "")
with TestClient(app, raise_server_exceptions=False) as c:
if api_key:
c.headers["Authorization"] = f"Bearer {api_key}"
yield c
def _full_prefs() -> dict:
return {
"channels": {
"device_online": "snack",
"device_offline": "both",
"device_discovered": "os",
"device_lost": "none",
},
"background_discovery_enabled": True,
"startup_grace_sec": 15,
"flap_debounce_sec": 7,
}
def test_get_returns_defaults_when_unset(client):
"""When no prefs have been saved, GET returns the documented defaults."""
# Wipe via PUT to a known state to make this order-independent.
# (No DELETE endpoint — settings rows are scalar.)
resp = client.get("/api/v1/preferences/notifications")
assert resp.status_code == 200
body = resp.json()
assert body["background_discovery_enabled"] is True
assert body["startup_grace_sec"] == 10
assert body["flap_debounce_sec"] == 5
# Default channel matrix
assert body["channels"]["device_online"] == "snack"
assert body["channels"]["device_offline"] == "both"
assert body["channels"]["device_discovered"] == "snack"
assert body["channels"]["device_lost"] == "none"
def test_put_then_get_round_trips(client):
"""PUT a payload, GET it back unchanged."""
payload = _full_prefs()
put = client.put("/api/v1/preferences/notifications", json=payload)
assert put.status_code == 200
assert put.json()["startup_grace_sec"] == 15
got = client.get("/api/v1/preferences/notifications")
assert got.status_code == 200
assert got.json() == payload
def test_put_rejects_invalid_channel(client):
"""A bogus channel value (e.g. 'siren') is rejected by Pydantic."""
bad = _full_prefs()
bad["channels"]["device_offline"] = "siren"
resp = client.put("/api/v1/preferences/notifications", json=bad)
assert resp.status_code == 422
def test_put_rejects_grace_out_of_range(client):
"""startup_grace_sec is clamped to [0, 300]."""
bad = _full_prefs()
bad["startup_grace_sec"] = -5
assert client.put("/api/v1/preferences/notifications", json=bad).status_code == 422
bad["startup_grace_sec"] = 9999
assert client.put("/api/v1/preferences/notifications", json=bad).status_code == 422
def test_put_rejects_debounce_out_of_range(client):
"""flap_debounce_sec is clamped to [0, 60]."""
bad = _full_prefs()
bad["flap_debounce_sec"] = 999
assert client.put("/api/v1/preferences/notifications", json=bad).status_code == 422
def test_partial_payload_uses_defaults_for_omitted_channels(client):
"""Pydantic fills in default channels when the matrix is partial.
The frontend may want to PUT only what changed; the backend should
fill in the default channel matrix for omitted rows so we don't
silently lose user preferences via partial-write.
"""
partial = {"background_discovery_enabled": False}
resp = client.put("/api/v1/preferences/notifications", json=partial)
assert resp.status_code == 200
body = resp.json()
assert body["background_discovery_enabled"] is False
# Defaulted matrix is present
assert body["channels"]["device_offline"] == "both"
def test_corrupt_stored_value_falls_back_to_defaults(client):
"""If something stomps on the stored row, the GET handler must
return defaults instead of 500. Mirrors how load_shutdown_action
treats corrupt input."""
# Stuff garbage into the underlying setting via the same Database
# the route uses, then verify GET still works.
from ledgrab.api.dependencies import get_database
db = get_database()
db.set_setting("notification_preferences", {"channels": "totally-wrong"})
resp = client.get("/api/v1/preferences/notifications")
assert resp.status_code == 200
# Defaults restored
assert resp.json()["channels"]["device_offline"] == "both"