|
| 1 | +from channels.testing import WebsocketCommunicator |
1 | 2 | from django.contrib.auth import get_user_model |
| 3 | +from django.test import TestCase |
2 | 4 | from django.urls import reverse |
3 | 5 | from rest_framework.test import APITestCase |
4 | 6 | from rest_framework_simplejwt.tokens import RefreshToken |
5 | 7 |
|
| 8 | +from chat.consumers import ChatConsumer |
6 | 9 | from chat.models import Message |
7 | | -from shop.models import Product |
| 10 | +from shop.models import Product, Category |
8 | 11 |
|
9 | 12 | User = get_user_model() |
10 | 13 |
|
@@ -52,3 +55,48 @@ def test_api_get_messages(self): |
52 | 55 | response = self.client.get(self.url) |
53 | 56 | self.assertEqual(response.status_code, 200) |
54 | 57 | self.assertIn('data', response.data) |
| 58 | + |
| 59 | + |
| 60 | +class ChatConsumerTest(TestCase): |
| 61 | + def setUp(self): |
| 62 | + # Create test users |
| 63 | + self.User = get_user_model() |
| 64 | + self. seller = self. User. objects. create_user( username='seller', password='password', email='[email protected]') |
| 65 | + self. buyer = self. User. objects. create_user( username='buyer', password='password', email='[email protected]') |
| 66 | + |
| 67 | + # Create a test product |
| 68 | + self.category = Category.objects.create(name='TestCat', slug='testcat') |
| 69 | + self.product = Product.objects.create(name='Test Product', user=self.seller, price=10.00, stock=5, category=self.category) |
| 70 | + |
| 71 | + async def test_chat_consumer(self): |
| 72 | + # Simulate WebSocket connection for the buyer |
| 73 | + communicator = WebsocketCommunicator( |
| 74 | + ChatConsumer.as_asgi(), |
| 75 | + f'/ws/chat/{self.product.product_id}/' |
| 76 | + ) |
| 77 | + communicator.scope['user'] = self.buyer |
| 78 | + communicator.scope['url_route'] = {'kwargs': {'product_id': self.product.product_id}} |
| 79 | + |
| 80 | + connected, _ = await communicator.connect() |
| 81 | + self.assertTrue(connected) |
| 82 | + |
| 83 | + # Send a message from the buyer |
| 84 | + message = 'Hello, I am interested in your product!' |
| 85 | + await communicator.send_json_to({ |
| 86 | + 'message': message |
| 87 | + }) |
| 88 | + |
| 89 | + # Receive the message from the WebSocket |
| 90 | + response = await communicator.receive_json_from() |
| 91 | + self.assertEqual(response['message'], message) |
| 92 | + self.assertEqual(response['sender'], self.buyer.username) |
| 93 | + |
| 94 | + # Check if the message was saved in the database |
| 95 | + saved_message = Message.objects.get(content=message) |
| 96 | + self.assertEqual(saved_message.sender, self.buyer) |
| 97 | + self.assertEqual(saved_message.recipient, self.seller) |
| 98 | + self.assertEqual(saved_message.product, self.product) |
| 99 | + |
| 100 | + # Disconnect the WebSocket |
| 101 | + await communicator.disconnect() |
| 102 | + |
0 commit comments