代码之家  ›  专栏  ›  技术社区  ›  notorious.no

如何将“url-route”键/值添加到测试的“scope”中?

  •  0
  • notorious.no  · 技术社区  · 6 年前

    我想测试一下我的消费者 scope['url_route'] HttpCommunicator ApplicationCommunicator ,该参数未设置。如何设置此参数?测试文档非常有限,没有任何关于此的文档 https://channels.readthedocs.io/en/latest/topics/testing.html .

    测试.py

    from channels.testing import HttpCommunicator
    import pytest
    
    from my_app import consumers
    
    @pytest.mark.asyncio
    async def test_consumers():
        communicator = HttpCommunicator(consumers.MyConsumer, 'GET', '/project/1')
        response = await communicator.get_response()
        assert response['status'] == 400
    

    我的应用程序.py

    import json
    
    from channels.db import database_sync_to_async
    from channels.generic.http import AsyncHttpConsumer
    
    from projects import model
    
    class MyConsumer(AsyncHttpConsumer):
        async def handle(self, body):
            _id = int(self.scope['url_route']['kwargs'].get('project_id', 1))
            record = await database_sync_to_async(models.Project.objects.get)(id=_id)
            data = json.dumps({"id": _id})
            await self.send_response(200, data.encode('utf8'))
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   notorious.no    6 年前

    在文档中找到了解决方案,但它在Websocket测试部分下,而不是在HTTP部分中。要么导入您的asgi应用程序,要么将消费者包装在 URLRouter 然后把它用在 HttpCommunicator scope['url_route'] 在里面 URLRouter路由器

    推荐文章