【问题标题】:How to write unittests for Consumers in django channels?如何在 django 频道中为消费者编写单元测试?
【发布时间】:2020-05-24 09:34:02
【问题描述】:

我是django-channels 的初学者。我使用channels 2.3.1。我有以下代码。

主路由

websocket_urlpatterns = [
    url(r'^ws/events/(?P<room_type>[^/]+)/(?P<room_id>[^/]+)/$', consumers.Consumer, name='core-consumer'),
]

应用路由

application = ProtocolTypeRouter({
    'websocket': URLRouter(core.routing.websocket_urlpatterns),
})

消费者

class Consumer(AsyncWebsocketConsumer):
    async def connect(self):
        room_type = self.scope['url_route']['kwargs']['room_type']
        room_id = self.scope['url_route']['kwargs']['room_id']
        self.room_group_name = f'{room_type}_{room_id}'

        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        await self.accept()

    async def receive(self, text_data = None, bytes_data = None):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        await self.channel_layer.group_send(self.room_group_name,
            {'type': 'send_data', 'message': message}
        )

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

    async def send_data(self, event):
        message = event['message']
        await self.send(text_data=json.dumps({
            'data': message
        }))

def send_event(channel='', message=''):
    channel_layer = get_channel_layer()
    asyncio.run(channel_layer.group_send(channel,
        {
            'type': 'send_data',
            'message': message
        }
    ))

信号

    def activate_notification(self):
        send_event(f'user_{self.id}',
                   {'message': f"Welcome back to one deeds!"})

如何使用unittest 测试consumer 中的每个函数?

我读了这个documentation,但什么都不懂(

我想用命令./manage.py test运行测试

我尝试使用WebsocketCommunicator对此进行测试

【问题讨论】:

    标签: python django django-channels channels django-unittest


    【解决方案1】:

    我会建议一些事情。

    1) 使用channels.layers.InMemoryChannelLayer 层。

    2) 使用pytest-asyncio,这样你的测试代码就可以是async方法

    @pytest.mark.django_db(transaction=True)
    @pytest.mark.asyncio
    async def test_get():
       ....
    

    要运行这些测试,您将使用 pytest

    3) 使用WebsocketCommunicator 检查这些examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多