skip to content

In FastAPI, how do you test a WebSocket endpoint with TestClient.websocket_connect, including a connection the endpoint refuses?

level: middleimportance: should knowfreq 25%

answer

  1. the same client used for HTTP tests
  2. a context manager around the session
  3. the session mirrors send and receive
  4. a refusal surfaces on entering the block

basics

~20 s

Open the socket in a with block around client.websocket_connect(url), then drive it with send_text(), send_json() and receive_json(). A refusal before accept surfaces as WebSocketDisconnect raised on entering the block, so the test asserts its code and reason.

solid answer

~40 s

`TestClient` from `fastapi.testclient` drives sockets as well as HTTP: `with client.websocket_connect("/rooms/lobby/ws?token=good") as ws:` runs the endpoint in-process, and the session offers `send_text()`, `send_json()`, `receive_text()` and `receive_json()`, mirroring the server side. Leaving the block sends a normal 1000 close, so the endpoint's `except WebSocketDisconnect` path runs too. A refusal before `accept()` raises `WebSocketDisconnect` as soon as the block is entered, carrying the `code` and `reason` the endpoint closed with, so the test catches it and asserts `exc.code == status.WS_1008_POLICY_VIOLATION`. Headers go in `headers=`, query values in the URL, and `app.dependency_overrides` replaces socket dependencies just as it does HTTP ones. Two gaps to remember: no real server is involved, so the test sees the close code where Uvicorn would answer 403, and a `receive_*` call waits forever if the endpoint never sends.

code

python · 35 lines
python
from typing import Annotated

from fastapi import FastAPI, Query, WebSocket, WebSocketDisconnect, WebSocketException, status
from fastapi.testclient import TestClient

app = FastAPI()


@app.websocket("/rooms/{room_id}/ws")
async def room_socket(
    websocket: WebSocket, room_id: str, token: Annotated[str | None, Query()] = None
):
    if token != "good":
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION, reason="bad token")
    await websocket.accept()
    text = await websocket.receive_text()
    await websocket.send_json({"room": room_id, "text": text})


client = TestClient(app)


def test_echo_in_room():
    with client.websocket_connect("/rooms/lobby/ws?token=good") as ws:
        ws.send_text("hi")
        assert ws.receive_json() == {"room": "lobby", "text": "hi"}


def test_refused_without_token():
    try:
        with client.websocket_connect("/rooms/lobby/ws"):
            raise AssertionError("the connection should have been refused")
    except WebSocketDisconnect as exc:
        assert exc.code == status.WS_1008_POLICY_VIOLATION
        assert exc.reason == "bad token"

go deeper

for a junior

Remember the shape: with client.websocket_connect(url) as ws, then send_text and receive_json on ws, using the same TestClient as for HTTP.

for a middle

Explain where a refusal surfaces (on entering the block), that leaving the block sends a 1000 close, and that dependency_overrides works for socket routes.

for a senior

Know the gaps: no 403 handshake, no timeout on receive, a single process, so add a check against a real server for anything a browser depends on.

for a principal

Decide which socket behaviours the team pins in fast in-process tests and which need a slower test against a running server, and make that split explicit.

