Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Testing WebSockets

You can use the sameTestClient to test WebSockets.

For this, you use theTestClient in awith statement, connecting to the WebSocket:

fromfastapiimportFastAPIfromfastapi.testclientimportTestClientfromfastapi.websocketsimportWebSocketapp=FastAPI()@app.get("/")asyncdefread_main():return{"msg":"Hello World"}@app.websocket("/ws")asyncdefwebsocket(websocket:WebSocket):awaitwebsocket.accept()awaitwebsocket.send_json({"msg":"Hello WebSocket"})awaitwebsocket.close()deftest_read_main():client=TestClient(app)response=client.get("/")assertresponse.status_code==200assertresponse.json()=={"msg":"Hello World"}deftest_websocket():client=TestClient(app)withclient.websocket_connect("/ws")aswebsocket:data=websocket.receive_json()assertdata=={"msg":"Hello WebSocket"}

Note

For more details, check Starlette's documentation fortesting WebSockets.


[8]ページ先頭

©2009-2026 Movatter.jp