How to change the client's hostname of FastAPI's TestClient?

Viewed 67

Within my code I take the IP-address from client.host in the request object and send this to another function, where I'm using Pydantic's IPvAnyAddress to validate if it is a valid IP-address.

Here is my code:

from fastapi import APIRouter, Request
from pydantic import IPvAnyAddress


route = APIRouter()


@route.get("/ip-address")
def request_ip_address_deblock_link(request: Request):
    return example_function(request.client.host)

def example_function(ip_address: IPvAnyAddress):
    print(ip_address)

But when I'm using FastAPI's TestClient to test my API routes, the IP-address check fails, as the hostname in the request is testclient.

ValueError: 'testclient' does not appear to be an IPv4 or IPv6 address

Is it possible to change the hostname of FastAPI/Starlette's TestClient?

1 Answers

From Starlette's source code on testclient.py here (that FastAPI actually uses under the hood, see here), the testclient hostname seems to be fixed/hardcoded.

Hence, you could simply check on server side if request.client.host == 'testclient' inside a Dependency function (as @MatsLindh suggested in the comments section), and then, either override testclient with the local IP address (if you are testing this locally), or raise some exception.

Alternatively, you could use the HTTPX library, also suggested in the FastAPI documentation. FastAPI/Starlette's TestClient is now built on httpx (see the relevant commit on github).

Related