Skip to content

Commit a4236a7

Browse files
authored
docs: add websockets testing capabilities (#4040)
1 parent 6cf631b commit a4236a7

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import Any
2+
3+
from litestar import WebSocket, websocket
4+
from litestar.datastructures import State
5+
from litestar.testing import create_test_client
6+
7+
8+
def test_websocket() -> None:
9+
@websocket(path="/ws")
10+
async def websocket_handler(socket: WebSocket[Any, Any, State]) -> None:
11+
await socket.accept()
12+
recv = await socket.receive_json()
13+
await socket.send_json({"message": recv})
14+
await socket.close()
15+
16+
with create_test_client(route_handlers=[websocket_handler]).websocket_connect("/ws") as ws:
17+
ws.send_json({"hello": "world"})
18+
data = ws.receive_json()
19+
assert data == {"message": {"hello": "world"}}

docs/usage/testing.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ We would then be able to rewrite our test like so:
148148
:caption: tests/test_health_check.py
149149
:language: python
150150

151+
Testing websockets
152+
++++++++++++++++++
153+
154+
Litestar's test client enhances the httpx client to support websockets. To test a websocket endpoint, you can use the :meth:`websocket_connect <litestar.testing.TestClient.websocket_connect>`
155+
method on the test client. The method returns a websocket connection object that you can use to send and receive messages, see an example below for json:
156+
157+
For more information, see also the :class:`WebSocket <litestar.connection.WebSocket>` class in the API documentation and the :ref:`websocket <usage/websockets:websockets>` documentation.
158+
159+
.. literalinclude:: /examples/testing/test_websocket.py
160+
:language: python
161+
151162

152163
Using sessions
153164
++++++++++++++

0 commit comments

Comments
 (0)