from types import SimpleNamespace from unittest.mock import AsyncMock, patch from uuid import uuid4 from asgiref.sync import sync_to_async from channels.layers import get_channel_layer from channels.testing import WebsocketCommunicator from django.apps import apps from django.contrib.auth import get_user_model from django.core.exceptions import ImproperlyConfigured from django.db import transaction from django.test import SimpleTestCase, TestCase, override_settings from notify.consumers import UserEventsConsumer from notify.models import DeliveryChannel, Notification from notify.realtime import publish, register_handlers, user_group_name, validate_configuration from notify.services import create_notification LAYERS = {"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}} @override_settings(CHANNEL_LAYERS=LAYERS, NOTIFY_REALTIME_ENABLED=True) class RealtimeSignalTests(TestCase): def setUp(self): apps.get_app_config("notify").ready() self.user = get_user_model().objects.create_user("alice") def create(self): return create_notification( title="Hello", recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], ) def test_registration_is_idempotent_and_events_wait_for_commit(self): register_handlers() register_handlers() with patch("notify.realtime.publish") as send: with self.captureOnCommitCallbacks(execute=True): notification = self.create() send.assert_not_called() self.assertEqual(send.call_count, 2) send.assert_any_call([self.user.pk], "notification.unread") send.assert_any_call( [self.user.pk], "notification.created", notification_id=notification.pk ) def test_rollback_does_not_publish(self): with patch("notify.realtime.publish") as send: with self.captureOnCommitCallbacks(execute=True): with self.assertRaises(RuntimeError), transaction.atomic(): self.create() raise RuntimeError("rollback") send.assert_not_called() @override_settings(NOTIFY_REALTIME_ENABLED=False) def test_disabled_adapter_does_not_publish(self): with patch("notify.realtime.publish") as send: with self.captureOnCommitCallbacks(execute=True): self.create() send.assert_not_called() def test_transport_failure_does_not_break_notification_creation(self): with patch("channels.layers.get_channel_layer", side_effect=ConnectionError("offline")): with self.assertLogs("notify.realtime", level="ERROR"): with self.captureOnCommitCallbacks(execute=True): notification = self.create() self.assertTrue(Notification.objects.filter(pk=notification.pk).exists()) @override_settings(CHANNEL_LAYERS=LAYERS) class RealtimeTransportTests(SimpleTestCase): def test_failed_recipient_does_not_block_others_and_ids_are_deduplicated(self): layer = SimpleNamespace(group_send=AsyncMock(side_effect=[ConnectionError("offline"), None])) with patch("channels.layers.get_channel_layer", return_value=layer): with self.assertLogs("notify.realtime", level="ERROR"): publish([1, 2, 1], "notification.unread") self.assertEqual(layer.group_send.await_count, 2) self.assertEqual( {call.args[0] for call in layer.group_send.await_args_list}, {user_group_name(1), user_group_name(2)}, ) @override_settings(CHANNEL_LAYERS={}) def test_missing_layer_is_a_configuration_error(self): with self.assertRaisesMessage(ImproperlyConfigured, "CHANNEL_LAYERS"): validate_configuration() def test_arbitrary_user_ids_produce_valid_separate_groups(self): for user_id in (uuid4(), "user@example.com", "long/" * 100): group = user_group_name(user_id) self.assertLess(len(group), 100) self.assertRegex(group, r"^[a-zA-Z0-9_.-]+$") self.assertNotEqual(group, user_group_name("other")) @override_settings(NOTIFY_REALTIME_GROUP_PREFIX="invalid prefix") def test_invalid_prefix_is_a_configuration_error(self): with self.assertRaisesMessage(ImproperlyConfigured, "NOTIFY_REALTIME_GROUP_PREFIX"): validate_configuration() @override_settings( CHANNEL_LAYERS={"events": {"BACKEND": "channels.layers.InMemoryChannelLayer"}}, NOTIFY_REALTIME_CHANNEL_LAYER="events", NOTIFY_REALTIME_GROUP_PREFIX="custom.users", ) class UserEventsConsumerTests(SimpleTestCase): def socket(self, user=None): socket = WebsocketCommunicator(UserEventsConsumer.as_asgi(), "/ws/events/") if user is not None: socket.scope["user"] = user return socket async def test_custom_layer_uuid_user_and_no_client_selected_subscriptions(self): user = SimpleNamespace(pk=uuid4(), is_authenticated=True, is_active=True) other_id = uuid4() socket = self.socket(user) try: self.assertTrue((await socket.connect())[0]) self.assertEqual(await socket.receive_json_from(), {"type": "connected"}) await socket.send_json_to({"type": "subscribe", "user_id": str(other_id)}) await sync_to_async(publish)([other_id], "notification.unread") self.assertTrue(await socket.receive_nothing(timeout=.05)) await sync_to_async(publish)([user.pk], "notification.created", notification_id=42) self.assertEqual( await socket.receive_json_from(), {"type": "notification.created", "notification_id": 42}, ) finally: await socket.disconnect() self.assertNotIn(user_group_name(user.pk), get_channel_layer("events").groups) async def test_missing_anonymous_and_inactive_users_are_rejected(self): for user in ( None, SimpleNamespace(is_authenticated=False), SimpleNamespace(is_authenticated=True, is_active=False), ): socket = self.socket(user) try: self.assertEqual(await socket.connect(), (False, 4401)) finally: await socket.disconnect()