harvestconnect-api / api /tests /chat_test_support.py
Dayozoe's picture
feat: deploy HarvestConnect Django API with crash-proof persistent volume
a6be783 verified
Raw History Blame Contribute Delete
1.96 kB
import asyncio
from unittest.mock import patch
from asgiref.sync import async_to_sync
from channels.routing import URLRouter
from channels.layers import channel_layers
from channels.testing import WebsocketCommunicator
from channels.security.websocket import OriginValidator
from django.contrib.auth import get_user_model
from django.test import TransactionTestCase, override_settings
from django.urls import re_path
from rest_framework_simplejwt.tokens import AccessToken
from ..consumers import ChatConsumer
from ..middleware import JwtAuthMiddleware
from ..models import ChatRoom
@override_settings(CHANNEL_LAYERS={"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}})
class ChatWebSocketTestCase(TransactionTestCase):
reset_sequences = True
def setUp(self):
# Reset Channels' cached backend so this isolated suite always uses its
# deterministic in-memory layer regardless of the runtime Redis config.
channel_layers.backends.clear()
User = get_user_model()
self.member = User.objects.create_user(username="chat-member", email="member@example.test", password="test-pass")
self.other = User.objects.create_user(username="chat-other", email="other@example.test", password="test-pass")
self.room = ChatRoom.objects.create(name="private-room", room_type="group")
self.room.participants.add(self.member)
self.application = OriginValidator(
JwtAuthMiddleware(URLRouter([
re_path(r"^ws/chat/(?P<room_id>[^/]+)/?$", ChatConsumer.as_asgi()),
])),
["http://localhost:3001"],
)
def _communicator(self, token=None, room_id=None):
protocols = ["jwt", token] if token else []
return WebsocketCommunicator(
self.application,
f"/ws/chat/{room_id or self.room.pk}/",
subprotocols=protocols,
headers=[(b"origin", b"http://localhost:3001")],
)