FastAPI's testing docs use the same `TestClient` for WebSockets as for HTTP. It calls the application in-process, without a network or a server, so a socket test is fast and deterministic, with a few gaps worth knowing. ## Opening a test session `client.websocket_connect(url)` returns a **session object** that must be used as a context manager: 1. Entering `with client.websocket_connect("/rooms/lobby/ws?token=good") as ws:` starts the endpoint, delivers the connect event and waits for the endpoint's first move. 2. If the endpoint calls `accept()`, the block body runs with `ws` connected. 3. If the endpoint closes first, entering the block raises `WebSocketDisconnect` instead. 4. Leaving the block sends a close with code 1000, which the endpoint's pending receive turns into `WebSocketDisconnect`. Calling `websocket_connect()` without `with` gives you a session that was never started, so its methods cannot be used. ## Driving the conversation | Test side (session) | What the endpoint sees | |---|---| | `ws.send_text("hi")` | `await websocket.receive_text()` returns `"hi"` | | `ws.send_json({"join": "lobby"})` | `await websocket.receive_json()` returns the dict | | `ws.receive_text()` | returns what `await websocket.send_text(...)` sent | | `ws.receive_json()` | returns what `await websocket.send_json(...)` sent, parsed | | `ws.close(code=1000)` or leaving the block | the pending receive raises `WebSocketDisconnect` | The session's calls are synchronous: it runs the endpoint in a background event loop and blocks the test thread on each exchange. ## Asserting a refusal A rejected connection never reaches the block body, so the assertion wraps the whole `with`: - Catch `WebSocketDisconnect` (from `fastapi`) around `with client.websocket_connect(...)`. - Assert `exc.code == status.WS_1008_POLICY_VIOLATION` and, when the endpoint sets one, `exc.reason`. - Fail the test explicitly if the block body runs, since that means the connection was accepted. - For a close after `accept()`, the `WebSocketDisconnect` comes from the next `receive_*` call inside the block instead. The test runner's own raises helper does the same job as a `try`/`except` if the suite already uses it. ## Overrides, headers and other inputs - **Query parameters** go in the URL: `/rooms/lobby/ws?token=good`. - **Headers** go in `headers={"x-token": "good"}`, which is also how a cookie header reaches `Cookie()` parameters. - **Subprotocols** go in `subprotocols=[...]`. - **Dependencies** are replaced with `app.dependency_overrides[get_socket_user] = lambda: "alice"`, keyed by the original function; overrides apply to socket routes exactly as to HTTP routes. Clear them after each test. ## Testing a conversation between two clients Room behaviour needs at least two sessions open at once, which nested context managers give you: - `with client.websocket_connect("/rooms/r/ws") as a, client.websocket_connect("/rooms/r/ws") as b:` opens both in the same test. - `a.send_text("x")`, then assert on `a.receive_json()` and `b.receive_json()` to prove the broadcast reached both. - When the endpoint relies on state built in `lifespan`, open the client itself as `with TestClient(app) as client:` so startup runs first. ## What the in-process test does not show - **The 403 handshake.** Under Uvicorn a close before `accept()` is answered with HTTP 403 and the client never sees your code. The test reports the code, so a passing test does not prove a browser can read it. - **`HTTPException` before accept.** Starlette sends it as a denial response, and the test client raises `WebSocketDenialResponse`, a `WebSocketDisconnect` subclass carrying the HTTP `status_code` and body. - **Timeouts.** `ws.receive_json()` has no timeout. If the endpoint never sends, the test hangs rather than failing, so keep exchanges strictly request-then-reply or put a timeout on the test run. - **Several workers.** Everything runs in one process, so a broadcast test passes even when production would split the room across workers. ## Common mistakes - Asserting a refusal inside the `with` body, where it is never reached. - Leaving an entry in `app.dependency_overrides` after a test, so the next test authenticates as the stub user without noticing. - Asserting the order of messages across two sessions when the endpoint sends to them concurrently; assert per session instead. - Expecting `websocket_connect()` to return `None` or an error object on refusal. - Forgetting that leaving the block is itself a disconnect the endpoint reacts to.

  • How do you test a FastAPI socket endpoint whose dependency verifies real tokens, without issuing any?
    Override the dependency: `app.dependency_overrides[get_socket_user] = lambda: "alice"`, keyed by the original function object. FastAPI consults the overrides when it solves a WebSocket route's dependencies, exactly as on HTTP routes. Clear the dict in the test's teardown so later tests see the real dependency, and keep one test without the override to cover the refusal path.
  • Why might a FastAPI WebSocket test hang instead of failing?
    The session's `receive_text()` and `receive_json()` wait for the endpoint's next message with no timeout. If the endpoint is waiting for input, or a code path skips its reply, both sides wait forever. Keep each exchange a strict send-then-receive, assert closes by catching `WebSocketDisconnect`, and put a timeout on the test run so a mistake shows up as a failure.
  • What does the test see when the endpoint raises HTTPException before accept()?
    A `WebSocketDenialResponse`, which Starlette's test client raises when the app answers the upgrade with an HTTP response instead of accepting or closing. It subclasses `WebSocketDisconnect` and also carries the HTTP `status_code` and body, so a test catching only `WebSocketDisconnect` still catches it but should assert the status, not a close code.

  • Calling websocket_connect() without a with block opens a usable session.
  • A refused connection makes websocket_connect() return None.
  • The test client reproduces Uvicorn's 403 answer to a refused handshake.
  • dependency_overrides does not apply to WebSocket routes.
  • receive_json() in a test fails after a default timeout when nothing arrives.