On this page

FastAPI Notifications, WebSockets & Test Coverage Guide

Published on August 16, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Background task notifications, WebSocket broadcasting, and comprehensive test coverage form the final layer of a production‑ready FastAPI application. A background task writes to a log file after every task creation — it runs as a plain synchronous function, scheduled via BackgroundTasks.add_task() to execute after the HTTP response is sent. A ConnectionManager class handles WebSocket connections with asyncio.Lock to protect the active connections list and broadcasts structured JSON events to all connected clients. The test suite covers both features with correct mocking: unittest.mock.patch replaces the notification function for assertion without running real file I/O, and TestClient.websocket_connect() provides synchronous WebSocket testing. The endpoint is async def because it awaits the broadcast, and WebSocketDisconnect is caught by name to prevent masking system exceptions. This lesson integrates these three components into a complete, production‑correct implementation.

info

This exercise is the continuation of hands-on exercises compelted in the previous modules. Be sure to check the previous parts to follow along:


What Changes in This Lesson​


Notifications via Background Tasks​

The notification function writes to a log file after every task creation. It is a plain synchronous def — FastAPI runs it in a thread pool executor, which keeps the event loop free during the file write.

đź“„ routers/tasks.py


from fastapi import APIRouter, Depends, BackgroundTasks

from sqlmodel import Session

from db import get_session

from models.task import Task

from models.user import User

from services import task_service

from core.dependencies import require_active_user

from routers.ws import manager

import logging



logger = logging.getLogger(__name__)



router = APIRouter(prefix="/tasks", tags=["Tasks"])





def send_notification(user: User, message: str) -> None:

    """

    Write a notification entry to the log file.

    Runs in FastAPI's thread pool after the response is sent.

    """

    try:

        with open("notifications.log", "a") as f:

            f.write(f"Notify {user.username}: {message}\n")

    except Exception:

        logger.exception(f"Failed to write notification for user {user.username}")





@router.post("/", status_code=201)

