pythonpytestdjango-channelspytest-asyncio

Django-Channels 2 Communicator receive_output() doesn't work


I have a basic Consumer that receives messages from the websocket and then broadcasts those messages to a channel specified in the message.

consumers.py

class BasicConsumer(AsyncJsonWebsocketConsumer):
    async def receive_json(self, content, **kwargs):
        channel = content['channel']
        await self.channel_layer.send(
            channel,
            {
                'type': 'some-message-type',
                'body': content,
            },
        )

I then want to test this with pytest and pytest-asyncio like so

@pytest.mark.asyncio
async def test_basic_consumer():
    channel_layer = get_channel_layer()

    # connect to consumer
    communicator = WebsocketCommunicator(BasicConsumer, "/my-url/")
    connected, subprotocol = await communicator.connect()
    assert connected

    # generate valid channel name
    channel_name = await channel_layer.new_channel()

    await communicator.send_json_to({
        'channel': channel_name,
        'data': 'some-data',
    })

    from_channel_layer = await communicator.receive_output(timeout=5)
    assert from_channel_layer == {
        'type': 'some-message-type',
        'body': {
            'channel': channel_name,
            'data': 'some-data',
        },
    }

My understanding is that communicator.receive_output() will retrieve the event the consumer sent to the channel layer. However I get the following error:

___________________________ test_basic_consumer ___________________________

self = <channels.testing.websocket.WebsocketCommunicator object at 0x7f901b5a87b8>
timeout = 5

    async def receive_output(self, timeout=1):
        """
        Receives a single message from the application, with optional timeout.
        """
        # Make sure there's not an exception to raise from the task
        if self.future.done():
            self.future.result()
        # Wait and receive the message
        try:
            async with async_timeout(timeout):
>               return await self.output_queue.get()

vp3test/lib/python3.7/site-packages/asgiref/testing.py:75: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <Queue at 0x7f901b5a8898 maxsize=0 tasks=1>

    async def get(self):
        """Remove and return an item from the queue.

        If queue is empty, wait until an item is available.
        """
        while self.empty():
            getter = self._loop.create_future()
            self._getters.append(getter)
            try:
>               await getter
E               concurrent.futures._base.CancelledError

/usr/lib/python3.7/asyncio/queues.py:159: CancelledError

During handling of the above exception, another exception occurred:

    @pytest.mark.asyncio
    async def test_basic_consumer():
        channel_layer = get_channel_layer()

        # connect to consumer
        communicator = WebsocketCommunicator(BasicConsumer, "/my-url/")
        connected, subprotocol = await communicator.connect()
        assert connected

        # generate valid channel name
        channel_name = await channel_layer.new_channel()

        await communicator.send_json_to({
            'channel': channel_name,
            'data': 'some-data',
        })

>       from_channel_layer = await communicator.receive_output(timeout=5)

test_consumers.py:150: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
vp3test/lib/python3.7/site-packages/asgiref/testing.py:86: in receive_output
    raise e
vp3test/lib/python3.7/site-packages/asgiref/testing.py:75: in receive_output
    return await self.output_queue.get()
vp3test/lib/python3.7/site-packages/asgiref/timeout.py:68: in __aexit__
    self._do_exit(exc_type)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <asgiref.timeout.timeout object at 0x7f901b5a8ba8>
exc_type = <class 'concurrent.futures._base.CancelledError'>

    def _do_exit(self, exc_type: Type[BaseException]) -> None:
        if exc_type is asyncio.CancelledError and self._cancelled:
            self._cancel_handler = None
            self._task = None
>           raise asyncio.TimeoutError
E           concurrent.futures._base.TimeoutError

vp3test/lib/python3.7/site-packages/asgiref/timeout.py:105: TimeoutError

Is there some more setup/configuration I need to do in my test? Or am I using receive_output() wrong?

I am using InMemoryChannelLayer for the tests and the latest released version of everything.


Solution

  • My problem was that I was calling

    from_channel_layer = await communicator.receive_output(timeout=5)
    

    This is waiting for a message the consumer is sending down the websocket.


    Instead I can call

    from_channel_layer = await channel_layer.receive(channel_name)
    

    to get the message the consumer is sending over the channel layer.