Search code examples
pythonpytestaiohttp

Pytest testing of a websocket connection


Using aiohttp for both client requests and websocket connection I am trying to find a proper pytest implementation.

For client requests I am using aioresponses https://pypi.python.org/pypi/aioresponses/0.1.2

For mocking a websocket connecting I am not sure what to do. Anyone any suggestions ?

Thanks !


Solution

  • Don't mock but use fake server for testing the client (like you probably use a test client provided by aiohttp for testing the server).

    Example of fake client: https://github.com/aio-libs/aiohttp/blob/master/examples/fake_server.py

    The example doesn't demonstrate websockets usage but I pretty sure you've got my idea and have enough knowledge to extend the shown approach to websockets.

    [edit]

    In WSGI world testing against a fake server is hard: it requires a separate thread at least. It asyncio the task is pretty easy.

    Thus please don't get me wrong. I don't advise against aioresponses etc, I just want to emphasize: in asyncio world the need for mocking responses is pretty low.

    The fake server based approach is much more reliable: you are testing the whole transport layer, not only mocked (monkey-patched actually) data.

    Libraries like aioresponse uses private attributes of aiohttp classes, the behavior could be broken by next aiohttp release. Moreover it is maybe broken already in some rare use cases.