async def create(

    task: Task,

    background_tasks: BackgroundTasks,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    created = task_service.create_task(task, session, user)



    # Schedule notification after commit — task is guaranteed to exist in the DB

    background_tasks.add_task(send_notification, user, f"Task created: {created.title}")



    # Broadcast only after the task is successfully persisted

    await manager.broadcast({

        "event":   "task_created",

        "task_id": created.id,

        "title":   created.title,

        "user_id": created.user_id,

    })



    return created

How background tasks work​

background_tasks.add_task(send_notification, user, ...) schedules send_notification to run after the HTTP response is sent.The user receives the 201 response immediately and the file write happens afterward without blocking them. The BackgroundTasks object is created by FastAPI and passed as a parameter to the path operation function.

send_notification is wrapped in try/except because exceptions inside background tasks are silently swallowed by default. Without explicit error handling, a failed file write would leave no trace in logs or monitoring.

await manager.broadcast(...) runs before return created within the same coroutine. The endpoint is async def because of this await call. The broadcast happens after task_service.create_task() commits the task, so clients receive the event only for tasks that are durably stored.


WebSocket Broadcasting with ConnectionManager​

The ConnectionManager pattern used here has several key properties: WebSocketDisconnect is caught by name (not a bare except:), the broadcast iterates over a copy of the connections list to avoid RuntimeError on modification during iteration, and send_json is used for structured JSON events.

đź“„ routers/ws.py


from fastapi import APIRouter, WebSocket, WebSocketDisconnect

import asyncio



router = APIRouter(prefix="/ws", tags=["WebSockets"])





class ConnectionManager:

    def __init__(self):

        self.active_connections: list[WebSocket] = []

        self._lock = asyncio.Lock()



    async def connect(self, websocket: WebSocket):

        await websocket.accept()

        async with self._lock:

            self.active_connections.append(websocket)



    async def disconnect(self, websocket: WebSocket):

        async with self._lock:

            if websocket in self.active_connections:

                self.active_connections.remove(websocket)



    async def broadcast(self, message: dict):

        stale: list[WebSocket] = []



        async with self._lock:

            targets = list(self.active_connections)  # iterate over a copy



        for connection in targets:

            try:

                await connection.send_json(message)

            except Exception:

                stale.append(connection)



        if stale:

            async with self._lock:

                for ws in stale:

                    if ws in self.active_connections:

                        self.active_connections.remove(ws)





manager = ConnectionManager()





@router.websocket("/tasks")

async def task_updates(websocket: WebSocket):

    await manager.connect(websocket)

    try:

        while True:

            await websocket.receive_text()  # keep-alive; discards client messages

    except WebSocketDisconnect:

        await manager.disconnect(websocket)

The _lock ensures that concurrent modifications to the connections list do not corrupt the data structure. The broadcast method copies the connections list while holding the lock, then releases it before sending messages — this prevents the lock from being held during potentially slow network operations. Failed sends are collected and the dead connections are removed from the list.


Full Test Coverage​

conftest.py — Complete Fixture Set​

The fixtures from the testing lesson are extended with an auth_headers fixture that the notification and WebSocket tests both require.

đź“„ tests/conftest.py


import pytest

from fastapi.testclient import TestClient

from sqlmodel import SQLModel, Session, create_engine

from sqlalchemy.pool import StaticPool

from main import app

from db import get_session



TEST_DATABASE_URL = "sqlite://"



@pytest.fixture(name="engine", scope="session")

def engine_fixture():

    engine = create_engine(

        TEST_DATABASE_URL,

        connect_args={"check_same_thread": False},

        poolclass=StaticPool,

    )

    SQLModel.metadata.create_all(engine)

    yield engine

    SQLModel.metadata.drop_all(engine)



@pytest.fixture(name="session")

def session_fixture(engine):

    with Session(engine) as session:

        yield session



@pytest.fixture(name="client")

def client_fixture(session: Session):

    def override_get_session():

        yield session



    app.dependency_overrides[get_session] = override_get_session

    app.state.limiter.enabled = False



    with TestClient(app) as test_client:

        yield test_client



    app.dependency_overrides.clear()



@pytest.fixture(name="auth_headers")

def auth_headers_fixture(client: TestClient) -> dict:

    client.post(

        "/auth/signup",

        json={

            "username": "testuser",

            "email": "[email protected]",

            "hashed_password": "testpassword123",

        },

    )

    token = client.post(

        "/auth/login",

        data={"username": "testuser", "password": "testpassword123"},

    ).json()["access_token"]

    return {"Authorization": f"Bearer {token}"}

Testing Background Task Notifications​

send_notification is a plain function passed to background_tasks.add_task() — it is not a FastAPI dependency and cannot be overridden with app.dependency_overrides. The correct approach is unittest.mock.patch, which replaces the function in the module where it is used for the duration of the test.

đź“„ tests/test_tasks.py


from unittest.mock import patch, MagicMock

from fastapi.testclient import TestClient





def test_create_task_triggers_notification(client: TestClient, auth_headers: dict):

    """

    Verify that send_notification is called after a successful task creation.



    patch() replaces send_notification in routers.tasks for the duration of this test.

    The mock records every call so we can assert it was called with the correct arguments.

    """

    with patch("routers.tasks.send_notification") as mock_notify:

        response = client.post(

            "/tasks/",

            json={"title": "Test Task", "description": "Notification test"},

            headers=auth_headers,

        )



    assert response.status_code == 201

    assert response.json()["title"] == "Test Task"



    # Verify the background task was scheduled with the correct message

    mock_notify.assert_called_once()

    call_args = mock_notify.call_args

    assert "Task created: Test Task" in call_args.args[1]





def test_create_task_notification_not_called_on_failure(client: TestClient):

    """

    Verify that send_notification is NOT called when task creation fails

    due to missing authentication.

    """

    with patch("routers.tasks.send_notification") as mock_notify:

        response = client.post(

            "/tasks/",

            json={"title": "Should Fail"},

            # No auth_headers — request should be rejected with 401

        )



    assert response.status_code == 401

    mock_notify.assert_not_called()





def test_create_task_notification_failure_does_not_affect_response(

    client: TestClient, auth_headers: dict

):

    """

    Verify that if send_notification raises an exception, the task creation

    response is still successful. Background task failures must not bubble up

    to the client.

    """

    with patch("routers.tasks.send_notification", side_effect=OSError("disk full")):

        response = client.post(

            "/tasks/",

            json={"title": "Resilient Task"},

            headers=auth_headers,

        )



    # The task was created successfully — the background failure is invisible to the client

    assert response.status_code == 201

Why patch and not dependency_overrides​

dependency_overrides only intercepts functions that are declared as FastAPI dependencies — those injected via Depends(). send_notification is a plain Python function passed as an argument to background_tasks.add_task(). It is not a dependency, so dependency_overrides has no effect on it and the original function runs regardless.

unittest.mock.patch("routers.tasks.send_notification") replaces the name send_notification in the routers.tasks module with a MagicMock for the duration of the with block. After the block exits, the original function is restored. TestClient runs background tasks synchronously before returning from the request method, so the mock will have been called by the time assertions run.


Testing WebSocket Broadcasts​

TestClient.websocket_connect() is a synchronous context manager. The WebSocket test must be a plain def function, not async def. Using @pytest.mark.asyncio on a synchronous TestClient test is incorrect and produces errors or undefined behaviour.

đź“„ tests/test_ws.py


from unittest.mock import patch, AsyncMock

from fastapi.testclient import TestClient





def test_websocket_receives_task_created_event(client: TestClient, auth_headers: dict):

    """

    Connect a WebSocket client, create a task via the REST API,

    and verify the client receives a structured JSON broadcast event.

    """

    with client.websocket_connect("/ws/tasks") as ws:

        response = client.post(

            "/tasks/",

            json={"title": "WS Task", "description": "WebSocket test"},

            headers=auth_headers,

        )

        assert response.status_code == 201



        message = ws.receive_json()



    assert message["event"] == "task_created"

    assert message["title"] == "WS Task"

    assert "task_id" in message

    assert "user_id" in message





def test_websocket_connection_accepts_and_closes_cleanly(client: TestClient):

    """

    Verify that connecting and disconnecting without sending any messages

    does not raise an exception on the server side.

    """

    with client.websocket_connect("/ws/tasks"):

        pass  # Connect and immediately exit the context — triggers clean disconnect





def test_multiple_clients_all_receive_broadcast(client: TestClient, auth_headers: dict):

    """

    Verify that multiple simultaneous WebSocket clients all receive

    the broadcast when a task is created.

    """

    with client.websocket_connect("/ws/tasks") as ws1:

        with client.websocket_connect("/ws/tasks") as ws2:

            client.post(

                "/tasks/",

                json={"title": "Multi-client task"},

                headers=auth_headers,

            )



            msg1 = ws1.receive_json()

            msg2 = ws2.receive_json()



    assert msg1["event"] == "task_created"

    assert msg2["event"] == "task_created"

    assert msg1["title"] == "Multi-client task"

    assert msg2["title"] == "Multi-client task"





def test_broadcast_not_sent_when_task_creation_fails(client: TestClient):

    """

    Verify that the WebSocket broadcast does not fire when task creation

    fails due to missing authentication.

    """

    with patch("routers.tasks.manager.broadcast", new_callable=AsyncMock) as mock_broadcast:

        response = client.post(

            "/tasks/",

            json={"title": "Should not broadcast"},

            # No auth — 401 expected, no broadcast should occur

        )



    assert response.status_code == 401

    mock_broadcast.assert_not_called()

Why the WebSocket test is def, not async def​

TestClient.websocket_connect() is a synchronous context manager provided by Starlette.It handles the ASGI protocol internally in a synchronous wrapper. When the test function is async def, pytest‑asyncio runs it in an event loop that conflicts with the internal event loop TestClient uses for the WebSocket handshake, causing errors. The correct pattern is a plain def test with a synchronous client.websocket_connect() call and synchronous ws.receive_json() inside.


Running the Full Test Suite​


# Run all tests with verbose output

python -m pytest -v



# Run only the notification tests

python -m pytest tests/test_tasks.py -v -k "notification"



# Run only the WebSocket tests

python -m pytest tests/test_ws.py -v



# Run with coverage report (requires pytest-cov)

pip install pytest-cov

python -m pytest --cov=. --cov-report=term-missing

Project File Summary​

FileChanges in this lessonrouters/tasks.pyAdded send_notification, changed create to async def, added BackgroundTasks injection, added await manager.broadcast() after commitrouters/ws.py``ConnectionManager class with asyncio.Lock, send_json broadcast, WebSocketDisconnect handled by nametests/conftest.pyExtended with auth_headers fixturetests/test_tasks.pyNotification tests using unittest.mock.patch``tests/test_ws.pyWebSocket tests using synchronous TestClient.websocket_connect()


Common Mistakes to Avoid​

Using app.dependency_overrides to mock a background task function. Dependency overrides only intercept FastAPI Depends() dependencies.A function passed to background_tasks.add_task() is not a dependency — the override is silently ignored and the real function runs. Use unittest.mock.patch instead.

Writing WebSocket tests as async def with @pytest.mark.asyncio. TestClient.websocket_connect() is synchronous.Using it inside an async def test creates event loop conflicts. WebSocket tests using TestClient must be plain def functions.

Using a bare except: in the WebSocket endpoint. This catches SystemExit and KeyboardInterrupt, masking application bugs and making the server hard to stop. Always catch WebSocketDisconnect by name.

Broadcasting before the database commit. If the broadcast fires and then the database operation fails, clients receive an event for a task that was never saved. Always commit first, then broadcast.

Not wrapping send_notification in try/except. Background task exceptions are silently swallowed. A disk‑full or permission error on the log file write will fail invisibly unless caught and logged explicitly inside the task function.


Practice Challenge​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Testing FastAPI Applications

Next

Deployment and Monitoring