WebSocket 테스트하기

WebSocket 테스트하기 (Testing WebSockets)

HTTP 테스트에서 썼던 그 TestClient를 그대로 WebSocket 테스트에도 쓸 수 있어요. WebSocket에 연결하려면 TestClientwith 안에서 쓰면 돼요.

출처: 공식문서

TestClient로 WebSocket 테스트하기

from fastapi import FastAPI
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocket

app = FastAPI()

@app.get("/")
async def read_main():
    return {"msg": "Hello World"}

@app.websocket("/ws")
async def websocket(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_json({"msg": "Hello WebSocket"})
    await websocket.close()

def test_read_main():
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": "Hello World"}

def test_websocket():
    client = TestClient(app)
    with client.websocket_connect("/ws") as websocket:
        data = websocket.receive_json()
        assert data == {"msg": "Hello WebSocket"}

일반 HTTP 요청(client.get)은 그냥 호출하면 되고, WebSocket 연결은 client.websocket_connect("/ws")with 문과 함께 써요. 연결된 websocket 객체에서 receive_json()으로 서버가 보낸 데이터를 받아와서 검증하면 돼요.

참고 — 더 자세한 내용은 Starlette의 WebSocket 테스트 문서를 확인해 주세요.

더 알아보기 (Learn more)