|
| 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