sanic-org / sanic-testing

Test clients for Sanic
https://sanic.dev/en/plugins/sanic-testing/getting-started.html
MIT License
31 stars 19 forks source link

Add functionality to mimic a websocket client against an endpoint #50

Closed ahopkins closed 2 years ago

ahopkins commented 2 years ago

This PR is meant to introduce a new API to test websocket endpoints. To do this, the developer would pass an async function that can send and recv messages from the endpoint. To test, these values will be stored and accessible to assert against.

def test_websocket_route_queue(app: Sanic):
    async def client_mimic(websocket: WebSocketClientProtocol):
        await websocket.send("foo")
        await websocket.recv()

    @app.websocket("/ws")
    async def handler(request, ws: Websocket):
        while True:
            await ws.send("hello!")
            if not await ws.recv():
                break

    _, response = app.test_client.websocket("/ws", mimic=client_mimic)
    assert response.server_sent == ["hello!"]
    assert response.server_received == ["foo", ""]