How do you test a FastAPI WebSocket endpoint and lifecycle with pytest?
Tests knowledge of FastAPI TestClient usage for async WebSocket lifecycles. Use a with statement for websocket_connect; assert send, receive_json, and close; tests use standard def because TestClient handles the async app.
WHAT THIS TESTS: This question probes whether you understand that FastAPI TestClient can test WebSockets using a synchronous test style. The interviewer wants to see that you know how to exercise the full connection lifecycle and that you can distinguish WebSocket integration testing from standard HTTP endpoint testing.
A GOOD ANSWER COVERS: First, the candidate explains that you use the same TestClient for WebSockets as you do for HTTP. Second, they describe entering a WebSocket connection using a with statement and client.websocket_connect("/ws"), which yields a websocket session. Third, they walk through the lifecycle in order: the endpoint calls await websocket.accept(), the test receives data with websocket.receive_json(), and the endpoint closes with await websocket.close(). Fourth, they note that the test function is written as a standard def, not async def, because TestClient drives the async app from a synchronous test. Fifth, they mention that the context manager ensures the connection is properly managed.
COMMON WRONG ANSWERS: A major red flag is suggesting that the tester must write async def test functions and manually manage an event loop to drive the FastAPI app. Another is treating WebSocket communication as a single request-response pair like HTTP, ignoring the persistent connection and stateful message flow. Candidates who forget the with statement and leave sockets open, or who try to use HTTP verbs against a WebSocket route, also signal weak understanding. Proposing mock libraries instead of TestClient without justification is another miss, because the question specifically targets integration testing of the actual endpoint.
LIKELY FOLLOW-UPS: The interviewer may ask how you would test a WebSocket that depends on application lifespan events or startup and shutdown handlers, which are related topics in the FastAPI testing guide. They might ask how to test dependencies with overrides in a WebSocket context. Another follow-up is how you would structure async tests if the project requires them, referencing the Async Tests section.
ONE CONCRETE EXAMPLE: Suppose you have a WebSocket route at /ws that accepts a connection, sends a greeting, and then closes. In pytest, you write def test_websocket, create a TestClient app instance, then use with client.websocket_connect("/ws") as websocket. Inside the block, you call data equals websocket.receive_json() and assert data equals the dictionary with msg set to Hello WebSocket. This single test validates connect, receive, and disconnect without async await in the test body because TestClient manages the connection.
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.