Initial commit with webpage
This commit is contained in:
commit
26875de1dd
55 files changed
+5726
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
# Point the app at a throwaway database before any app module is imported:
|
||||
# a temp SQLite file, or TEST_DATABASE_URL to run the suite against Postgres.
|
||||
# Never point TEST_DATABASE_URL at real data: every test empties the tables.
|
||||
_TMP = Path(tempfile.mkdtemp(prefix="mamadachi-test-"))
|
||||
os.environ["DATABASE_URL"] = os.environ.get("TEST_DATABASE_URL") or f"sqlite:///{(_TMP / 'test.db').as_posix()}"
|
||||
os.environ["DASHBOARD_PASSWORD"] = ""
|
||||
os.environ["DEFAULT_TIMEZONE"] = "America/New_York"
|
||||
os.environ["APP_ENV"] = "development"
|
||||
|
||||
import pytest # noqa: E402
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
from sqlalchemy import delete # noqa: E402
|
||||
|
||||
from app.config import get_settings # noqa: E402
|
||||
from app.db import SessionLocal # noqa: E402
|
||||
from app.main import app # noqa: E402
|
||||
from app.models import ButtonMap, Device, DeviceReport, Event, Kind, Press, Profile # noqa: E402
|
||||
from app.services.catalog import ensure_defaults # noqa: E402
|
||||
from app.services.ingest import create_device # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def _app_started():
|
||||
with TestClient(app) as c: # runs startup: migrations + defaults
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
s = SessionLocal()
|
||||
yield s
|
||||
s.close()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_db(_app_started):
|
||||
"""Every test starts from an empty log and default settings."""
|
||||
with SessionLocal() as s:
|
||||
for model in (Press, Event, DeviceReport, Device, ButtonMap, Kind, Profile):
|
||||
s.execute(delete(model))
|
||||
s.commit()
|
||||
ensure_defaults(s)
|
||||
settings = get_settings()
|
||||
saved = settings.dashboard_password
|
||||
yield
|
||||
settings.dashboard_password = saved
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(_app_started):
|
||||
# Fresh cookies for each test; the app itself stays started.
|
||||
with TestClient(app, base_url="http://testserver") as c:
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def device(db):
|
||||
dev, token = create_device(db, "Test Mamadachi")
|
||||
return dev, token
|
||||
|
||||
|
||||
def auth(token: str) -> dict:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Catches "edited models.py but forgot the migration"."""
|
||||
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
|
||||
from app.db import engine
|
||||
from app.models import Base, alembic_compare_type
|
||||
|
||||
|
||||
def test_migrations_match_models(_app_started):
|
||||
with engine.connect() as conn:
|
||||
ctx = MigrationContext.configure(conn, opts={"compare_type": alembic_compare_type})
|
||||
diff = compare_metadata(ctx, Base.metadata)
|
||||
assert diff == [], f"Models and migrations differ; run: alembic revision --autogenerate\n{diff}"
|
||||
@@ -0,0 +1,120 @@
|
||||
"""The numbers on the dashboard."""
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app.charts import nice_ticks
|
||||
from app.models import Kind
|
||||
from app.services import events as ev_svc
|
||||
from app.services.catalog import battery_percent, get_profile
|
||||
from app.services.stats import build_summary, daily_stats, group_feeds, next_side
|
||||
from app.timeutil import baby_age, local_day_start, safe_zone, utcnow
|
||||
|
||||
NY = safe_zone("America/New_York")
|
||||
|
||||
|
||||
def at(d: date, hour: int, minute: int = 0) -> datetime:
|
||||
return local_day_start(d, NY) + timedelta(hours=hour, minutes=minute)
|
||||
|
||||
|
||||
def press(db, slug, when):
|
||||
ev, _ = ev_svc.apply_press(db, db.get(Kind, slug), when, source="manual")
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def test_left_then_right_is_one_feed(db):
|
||||
d = date(2026, 10, 1)
|
||||
press(db, "nurse_left", at(d, 10))
|
||||
press(db, "nurse_right", at(d, 10, 15))
|
||||
press(db, "bottle", at(d, 13))
|
||||
feeds = group_feeds(ev_svc.events_between(db, at(d, 0), at(d, 23)))
|
||||
assert len(feeds) == 2
|
||||
assert feeds[0].sides == ["L", "R"]
|
||||
assert feeds[0].label == "Nursing L → R"
|
||||
assert next_side(feeds) == "R" # last nursing feed started on the left
|
||||
|
||||
|
||||
def test_sleep_across_midnight_counts_toward_both_days(db):
|
||||
d = date(2026, 10, 1)
|
||||
press(db, "sleep", at(d, 22))
|
||||
press(db, "sleep", at(d + timedelta(days=1), 6))
|
||||
days = daily_stats(db, NY, d, d + timedelta(days=1), now=at(d + timedelta(days=2), 0))
|
||||
assert [round(x.sleep_min) for x in days] == [120, 360]
|
||||
assert days[0].longest_sleep_min == 480
|
||||
assert days[0].naps == 1
|
||||
|
||||
|
||||
def test_dst_day_is_25_hours(db):
|
||||
# US clocks fall back on 2026-11-01, so that local day lasts 25 h.
|
||||
d = date(2026, 11, 1)
|
||||
midnight = at(d, 0)
|
||||
for start, end in [(0, 11), (13, 25)]: # hours after midnight, real elapsed time
|
||||
press(db, "sleep", midnight + timedelta(hours=start))
|
||||
press(db, "sleep", midnight + timedelta(hours=end) - timedelta(minutes=1))
|
||||
days = daily_stats(db, NY, d, d, now=midnight + timedelta(days=2))
|
||||
assert round(days[0].sleep_min) == 11 * 60 - 1 + 12 * 60 - 1 # nothing clipped at hour 24
|
||||
|
||||
|
||||
def test_forgotten_sleep_is_capped_and_flagged(db):
|
||||
now = utcnow()
|
||||
ev = press(db, "sleep", now - timedelta(hours=20))
|
||||
assert ev_svc.effective_end(ev, now) == ev.started_at + timedelta(hours=12)
|
||||
assert ev_svc.is_stale(ev, now)
|
||||
s = build_summary(db, get_profile(db), now)
|
||||
assert s.sleeping is None # a stale session doesn't count as asleep
|
||||
assert any("never stopped" in a.text for a in s.alerts)
|
||||
|
||||
|
||||
def test_counts_for_today(db):
|
||||
now = utcnow()
|
||||
for minutes in (10, 20, 30):
|
||||
press(db, "wet", now - timedelta(minutes=minutes))
|
||||
press(db, "dirty", now - timedelta(minutes=5))
|
||||
s = build_summary(db, get_profile(db), now)
|
||||
assert (s.today.wet, s.today.dirty) == (3, 1)
|
||||
assert s.last_diaper.kind_slug == "dirty"
|
||||
|
||||
|
||||
def test_deleted_events_are_ignored(db):
|
||||
now = utcnow()
|
||||
ev = press(db, "wet", now - timedelta(minutes=10))
|
||||
ev_svc.delete_event(db, ev)
|
||||
assert build_summary(db, get_profile(db), now).today.wet == 0
|
||||
ev_svc.restore_event(db, ev)
|
||||
assert build_summary(db, get_profile(db), now).today.wet == 1
|
||||
|
||||
|
||||
def test_manual_event_validation(db):
|
||||
sleep = db.get(Kind, "sleep")
|
||||
now = utcnow()
|
||||
with pytest.raises(ev_svc.EventError):
|
||||
ev_svc.create_manual(db, sleep, now + timedelta(hours=2), None, None)
|
||||
with pytest.raises(ev_svc.EventError):
|
||||
ev_svc.create_manual(db, sleep, now - timedelta(hours=1), now - timedelta(hours=2), None)
|
||||
with pytest.raises(ev_svc.EventError):
|
||||
ev_svc.create_manual(db, db.get(Kind, "wet"), now - timedelta(hours=1), now, None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mv", "pct"),
|
||||
[(None, None), (4250, 100), (4200, 100), (3840, 50), (3700, 12), (3270, 0), (3000, 0)],
|
||||
)
|
||||
def test_battery_percent(mv, pct):
|
||||
assert battery_percent(mv) == pct
|
||||
|
||||
|
||||
def test_nice_ticks():
|
||||
assert nice_ticks(8, integer=True) == [0, 5, 10]
|
||||
assert nice_ticks(3, integer=True) == [0, 1, 2, 3]
|
||||
assert nice_ticks(0, integer=True) == [0, 1]
|
||||
assert nice_ticks(16.8, integer=False) == [0, 10, 20]
|
||||
|
||||
|
||||
def test_baby_age():
|
||||
born = date(2026, 9, 1)
|
||||
assert baby_age(born, date(2026, 9, 6)) == "5 days old"
|
||||
assert baby_age(born, date(2026, 10, 16)) == "6 weeks 3 days"
|
||||
assert baby_age(born, date(2027, 3, 1)) == "6 months"
|
||||
assert baby_age(None, date(2026, 10, 16)) == ""
|
||||
@@ -0,0 +1,165 @@
|
||||
"""The device API: the part the firmware depends on."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.models import Event, Press
|
||||
from app.timeutil import unix, utcnow
|
||||
from tests.conftest import auth
|
||||
|
||||
URL = "/api/v1/device/sync"
|
||||
|
||||
|
||||
def sync(client, token, events, device_time=None, **extra):
|
||||
body = {"device_time": device_time if device_time is not None else unix(utcnow()), "events": events, **extra}
|
||||
return client.post(URL, json=body, headers=auth(token))
|
||||
|
||||
|
||||
def test_needs_a_valid_token(client, device):
|
||||
assert client.post(URL, json={"events": []}).status_code == 401
|
||||
assert client.post(URL, json={"events": []}, headers=auth("mmd_wrong")).status_code == 401
|
||||
assert sync(client, device[1], []).status_code == 200
|
||||
|
||||
|
||||
def test_revoked_device_is_rejected(client, db, device):
|
||||
dev, token = device
|
||||
dev.revoked_at = utcnow()
|
||||
db.commit()
|
||||
assert sync(client, token, []).status_code == 401
|
||||
|
||||
|
||||
def test_stores_presses_once(client, db, device):
|
||||
_, token = device
|
||||
t = unix(utcnow() - timedelta(hours=1))
|
||||
events = [
|
||||
{"seq": 1, "time": t, "button": 4},
|
||||
{"seq": 2, "time": t + 60, "button": 5},
|
||||
{"seq": 3, "time": t + 120, "button": 3},
|
||||
]
|
||||
r = sync(client, token, events, battery_mv=3950, rssi=-60, firmware="0.1.0")
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert (body["received"], body["stored"], body["duplicates"], body["ack_seq"]) == (3, 3, 0, 3)
|
||||
|
||||
# The response got lost and the device retries the same batch: nothing doubles.
|
||||
r2 = sync(client, token, events)
|
||||
assert (r2.json()["stored"], r2.json()["duplicates"]) == (0, 3)
|
||||
assert db.scalar(select(func.count()).select_from(Event)) == 3
|
||||
assert db.scalar(select(func.count()).select_from(Press)) == 3
|
||||
|
||||
|
||||
def test_seq_counter_reset_is_not_mistaken_for_a_retry(client, db, device):
|
||||
_, token = device
|
||||
t = unix(utcnow() - timedelta(hours=2))
|
||||
sync(client, token, [{"seq": 1, "time": t, "button": 4}])
|
||||
# Reflashed device: counter starts at 1 again, but it's a new press.
|
||||
r = sync(client, token, [{"seq": 1, "time": t + 3600, "button": 4}])
|
||||
assert r.json()["stored"] == 1
|
||||
assert db.scalar(select(func.count()).select_from(Event)) == 2
|
||||
|
||||
|
||||
def test_sleep_presses_pair_into_one_session(client, db, device):
|
||||
_, token = device
|
||||
t = unix(utcnow() - timedelta(hours=3))
|
||||
r = sync(client, token, [{"seq": 1, "time": t, "button": 6}, {"seq": 2, "time": t + 5400, "button": 6}])
|
||||
assert r.json()["stored"] == 2
|
||||
sleeps = db.scalars(select(Event).where(Event.kind_slug == "sleep")).all()
|
||||
assert len(sleeps) == 1
|
||||
assert sleeps[0].duration == timedelta(minutes=90)
|
||||
roles = [p.role for p in db.scalars(select(Press).order_by(Press.seq))]
|
||||
assert roles == ["start", "end"]
|
||||
|
||||
|
||||
def test_sleep_start_and_stop_in_separate_syncs(client, db, device):
|
||||
_, token = device
|
||||
t = unix(utcnow() - timedelta(hours=3))
|
||||
sync(client, token, [{"seq": 1, "time": t, "button": 6}])
|
||||
body = sync(client, token, []).json()
|
||||
assert [o["kind"] for o in body["status"]["open"]] == ["sleep"]
|
||||
sync(client, token, [{"seq": 2, "time": t + 3600, "button": 6}])
|
||||
ev = db.scalars(select(Event)).one()
|
||||
assert ev.duration == timedelta(hours=1)
|
||||
|
||||
|
||||
def test_forgotten_stop_starts_a_new_session(client, db, device):
|
||||
_, token = device
|
||||
t = unix(utcnow() - timedelta(hours=20))
|
||||
# 13 h later is past sleep's 12 h auto-close, so this is a new nap, not a 13 h one.
|
||||
sync(client, token, [{"seq": 1, "time": t, "button": 6}, {"seq": 2, "time": t + 13 * 3600, "button": 6}])
|
||||
sleeps = db.scalars(select(Event).order_by(Event.started_at)).all()
|
||||
assert len(sleeps) == 2
|
||||
assert all(s.ended_at is None for s in sleeps)
|
||||
|
||||
|
||||
def test_wrong_device_clock_is_corrected(client, db, device):
|
||||
_, token = device
|
||||
real_now = utcnow()
|
||||
device_now = real_now - timedelta(days=1) # RTC lost a day
|
||||
pressed = device_now - timedelta(hours=1)
|
||||
r = sync(client, token, [{"seq": 1, "time": unix(pressed), "button": 4}], device_time=unix(device_now))
|
||||
body = r.json()
|
||||
assert body["clock_corrected"] is True
|
||||
assert abs(body["clock_skew_s"] - 86400) < 5
|
||||
assert abs(body["server_time"] - unix(real_now)) < 5
|
||||
ev = db.scalars(select(Event)).one()
|
||||
assert ev.clock_corrected
|
||||
assert abs((ev.started_at - (real_now - timedelta(hours=1))).total_seconds()) < 5
|
||||
|
||||
|
||||
def test_small_clock_drift_is_left_alone(client, db, device):
|
||||
_, token = device
|
||||
now = utcnow()
|
||||
pressed = unix(now - timedelta(minutes=30))
|
||||
r = sync(client, token, [{"seq": 1, "time": pressed, "button": 4}], device_time=unix(now) - 30)
|
||||
assert r.json()["clock_corrected"] is False
|
||||
assert unix(db.scalars(select(Event)).one().started_at) == pressed
|
||||
|
||||
|
||||
def test_unassigned_button_is_kept_not_dropped(client, db, device):
|
||||
_, token = device
|
||||
r = sync(client, token, [{"seq": 1, "time": unix(utcnow()) - 60, "button": 9}])
|
||||
assert r.status_code == 200
|
||||
ev = db.scalars(select(Event)).one()
|
||||
assert ev.kind_slug == "other"
|
||||
assert "Button 9" in ev.note
|
||||
|
||||
|
||||
def test_response_tells_the_device_what_to_show(client, device):
|
||||
_, token = device
|
||||
t = unix(utcnow() - timedelta(minutes=40))
|
||||
body = sync(client, token, [{"seq": 1, "time": t, "button": 1}, {"seq": 2, "time": t + 300, "button": 4}]).json()
|
||||
assert [b["kind"] for b in body["buttons"]] == [
|
||||
"nurse_left", "nurse_right", "bottle", "wet", "dirty", "sleep", "pump", "medicine",
|
||||
]
|
||||
assert body["buttons"][5]["mode"] == "duration"
|
||||
status = body["status"]
|
||||
assert status["last_feed"]["kind"] == "nurse_left"
|
||||
assert status["last_feed"]["time"] == t
|
||||
assert status["next_side"] == "R"
|
||||
assert status["last_diaper"]["short"] == "Wet"
|
||||
assert body["sync_interval_s"] == 3600
|
||||
assert body["tz_offset_s"] in (-4 * 3600, -5 * 3600) # America/New_York
|
||||
assert len(body["config_version"]) == 8
|
||||
|
||||
|
||||
def test_bad_payload_is_a_422(client, device):
|
||||
_, token = device
|
||||
r = client.post(URL, json={"events": [{"seq": 1, "time": 5, "button": -1}]}, headers=auth(token))
|
||||
assert r.status_code == 422
|
||||
r = client.post(URL, json={"events": [{"time": 5, "button": 1}]}, headers=auth(token))
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_telemetry_is_recorded(client, db, device):
|
||||
dev, token = device
|
||||
sync(client, token, [], battery_mv=3800, rssi=-70, charging=True, firmware="0.2.0", diag={"wake": "timer"})
|
||||
db.refresh(dev)
|
||||
assert (dev.battery_mv, dev.rssi, dev.charging, dev.firmware) == (3800, -70, True, "0.2.0")
|
||||
assert dev.last_seen_at is not None
|
||||
|
||||
|
||||
def test_config_endpoint(client, device):
|
||||
r = client.get("/api/v1/device/config", headers=auth(device[1]))
|
||||
assert r.status_code == 200
|
||||
assert r.json()["received"] == 0
|
||||
@@ -0,0 +1,171 @@
|
||||
"""The dashboard pages, its JSON API and the login gate."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.config import get_settings
|
||||
from app.demo import seed_demo
|
||||
from app.models import Event
|
||||
from app.timeutil import utcnow
|
||||
from tests.conftest import auth
|
||||
|
||||
|
||||
def test_every_page_renders_with_demo_data(client, db):
|
||||
seed_demo(db, days=3)
|
||||
ev_id = db.scalars(select(Event.id).limit(1)).one()
|
||||
for url in ["/", "/log", "/log?cat=sleep", "/log?before=2026-01-01", "/trends", "/trends?days=7",
|
||||
"/trends?days=30", "/device", "/settings", f"/events/{ev_id}"]:
|
||||
r = client.get(url)
|
||||
assert r.status_code == 200, url
|
||||
assert "Since last feed" in client.get("/").text
|
||||
|
||||
|
||||
def test_empty_database_renders(client):
|
||||
for url in ["/", "/log", "/trends", "/device", "/settings"]:
|
||||
assert client.get(url).status_code == 200, url
|
||||
|
||||
|
||||
def test_quick_log_then_undo(client, db):
|
||||
r = client.post("/quick", data={"kind": "wet", "next": "/"}, follow_redirects=False)
|
||||
assert r.status_code == 303
|
||||
ev = db.scalars(select(Event)).one()
|
||||
assert ev.source == "manual" and ev.kind_slug == "wet"
|
||||
|
||||
client.post(f"/events/{ev.id}/delete")
|
||||
db.refresh(ev)
|
||||
assert ev.deleted_at is not None
|
||||
client.post(f"/events/{ev.id}/restore")
|
||||
db.refresh(ev)
|
||||
assert ev.deleted_at is None
|
||||
|
||||
|
||||
def test_quick_log_toggles_sleep(client, db):
|
||||
client.post("/quick", data={"kind": "sleep"})
|
||||
assert db.scalars(select(Event)).one().ended_at is None
|
||||
client.post("/quick", data={"kind": "sleep"})
|
||||
db.expire_all()
|
||||
assert db.scalars(select(Event)).one().ended_at is not None
|
||||
|
||||
|
||||
def test_manual_event_uses_family_timezone(client, db):
|
||||
# 2026-10-01 13:05 in New York (EDT, UTC-4) is 17:05 UTC.
|
||||
client.post("/events", data={"kind": "bottle", "started_at": "2026-10-01T13:05", "note": "90 ml"})
|
||||
ev = db.scalars(select(Event)).one()
|
||||
assert ev.started_at.isoformat() == "2026-10-01T17:05:00+00:00"
|
||||
assert ev.note == "90 ml"
|
||||
|
||||
|
||||
def test_edit_event(client, db):
|
||||
client.post("/events", data={"kind": "sleep", "started_at": "2026-10-01T13:00"})
|
||||
ev = db.scalars(select(Event)).one()
|
||||
client.post(f"/events/{ev.id}", data={"kind": "sleep", "started_at": "2026-10-01T13:00",
|
||||
"ended_at": "2026-10-01T14:30", "note": ""})
|
||||
db.refresh(ev)
|
||||
assert ev.duration == timedelta(minutes=90)
|
||||
|
||||
|
||||
def test_button_layout_reaches_the_device(client, device):
|
||||
client.post("/settings/buttons", data={f"button_{n}": "wet" for n in range(1, 9)})
|
||||
body = client.get("/api/v1/device/config", headers=auth(device[1])).json()
|
||||
assert {b["kind"] for b in body["buttons"]} == {"wet"}
|
||||
|
||||
|
||||
def test_add_kind(client):
|
||||
client.post("/settings/kinds/new", data={"label": "Vitamin D", "category": "health", "emoji": "☀️"})
|
||||
kinds = client.get("/api/v1/kinds").json()
|
||||
assert any(k["slug"] == "vitamin_d" and k["category"] == "health" for k in kinds)
|
||||
|
||||
|
||||
def test_register_device_shows_token_once(client):
|
||||
r = client.post("/device/new", data={"name": "Kitchen"})
|
||||
assert "mmd_" in r.text and "Kitchen" in r.text
|
||||
assert r.text.count("only once") == 1
|
||||
assert "mmd_" not in client.get("/device").text.replace("mmd_…", "")
|
||||
|
||||
|
||||
def test_json_api_crud(client):
|
||||
r = client.post("/api/v1/events", json={"kind": "wet"})
|
||||
assert r.status_code == 201
|
||||
eid = r.json()["id"]
|
||||
start = (utcnow() - timedelta(hours=2)).isoformat()
|
||||
r = client.patch(f"/api/v1/events/{eid}", json={"kind": "dirty", "started_at": start, "note": "big one"})
|
||||
assert r.json()["kind"] == "dirty" and r.json()["note"] == "big one"
|
||||
assert len(client.get("/api/v1/events?category=diaper").json()) == 1
|
||||
assert client.delete(f"/api/v1/events/{eid}").status_code == 204
|
||||
assert client.get("/api/v1/events").json() == []
|
||||
assert len(client.get("/api/v1/stats/daily?days=7").json()) == 7
|
||||
|
||||
|
||||
def test_api_rejects_naive_datetimes(client):
|
||||
r = client.post("/api/v1/events", json={"kind": "wet", "started_at": "2026-10-01T10:00:00"})
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_exports(client, db):
|
||||
seed_demo(db, days=1)
|
||||
csv = client.get("/api/v1/export.csv")
|
||||
assert csv.status_code == 200 and csv.text.startswith("id,date,start")
|
||||
backup = client.get("/api/v1/export.json").json()
|
||||
assert backup["format"] == "mamadachi-backup-1"
|
||||
assert backup["events"] and backup["presses"] and backup["device_reports"]
|
||||
assert "token_hash" not in str(backup)
|
||||
|
||||
|
||||
def test_password_gate(client):
|
||||
get_settings().dashboard_password = "hunter2"
|
||||
r = client.get("/", follow_redirects=False)
|
||||
assert r.status_code == 303 and r.headers["location"].startswith("/login")
|
||||
assert client.get("/api/v1/events").status_code == 401
|
||||
assert client.post("/login", data={"password": "nope"}).status_code == 401
|
||||
r = client.post("/login", data={"password": "hunter2", "next": "/trends"}, follow_redirects=False)
|
||||
assert r.headers["location"] == "/trends"
|
||||
assert client.get("/").status_code == 200
|
||||
assert client.get("/api/v1/events").status_code == 200
|
||||
|
||||
|
||||
def test_device_api_ignores_dashboard_password(client, device):
|
||||
get_settings().dashboard_password = "hunter2"
|
||||
r = client.post("/api/v1/device/sync", json={"events": []}, headers=auth(device[1]))
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_cross_site_form_post_is_blocked(client, db):
|
||||
r = client.post("/quick", data={"kind": "wet"}, headers={"Origin": "https://evil.example"})
|
||||
assert r.status_code == 403
|
||||
assert db.scalars(select(Event)).first() is None
|
||||
ok = client.post("/quick", data={"kind": "wet"}, headers={"Origin": "http://testserver"})
|
||||
assert ok.status_code == 200
|
||||
|
||||
|
||||
def test_health(client):
|
||||
assert client.get("/healthz").json()["ok"] is True
|
||||
assert client.get("/readyz").json()["database"] == "ok"
|
||||
|
||||
|
||||
def test_unknown_page_is_friendly(client):
|
||||
r = client.get("/nope", headers={"Accept": "text/html"})
|
||||
assert r.status_code == 404 and "Not found" in r.text
|
||||
|
||||
|
||||
def test_production_refuses_to_start_on_sqlite():
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
settings = get_settings()
|
||||
saved = (settings.app_env, settings.database_url)
|
||||
settings.app_env = "production"
|
||||
try:
|
||||
if settings.is_sqlite:
|
||||
with pytest.raises(RuntimeError, match="DATABASE_URL"):
|
||||
with TestClient(app):
|
||||
pass
|
||||
settings.database_url = "postgresql+psycopg://x@nowhere/db" # only checked, never connected
|
||||
settings.dashboard_password = "pw"
|
||||
with pytest.raises(RuntimeError, match="SECRET_KEY"):
|
||||
with TestClient(app):
|
||||
pass
|
||||
finally:
|
||||
settings.app_env, settings.database_url = saved
|
||||
Reference in new issue
Block a user