import json import pytest from apps.notifications.api.views import NotificationStreamView from apps.notifications.services import RedisNotificationStore pytestmark = pytest.mark.unit def test_sse_stream_sends_snapshot_update_and_closes_pubsub(mocker, settings): settings.NOTIFICATION_SSE_HEARTBEAT_SECONDS = 60 pubsub = mocker.Mock() pubsub.get_message.side_effect = [{"type": "message", "data": json.dumps({"event": "notification", "data": {"id": "one"}})}] mocker.patch("apps.notifications.api.views.RedisNotificationStore.get_pubsub", return_value=pubsub) mocker.patch("apps.notifications.api.views.RedisNotificationStore.list", return_value=([{"id": "one"}], 1)) mocker.patch("apps.notifications.api.views.RedisNotificationStore.unread_count", return_value=1) mocker.patch("apps.notifications.api.views.RedisNotificationStore.summary", return_value={"id": "one"}) stream = NotificationStreamView()._build_stream("42") assert next(stream).startswith("retry:") assert "connected" in next(stream) assert "unread_count" in next(stream) assert '"id": "one"' in next(stream) stream.close() pubsub.subscribe.assert_called_once_with(RedisNotificationStore._channel_key("42")) pubsub.unsubscribe.assert_called_once() pubsub.close.assert_called_once()