49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
import asyncio
|
|
|
|
from starlette.websockets import WebSocketState
|
|
|
|
import euniv.study_push as study_push
|
|
|
|
|
|
class _Socket:
|
|
client_state = WebSocketState.CONNECTED
|
|
|
|
def __init__(self) -> None:
|
|
self.payloads: list[dict] = []
|
|
|
|
async def send_json(self, payload: dict) -> None:
|
|
self.payloads.append(payload)
|
|
|
|
|
|
def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
|
|
socket = _Socket()
|
|
monkeypatch.setattr("euniv.study_control.payload_for", lambda eid: {"eid": eid, "n": len(socket.payloads)})
|
|
|
|
async def main() -> None:
|
|
study_push._pending.clear()
|
|
study_push._inflight.clear()
|
|
study_push._dirty.clear()
|
|
study_push._urgent.clear()
|
|
study_push._last_flush.clear()
|
|
study_push._latest.clear()
|
|
study_push._clients.clear()
|
|
study_push.attach_loop(asyncio.get_running_loop())
|
|
study_push.register("u1", socket)
|
|
try:
|
|
study_push.notify("u1")
|
|
await asyncio.sleep(0.05)
|
|
assert len(socket.payloads) == 1
|
|
study_push.notify("u1")
|
|
await asyncio.sleep(0.05)
|
|
assert len(socket.payloads) == 1
|
|
study_push.notify("u1", urgent=True)
|
|
await asyncio.sleep(0.05)
|
|
assert len(socket.payloads) == 2
|
|
assert study_push.latest_of("u1") == socket.payloads[-1]
|
|
finally:
|
|
for handle in list(study_push._pending.values()):
|
|
handle.cancel()
|
|
study_push.unregister("u1", socket)
|
|
|
|
asyncio.run(main())
|