Test a Middleware with a Header in FastAPI


This is a method to test a FastAPI middleware that reads an HTTP header.

The Middleware

Let's make a little FastAPI app. It has one endpoint. The middleware on that endpoint will test for the existence of x_my_header. If it's not set, an exception will be thrown.

from fastapi import Depends, FastAPI, Header, HTTPException
from typing import Union

async def middleware(x_my_header: Union[str, None] = Header(default=None)):
    if not x_my_header:
      raise HttpException('No header!')

app = FastAPI()

@app.get("/", dependencies=[Depends(middleware)])
def protected_endpoint():
    return {"status": "ok"}

The Depends value is the middleware used in the API.

The Header value will read the HTTP request headers and pass it in as a parameter to the function.

Test the Middleware

To test your middleware, you can't just call the middleware function. This is because I don't know how to create a Header with a value and have it pass through. I have to rely on the magic of on FastAPI to do this.

This means that I have to setup a TestClient and run it as a FastAPI app in the test environment. This lame. If anyone can learn me how to do it better, please contact me.

But for now, set up the TestClient, make the request and verify that the middleware-thrown exception is thrown:

from app import app
from fastapi import HTTPException
from fastapi.testclient import TestClient

client = TestClient(app)

def test_require_header_missing():
    with pytest.raises(HttpException) as exc_info:
        response = client.get("/")

    assert str(exc_info.value) == "No header!"