给定一个 Django Channels 消费者,如下所示:
class NotificationConsumer(JsonWebsocketConsumer):
def connect(self):
user = self.scope["user"]
async_to_sync(self.channel_layer.group_add)("hello", "hello")
self.accept()
async_to_sync(self.channel_layer.group_send)(
"hello", {"type": "chat.message", "content": "hello"}
)
def receive_json(self, content, **kwargs):
print(content)
async_to_sync(self.channel_layer.group_send)(
"hello", {"type": "chat.message", "content": "hello"}
)
print("Here we are")
def chat_message(self, event):
self.send_json(content=event["content"])
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)("hello", "hello")
以及如下所示的测试:
@pytest.mark.asyncio
class TestWebsockets:
async def test_receives_data(self, settings):
communicator = WebsocketCommunicator(
application=application, path="/ws/notifications/"
)
connected, _ = await communicator.connect()
assert connected
await communicator.send_json_to({"type": "notify", "data": "who knows"})
response = await communicator.receive_json_from()
await communicator.disconnect()
当我运行测试时,我总是收到TimeoutError
。我需要做哪些不同的事情?
如果您想查看完整的存储库示例,请查看 https://github.com/phildini/websockets-test
最佳答案
不应该async_to_sync(self.channel_layer.group_add)("hello", "hello")
是async_to_sync(self.channel_layer.group_add)("hello", self.channel_name )
?
在第一种情况下,您将“hello”添加到组中,测试中的 communicator.receive_json_from()
将失败,因为测试客户端不会收到 group_send。
将类重构为:
class NotificationConsumer(JsonWebsocketConsumer):
def connect(self):
user = self.scope["user"]
async_to_sync(self.channel_layer.group_add)("hello", self.channel_name)
self.accept()
async_to_sync(self.channel_layer.group_send)(
"hello", {"type": "chat.message", "content": "hello"}
)
def receive_json(self, content, **kwargs):
print(content)
async_to_sync(self.channel_layer.group_send)(
"hello", {"type": "chat.message", "content": "hello"}
)
print("Here we are")
def chat_message(self, event):
self.send_json(content=event["content"])
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)("hello", self.channel_name)
我可以从示例存储库通行证中获取测试
关于django - 无法让 websockets 测试通过 Django Channels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61599735/