cmvr-visual/backend/tests/test_events.py

65 lines
3.1 KiB
Python

from sqlalchemy import select
from types import SimpleNamespace
import asyncio
async def test_empty_stream_immediately_sends_connection_comment(system):
from app.events import event_stream
system.settings.event_heartbeat_seconds = 15
owner = (await system.client.get("/api/auth/me")).json()["user"]["id"]
async def connected():
return False
request = SimpleNamespace(app=system.app, is_disconnected=connected)
stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0)
try:
assert await asyncio.wait_for(anext(stream), timeout=.1) == ": connected\n\n"
finally:
await stream.aclose()
async def test_durable_events_owner_replay_and_session_revocation(system, other_client):
from app.events import event_batch, session_is_active
job = (await system.client.post("/api/jobs", json={"task_type": "image.generate",
"input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0]
actor = (await system.client.get("/api/auth/me")).json()["user"]
other = (await other_client.get("/api/auth/me")).json()["user"]
events = await event_batch(system.app.state.db, actor["id"], 0)
assert events and events[-1]["data"]["job"]["id"] == job["id"]
assert await event_batch(system.app.state.db, other["id"], 0) == []
assert await event_batch(system.app.state.db, actor["id"], events[-1]["id"]) == []
token = system.client.cookies.get("cmvr_session")
assert await session_is_active(system.app.state.db, token)
assert (await system.client.post("/api/auth/logout")).status_code == 204
assert not await session_is_active(system.app.state.db, token)
async def test_real_stream_replays_ids_heartbeats_then_stops_after_logout(system):
from app.events import event_stream
await system.client.post("/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}})
owner = (await system.client.get("/api/auth/me")).json()["user"]["id"]
async def connected():
return False
request = SimpleNamespace(app=system.app, is_disconnected=connected)
stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0)
assert await anext(stream) == ": connected\n\n"
event = await anext(stream)
assert "event: job.updated" in event and "id: " in event
heartbeat = await asyncio.wait_for(anext(stream), timeout=1)
assert heartbeat == ": heartbeat\n\n"
await system.client.post("/api/auth/logout")
try:
await anext(stream)
assert False, "revoked sessions must stop SSE"
except StopAsyncIteration:
pass
async def test_http_eventsource_last_event_id_overrides_initial_query(system, monkeypatch):
import app.events as events
async def one_event(request, owner_id, token, after):
yield f"id: {after}\nevent: reset\ndata: {{}}\n\n"
monkeypatch.setattr(events, "event_stream", one_event)
response = await system.client.get("/api/events?after=2", headers={"Last-Event-ID": "19"})
assert response.status_code == 200 and response.text.startswith("id: 19\n")
assert response.headers["x-accel-buffering"] == "no"