tezvyn:

Testing WebSockets in FastAPI

AI-drafted, machine-checkedSource: fastapi.tiangolo.comadvanced
Testing WebSockets in FastAPI

Test a WebSocket conversation by scripting both sides. FastAPI's TestClient provides a `websocket_connect` context manager to send messages and assert responses sequentially, which is crucial for testing chats or live data feeds.

WHY IT EXISTS Testing interactive, stateful protocols like WebSockets is harder than testing stateless HTTP requests. A simple request-response test isn't enough. You need a tool that can simulate a live client connection over its entire lifecycle: connecting, sending multiple messages, receiving multiple messages, and disconnecting.

THE MENTAL MODEL Think of testing a WebSocket endpoint like having a scripted conversation. FastAPI's TestClient acts as one person in the conversation, following your test script to send messages and check the replies it gets back from your app. The entire back-and-forth happens within a single test function, mimicking a real user session.

HOW IT WORKS FastAPI bundles the TestClient, which you can use to call your application in tests. To test a WebSocket, you don't use client.get() or client.post(). Instead, you use a Python context manager: with client.websocket_connect("/your-ws-url") as websocket:. This statement handles opening the connection and cleanly closing it afterward. Inside the with block, you get a websocket object. You use this object to drive the interaction, calling methods like websocket.send_text("hello") or websocket.send_json({...}) to send data to your server. To check the server's response, you call data = websocket.receive_text() or data = websocket.receive_json(), and then use assert to verify the data is correct. The order of these calls must match your application's logic.

WHEN TO USE IT Use the TestClient with websocket_connect for writing integration or functional tests for any FastAPI application that uses WebSockets. It's the canonical way to verify the logic of real-time features like chat applications, live notifications, or data streaming dashboards before deploying them.

WHEN NOT TO USE IT Do not use websocket_connect to test regular HTTP endpoints (like those for GET, POST, PUT, DELETE). For those, use the standard TestClient methods: client.get(), client.post(), etc. Using the wrong method for the endpoint type will result in an error. This tool is exclusively for the WebSocket protocol.

ONE CANONICAL EXAMPLE First, import TestClient from fastapi.testclient and your app object. Create a client instance: client = TestClient(app). In your test function, open a connection using a with statement: with client.websocket_connect("/ws/echo") as websocket:. Inside this block, send a message: websocket.send_text("Hello, world"). Then, receive the server's response: data = websocket.receive_text(). Finally, assert that the received data is what you expect: assert data == "Echo: Hello, world".

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.