Skip to content

Commit 4d766b1

Browse files
committed
📝 (testing.md): add documentation for testing WebSocket actions and channels with TestClient
1 parent 78bad08 commit 4d766b1

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

‎docs/Usage/testing.md‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Testing
2+
3+
SocketAPI includes a built-in `TestClient` based on Starlette's test client, making it easy to test your WebSocket actions and channels.
4+
5+
## Basic Usage
6+
7+
```python
8+
from socketapi import SocketAPI
9+
from socketapi.testclient import TestClient
10+
11+
app = SocketAPI()
12+
13+
@app.action("calculate")
14+
async def calculate(a: int, b: int) -> int:
15+
return a + b
16+
17+
@app.channel("notifications")
18+
async def notifications(message: str):
19+
return {"message": message}
20+
21+
def test_action():
22+
client = TestClient(app)
23+
24+
with client.websocket_connect("/") as websocket:
25+
# Send action request
26+
websocket.send_json({
27+
"type": "action",
28+
"channel": "calculate",
29+
"data": {"a": 5, "b": 3}
30+
})
31+
32+
# Receive response
33+
response = websocket.receive_json()
34+
assert response["data"] == 8
35+
assert response["status"] == "completed"
36+
37+
def test_channel():
38+
client = TestClient(app)
39+
40+
with client.websocket_connect("/") as websocket:
41+
# Subscribe to channel
42+
websocket.send_json({
43+
"type": "subscribe",
44+
"channel": "notifications"
45+
})
46+
47+
# Receive subscription confirmation
48+
response = websocket.receive_json()
49+
assert response["type"] == "subscribed"
50+
assert response["channel"] == "notifications"
51+
```
52+
53+
The `TestClient` provides a simple way to test your WebSocket endpoints without running a live server.

0 commit comments

Comments
 (0)