test_archive_updated_scope.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Live archive updates reach only sockets that may see the archive's printer."""
  2. from __future__ import annotations
  3. from types import SimpleNamespace
  4. from unittest.mock import AsyncMock, patch
  5. import pytest
  6. from backend.app.core import websocket
  7. from backend.app.core.printer_scope import PrinterScope
  8. pytestmark = pytest.mark.asyncio
  9. def _socket(printer_ids):
  10. scope = PrinterScope() if printer_ids is None else PrinterScope(frozenset(printer_ids))
  11. return SimpleNamespace(state=SimpleNamespace(bambuddy_printer_scope=scope), send_text=AsyncMock())
  12. @pytest.mark.parametrize(
  13. ("archive_printer", "expected"),
  14. [
  15. (1, {"team_a": True, "team_b": False, "everyone": True}),
  16. (None, {"team_a": True, "team_b": True, "everyone": True}), # printer-less: in every scope
  17. (websocket._UNKNOWN_PRINTER, {"team_a": False, "team_b": False, "everyone": True}),
  18. ],
  19. )
  20. async def test_an_update_follows_the_archive_printer(archive_printer, expected):
  21. manager = websocket.ConnectionManager()
  22. sockets = {"team_a": _socket({1}), "team_b": _socket({2}), "everyone": _socket(None)}
  23. manager.active_connections = list(sockets.values())
  24. with patch.object(websocket, "_archive_printer_id", new=AsyncMock(return_value=archive_printer)):
  25. await manager.send_archive_updated({"id": 7, "cost": 1.5})
  26. assert {name: s.send_text.await_count == 1 for name, s in sockets.items()} == expected
  27. async def test_an_archive_that_cannot_be_looked_up_reaches_only_unrestricted_sockets():
  28. with patch("backend.app.core.database.async_session", side_effect=RuntimeError("db down")):
  29. assert await websocket._archive_printer_id(7) == websocket._UNKNOWN_PRINTER
  30. assert await websocket._archive_printer_id(None) == websocket._UNKNOWN_PRINTER