|
| 1 | +"""Behavioral checks for capture cleanup and durable-write ordering.""" |
| 2 | +import ast |
| 3 | +import asyncio |
| 4 | +import contextlib |
| 5 | +from datetime import datetime, timedelta, timezone |
| 6 | +from pathlib import Path |
| 7 | +from types import MethodType, SimpleNamespace |
| 8 | +from unittest.mock import AsyncMock |
| 9 | + |
| 10 | +ROOT = Path(__file__).resolve().parents[1] |
| 11 | +FRESH = b"\xff\xd8\xff" + b"f" * 1500 |
| 12 | +OLD = b"\xff\xd8\xff" + b"o" * 1500 |
| 13 | + |
| 14 | + |
| 15 | +def method(path, name, namespace): |
| 16 | + tree = ast.parse((ROOT / path).read_text()) |
| 17 | + node = next(n for n in ast.walk(tree) if isinstance(n, ast.AsyncFunctionDef) and n.name == name) |
| 18 | + node.decorator_list = [] |
| 19 | + exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), "exec"), namespace) |
| 20 | + return namespace[name] |
| 21 | + |
| 22 | + |
| 23 | +def test_capture_publishes_and_commits_after_cleanup_replays_old_picture(): |
| 24 | + async def exercise(): |
| 25 | + status = SimpleNamespace(IDLE="idle", STREAMING="streaming") |
| 26 | + ffmpeg = SimpleNamespace(async_get_image=AsyncMock(return_value=FRESH)) |
| 27 | + namespace = dict(asyncio=asyncio, contextlib=contextlib, datetime=datetime, |
| 28 | + timedelta=timedelta, timezone=timezone, ffmpeg=ffmpeg, StreamStatus=status, |
| 29 | + STREAM_TIMEOUT_SECONDS=1, FailedCommandException=RuntimeError, |
| 30 | + WebSocketConnectionException=ConnectionError, is_valid_snapshot=lambda b: b == FRESH) |
| 31 | + capture = method("custom_components/eufy_security/camera.py", "async_refresh_stale_snapshot", namespace) |
| 32 | + product = SimpleNamespace(commands=["start_livestream", "stop_livestream"], |
| 33 | + image_last_updated=datetime(2026, 1, 1, tzinfo=timezone.utc), |
| 34 | + properties={"picture": {"data": OLD}}, stream_status=status.IDLE, |
| 35 | + notify_state_update=lambda: None) |
| 36 | + order = [] |
| 37 | + async def start(): |
| 38 | + product.stream_status = status.STREAMING |
| 39 | + return True |
| 40 | + async def stop(): |
| 41 | + order.append("cleanup") |
| 42 | + product.stream_status = status.IDLE |
| 43 | + product.properties["picture"] = {"data": OLD} |
| 44 | + async def persist(value): |
| 45 | + assert value.properties["picture"]["data"] == FRESH |
| 46 | + assert value.stream_status == status.IDLE |
| 47 | + await asyncio.sleep(0) |
| 48 | + order.append("persisted") |
| 49 | + return True |
| 50 | + product.start_livestream = start |
| 51 | + product.stop_livestream = stop |
| 52 | + class Camera: |
| 53 | + @property |
| 54 | + def is_streaming(self): return product.stream_status == status.STREAMING |
| 55 | + camera = Camera() |
| 56 | + camera.product, camera.hass = product, object() |
| 57 | + camera._scheduled_snapshot_lock = asyncio.Lock() |
| 58 | + camera.coordinator = SimpleNamespace(async_persist_snapshot_capture=persist) |
| 59 | + camera.stream_source = AsyncMock(return_value="test-source") |
| 60 | + camera.async_update_token = lambda: order.append("token") |
| 61 | + camera.async_write_ha_state = lambda: order.append("published") |
| 62 | + assert await capture(camera, force=True) |
| 63 | + assert order == ["cleanup", "persisted", "token", "published"] |
| 64 | + assert product.properties["picture"]["data"] == FRESH |
| 65 | + assert product.snapshot_source == "explicit_live_capture" |
| 66 | + asyncio.run(exercise()) |
| 67 | + |
| 68 | + |
| 69 | +def test_capture_commit_waits_for_bytes_and_time_and_rejects_stale_or_retired_products(): |
| 70 | + async def exercise(): |
| 71 | + namespace = dict(asyncio=asyncio, product_snapshot_bytes=lambda d: d.picture_bytes) |
| 72 | + commit = method("custom_components/eufy_security/coordinator.py", "async_persist_snapshot_capture", namespace) |
| 73 | + now = datetime.now(timezone.utc) |
| 74 | + product = SimpleNamespace(serial_no="camera", picture_bytes=FRESH, image_last_updated=now) |
| 75 | + stored = [None] |
| 76 | + async def write(): |
| 77 | + await asyncio.sleep(0.01) |
| 78 | + stored[0] = (FRESH, {"updated_at": now.isoformat()}) |
| 79 | + coordinator = SimpleNamespace(devices={"camera": product}, |
| 80 | + _valid_snapshot=lambda b: b == FRESH, _snapshot_cache_dir="test-dir", |
| 81 | + _snapshot_cache_key=lambda serial: serial, |
| 82 | + _read_snapshot_record=lambda *_args: stored[0]) |
| 83 | + def schedule(): coordinator._snapshot_cache_task = asyncio.create_task(write()) |
| 84 | + coordinator._schedule_snapshot_cache_write = schedule |
| 85 | + assert await commit(coordinator, product) |
| 86 | + coordinator._schedule_snapshot_cache_write = lambda: setattr(coordinator, |
| 87 | + "_snapshot_cache_task", asyncio.create_task(asyncio.sleep(0))) |
| 88 | + stored[0] = (OLD, {"updated_at": now.isoformat()}) |
| 89 | + assert not await commit(coordinator, product) |
| 90 | + stored[0] = (FRESH, {"updated_at": "old"}) |
| 91 | + assert not await commit(coordinator, product) |
| 92 | + coordinator.devices["camera"] = object() |
| 93 | + assert not await commit(coordinator, product) |
| 94 | + asyncio.run(exercise()) |
0 commit comments