"""The gallery seed command (TODO 3.0). The scoping test here is the one that matters. ``poorbird seed --clear`` holds a DELETE over the same tables a real camera writes to, so the property worth pinning is not that it removes seeded rows -- it is that it removes *nothing else*. Counts are deliberately tiny. Each frame is a real 1600x1200 JPEG encode plus a thumbnail; the behaviour under test is the same at 8 as at 500, and the suite should not spend half a minute proving it. """ from __future__ import annotations import secrets import pytest from conftest import needs_db from sqlalchemy import func, select, text from poorbird.config import get_settings from poorbird.models import Capture, Device from poorbird.seed import BURST_MIN, SEED_UID_PREFIX, clear, generate, seed_device pytestmark = [pytest.mark.db, needs_db] @pytest.fixture def db(): from poorbird.db import SessionLocal with SessionLocal() as session: yield session @pytest.fixture(autouse=True) def no_seed_left_behind(db): """Remove seeded rows however the test ends. ``clear()`` is the subject of some of these tests, so it cannot be relied on as the teardown for all of them -- a broken clear() would then leave the database dirty *and* hide that it was broken. """ yield devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() for device in devices: db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device.id}) db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device.id}) db.commit() @pytest.fixture def real_device(db): """A device that is NOT seeded, with a capture, to prove clear() misses it.""" device = Device(device_uid=secrets.token_hex(6), name="real-camera", enabled=True) db.add(device) db.commit() db.refresh(device) capture = Capture( device_id=device.id, path="2026/09/20/real.jpg", sha256=secrets.token_hex(32), bytes=1234, trigger="radar", ) db.add(capture) db.commit() device_id = device.id yield device db.execute(text("DELETE FROM captures WHERE device_id = :i"), {"i": device_id}) db.execute(text("DELETE FROM devices WHERE id = :i"), {"i": device_id}) db.commit() def _seeded_captures(db, device: Device) -> list[Capture]: return list( db.scalars( select(Capture).where(Capture.device_id == device.id).order_by(Capture.frame_seq) ).all() ) # --- generating -------------------------------------------------------------- def test_it_makes_the_requested_number_of_captures(db): made = generate(db, count=6, days=3, device_name="t-seed", thumbnails=False, progress=False) assert made == 6 device = seed_device(db, "t-seed") assert len(_seeded_captures(db, device)) == 6 def test_the_count_is_exact_even_though_bursts_are_random_sized(db): """Bursts are 3-5 frames, so a naive loop overshoots. 7 is not a multiple of any burst size, which is the point of asking for it.""" made = generate(db, count=7, days=2, device_name="t-seed", thumbnails=False, progress=False) assert made == 7 assert len(_seeded_captures(db, seed_device(db, "t-seed"))) == 7 def test_the_frames_really_exist_on_disk(db): """A gallery whose rows point at missing files tests nothing about the delivery path, which is the half most likely to be wrong.""" generate(db, count=4, days=1, device_name="t-seed", thumbnails=False, progress=False) root = get_settings().image_root for capture in _seeded_captures(db, seed_device(db, "t-seed")): path = root / capture.path assert path.is_file(), f"missing {path}" assert path.read_bytes().startswith(b"\xff\xd8\xff"), "not a JPEG" assert capture.bytes == path.stat().st_size def test_thumbnails_are_generated_when_asked(db): generate(db, count=3, days=1, device_name="t-seed", thumbnails=True, progress=False) thumb_root = get_settings().thumb_root for capture in _seeded_captures(db, seed_device(db, "t-seed")): assert capture.thumb_path is not None thumb = thumb_root / capture.thumb_path assert thumb.is_file() # WebP, per SPEC 3.3. RIFF magic rather than trusting the extension. assert thumb.read_bytes()[:4] == b"RIFF" def test_without_thumbnails_the_worker_still_has_something_to_do(db): """--no-thumbnails is how the queue gets exercised at volume, so the rows must be left in exactly the state /ingest leaves them.""" generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) captures = _seeded_captures(db, seed_device(db, "t-seed")) assert captures assert all(c.thumb_path is None for c in captures) def test_frames_are_grouped_into_consistent_bursts(db): generate(db, count=8, days=2, device_name="t-seed", thumbnails=False, progress=False) captures = _seeded_captures(db, seed_device(db, "t-seed")) by_burst: dict[str, list[Capture]] = {} for capture in captures: by_burst.setdefault(capture.burst_id, []).append(capture) assert len(by_burst) >= 2, "8 frames should not be one burst" for frames in by_burst.values(): indexes = sorted(f.burst_index for f in frames) assert indexes == list(range(len(frames))), "burst_index must be dense from 0" # burst_count is what the device claims it sent, so every frame in a # burst has to agree on it. assert len({f.burst_count for f in frames}) == 1 def test_every_burst_has_pre_trigger_frames(db): """SPEC 0: the first frames come out of the PSRAM ring and are usually the good ones. A seed with none would hide whatever the UI does with them.""" generate(db, count=8, days=2, device_name="t-seed", thumbnails=False, progress=False) captures = _seeded_captures(db, seed_device(db, "t-seed")) by_burst: dict[str, list[Capture]] = {} for capture in captures: by_burst.setdefault(capture.burst_id, []).append(capture) assert by_burst for frames in by_burst.values(): assert any(f.pre_trigger for f in frames) # ...and not all of them, or the flag would carry no information. # Stated with its precondition: a single-frame burst is necessarily # all pre-trigger, so the generator is expected not to produce one. assert len(frames) >= BURST_MIN, "a burst this short is not something a camera sends" assert not all(f.pre_trigger for f in frames) def test_frames_in_a_burst_arrive_close_enough_to_tie(db): """The reason the gallery cursor carries the id as well as the timestamp. If the seed spread a burst over minutes, it would never reproduce the received_at collision that real bursts cause, and the paging bug that collision triggers would only ever appear against a real camera. """ generate(db, count=5, days=1, device_name="t-seed", thumbnails=False, progress=False) captures = _seeded_captures(db, seed_device(db, "t-seed")) by_burst: dict[str, list[Capture]] = {} for capture in captures: by_burst.setdefault(capture.burst_id, []).append(capture) burst = max(by_burst.values(), key=len) span = max(f.received_at for f in burst) - min(f.received_at for f in burst) assert span.total_seconds() < 5, "a burst should arrive within seconds, not minutes" def test_the_seed_device_cannot_authenticate(db): """It is a row for the gallery to point at, not a camera. Giving it a working token would be creating a real way in for test data's sake.""" device = seed_device(db, "t-seed") assert device.token_hash is None assert device.device_uid.startswith(SEED_UID_PREFIX) def test_seeding_twice_reuses_the_same_device(db): generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() assert len(devices) == 1 assert len(_seeded_captures(db, devices[0])) == 6 # --- clearing ---------------------------------------------------------------- def test_clear_removes_seeded_captures_and_the_device(db): generate(db, count=4, days=1, device_name="t-seed", thumbnails=True, progress=False) captures, devices = clear(db) assert captures == 4 assert devices == 1 assert ( db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all() == [] ) def test_clear_leaves_a_real_camera_completely_alone(db, real_device): """The property this command lives or dies by. It holds a DELETE over the same tables a real camera writes to. Scoping it by device_uid prefix is what makes that safe, and a change that widened the scope has to fail here rather than in someone's photo library. """ generate(db, count=4, days=1, device_name="t-seed", thumbnails=False, progress=False) before = db.scalar( select(func.count()).select_from(Capture).where(Capture.device_id == real_device.id) ) assert before == 1 clear(db) assert db.get(Device, real_device.id) is not None assert ( db.scalar( select(func.count()).select_from(Capture).where(Capture.device_id == real_device.id) ) == 1 ) def test_clear_deletes_the_files_too(db): """Otherwise the image root grows every time the seed is regenerated, and nothing ever points at the leftovers.""" generate(db, count=3, days=1, device_name="t-seed", thumbnails=True, progress=False) settings = get_settings() device = seed_device(db, "t-seed") paths = [ (settings.image_root / c.path, settings.thumb_root / c.thumb_path) for c in _seeded_captures(db, device) ] assert all(image.is_file() and thumb.is_file() for image, thumb in paths) clear(db) for image, thumb in paths: assert not image.exists(), f"left behind {image}" assert not thumb.exists(), f"left behind {thumb}" def test_clear_on_an_unseeded_database_is_not_an_error(db): assert clear(db) == (0, 0) def test_clear_removes_the_thumbnail_jobs_as_well(db): """A job pointing at a capture that no longer exists is not a failure -- the handler tolerates it -- but it is the worker waking up to do nothing and logging about it, which looks like a fault later.""" from poorbird.models import Job from poorbird.worker.queue import enqueue generate(db, count=3, days=1, device_name="t-seed", thumbnails=False, progress=False) device = seed_device(db, "t-seed") captures = _seeded_captures(db, device) for capture in captures: enqueue(db, "thumbnail", {"capture_id": str(capture.id)}) db.commit() ids = [str(c.id) for c in captures] assert ( db.scalar( select(func.count()).select_from(Job).where(Job.payload["capture_id"].astext.in_(ids)) ) == 3 ) clear(db) assert ( db.scalar( select(func.count()).select_from(Job).where(Job.payload["capture_id"].astext.in_(ids)) ) == 0 )