| 1 |
from fastapi import FastAPI |
| 2 |
from fastapi.testclient import TestClient |
| 3 |
from fastapi.websockets import WebSocket |
| 4 |
|
| 5 |
app = FastAPI() |
| 6 |
|
| 7 |
|
| 8 |
@app.get("/") |
| 9 |
async def read_main(): |
| 10 |
return {"msg": "Hello World"} |
| 11 |
|
| 12 |
|
| 13 |
@app.websocket("/ws") |
| 14 |
async def websocket(websocket: WebSocket): |
| 15 |
await websocket.accept() |
| 16 |
await websocket.send_json({"msg": "Hello WebSocket"}) |
| 17 |
await websocket.close() |
| 18 |
|
| 19 |
|
| 20 |
def test_read_main(): |
| 21 |
client = TestClient(app) |
| 22 |
response = client.get("/") |
| 23 |
assert response.status_code == 200 |
| 24 |
assert response.json() == {"msg": "Hello World"} |
| 25 |
|
| 26 |
|
| 27 |
def test_websocket(): |
| 28 |
client = TestClient(app) |
| 29 |
with client.websocket_connect("/ws") as websocket: |
| 30 |
data = websocket.receive_json() |
| 31 |
assert data == {"msg": "Hello WebSocket"} |