如何将“url_route”键/值添加到“scope”中进行测试?

not*_*.no 4 python-asyncio django-channels pytest-asyncio

我正在测试我的消费者,它使用scope['url_route']但使用HttpCommunicatoror 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
Run Code Online (Sandbox Code Playgroud)

my_app.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'))
Run Code Online (Sandbox Code Playgroud)

not*_*.no 8

在文档中找到了解决方案,但它位于 Websocket 测试部分,而不是 HTTP 部分。导入您的 asgi 应用程序或将消费者包装起来,URLRouter然后在HttpCommunicator. 事实证明,添加了一些scope['url_route']流量URLRouter