|
| 1 | +from django.contrib.auth.models import User |
| 2 | +from .models import Chat, Message |
| 3 | +from django.contrib.auth import get_user_model |
| 4 | +from .consumers import ChatConsumer |
| 5 | +from channels.testing import WebsocketCommunicator |
| 6 | +from django.conf import settings |
| 7 | +from backend.asgi import application |
| 8 | +from apps.users.models import Profile |
| 9 | +from rest_framework_simplejwt.tokens import RefreshToken |
| 10 | +import asyncio |
| 11 | +import pytest |
| 12 | +import json |
| 13 | + |
| 14 | +@pytest.mark.asyncio |
| 15 | +@pytest.mark.django_db(transaction=True) |
| 16 | +class TestChatWebsockets: |
| 17 | + @pytest.fixture(autouse=True) |
| 18 | + def setup(self, db): |
| 19 | + self.user1 = get_user_model().objects.create_user( |
| 20 | + username='testuser1', |
| 21 | + password='password', |
| 22 | + first_name='John', |
| 23 | + last_name='Doe', |
| 24 | + email='testuser1@example.com' |
| 25 | + ) |
| 26 | + self.profile1 = Profile.objects.create(user=self.user1, role=2) |
| 27 | + self.token1 = self.get_jwt_token(self.user1) |
| 28 | + |
| 29 | + self.user2 = get_user_model().objects.create_user( |
| 30 | + username='testuser2', |
| 31 | + password='password', |
| 32 | + first_name='Jane', |
| 33 | + last_name='Doe', |
| 34 | + email='testuser2@example.com' |
| 35 | + ) |
| 36 | + self.profile2 = Profile.objects.create(user=self.user2, role=2) |
| 37 | + self.token2 = self.get_jwt_token(self.user2) |
| 38 | + |
| 39 | + # Create test chat |
| 40 | + self.chat, _ = Chat.objects.get_or_create_chat(self.user1, self.user2) |
| 41 | + self.chat.name = "room1" |
| 42 | + self.chat.save() |
| 43 | + |
| 44 | + # Create test messages |
| 45 | + self.message1 = Message.objects.create( |
| 46 | + chat=self.chat, |
| 47 | + sender=self.user1, |
| 48 | + content="Test message 1 for chat", |
| 49 | + status=Message.NOT_SEEN |
| 50 | + ) |
| 51 | + self.message2 = Message.objects.create( |
| 52 | + chat=self.chat, |
| 53 | + sender=self.user1, |
| 54 | + content="Test message 2 for chat", |
| 55 | + status=Message.NOT_SEEN |
| 56 | + ) |
| 57 | + |
| 58 | + def get_jwt_token(self, user): |
| 59 | + refresh = RefreshToken.for_user(user) |
| 60 | + return str(refresh.access_token) |
| 61 | + |
| 62 | + def setup_communicator(self, room_name, token): |
| 63 | + return WebsocketCommunicator( |
| 64 | + application, |
| 65 | + f"/ws/apps/chat/{room_name}/", |
| 66 | + subprotocols=["chat", token], |
| 67 | + ) |
| 68 | + |
| 69 | + async def test_websocket_connection(self): |
| 70 | + communicator = self.setup_communicator("room1", self.token1) |
| 71 | + connected, _ = await communicator.connect() |
| 72 | + assert connected |
| 73 | + |
| 74 | + await asyncio.sleep(0.1) |
| 75 | + |
| 76 | + await communicator.send_to(text_data=json.dumps({"message": "ping"})) |
| 77 | + response = await communicator.receive_from() |
| 78 | + data = json.loads(response) |
| 79 | + |
| 80 | + assert data["message"] == "successful" |
| 81 | + assert data["body"] == "ping" |
| 82 | + |
| 83 | + await communicator.disconnect() |
| 84 | + |
| 85 | + async def test_websocket_error_when_room_missing(self): |
| 86 | + # Pick a room name you never created in your fixtures or setup |
| 87 | + missing_room = "i_dont_exist" |
| 88 | + |
| 89 | + # Set up communicator exactly the same way |
| 90 | + communicator = self.setup_communicator(missing_room, self.token1) |
| 91 | + connected, _ = await communicator.connect() |
| 92 | + assert connected |
| 93 | + |
| 94 | + # Give the consumer a split-second to finish any setup |
| 95 | + await asyncio.sleep(0.1) |
| 96 | + |
| 97 | + # Send a normal chat payload |
| 98 | + await communicator.send_to(text_data=json.dumps({"message": "hello"})) |
| 99 | + |
| 100 | + # The consumer should catch Chat.DoesNotExist and send back an 'error' field |
| 101 | + response = await communicator.receive_from() |
| 102 | + data = json.loads(response) |
| 103 | + |
| 104 | + assert "error" in data, "Expected an 'error' key when room is missing" |
| 105 | + assert data["error"] == f"Chat room '{missing_room}' not found. Message not saved." |
| 106 | + |
| 107 | + await communicator.disconnect() |
| 108 | + |
| 109 | + async def test_websocket_typing_status(self): |
| 110 | + communicator = self.setup_communicator("room1", self.token1) |
| 111 | + connected, _ = await communicator.connect() |
| 112 | + assert connected |
| 113 | + |
| 114 | + await asyncio.sleep(0.1) |
| 115 | + |
| 116 | + await communicator.send_to(text_data=json.dumps({"typing": True})) |
| 117 | + response = await communicator.receive_from() |
| 118 | + data = json.loads(response) |
| 119 | + |
| 120 | + assert data["message"] == "successful" |
| 121 | + assert data["typing"] is True |
| 122 | + assert data["username"] == self.user1.username |
| 123 | + |
| 124 | + await communicator.disconnect() |
| 125 | + |
| 126 | + async def test_websocket_seen_status(self): |
| 127 | + communicator = self.setup_communicator("room1", self.token2) # User who sees the text |
| 128 | + connected, _ = await communicator.connect() |
| 129 | + assert connected |
| 130 | + |
| 131 | + await asyncio.sleep(0.1) |
| 132 | + |
| 133 | + seen_ids = [self.message1.id, self.message2.id] |
| 134 | + await communicator.send_to(text_data=json.dumps({"seen": seen_ids})) |
| 135 | + response = await communicator.receive_from() |
| 136 | + data = json.loads(response) |
| 137 | + |
| 138 | + assert data["message"] == "seen_successful" |
| 139 | + assert sorted(data["ids"]) == sorted(seen_ids) |
| 140 | + assert data["username"] == self.user1.username |
| 141 | + |
| 142 | + await communicator.disconnect() |
0 commit comments