Skip to content
This repository was archived by the owner on Feb 8, 2025. It is now read-only.

Commit 54a65f3

Browse files
authored
Create test_websocket.py
1 parent 3bf335f commit 54a65f3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

tests/test_websocket.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from multiprocessing import Process
2+
import socket
3+
import random
4+
import time
5+
6+
import pytest
7+
import uvicorn
8+
from kasumi import Kasumi, WebSocket
9+
from kasumi.exceptions import ConnectionClosed
10+
from websockets.client import connect
11+
from websockets.exceptions import ConnectionClosedError
12+
13+
app = Kasumi()
14+
15+
def is_port_in_use(port: int) -> bool:
16+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
17+
return s.connect_ex(('localhost', port)) == 0
18+
19+
def get_random_port() -> int:
20+
while True:
21+
port = random.randint(1024, 65535)
22+
if not is_port_in_use(port):
23+
return port
24+
25+
port = get_random_port()
26+
27+
@app.ws("/ws")
28+
async def websocket_endpoint(websocket: WebSocket):
29+
await websocket.accept()
30+
try:
31+
while True:
32+
data = await websocket.recv()
33+
if data:
34+
await websocket.send_str(f"Message text was: {data.text}")
35+
except ConnectionClosed:
36+
pass
37+
38+
@pytest.fixture(scope="module")
39+
def uvicorn_server():
40+
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="info")
41+
server = uvicorn.Server(config)
42+
process = Process(target=server.run)
43+
process.start()
44+
time.sleep(1)
45+
yield
46+
process.terminate()
47+
process.join()
48+
49+
@pytest.mark.asyncio
50+
async def test_websocket(uvicorn_server):
51+
try:
52+
async with connect(f"ws://127.0.0.1:{port}/ws") as websocket:
53+
await websocket.send("Hello, WebSocket!")
54+
response = await websocket.recv()
55+
assert response == "Message text was: Hello, WebSocket!"
56+
except ConnectionClosedError:
57+
pass

0 commit comments

Comments
 (0)