Home > Net >  Can FastAPI test client be called by something external?
Can FastAPI test client be called by something external?

Time:04-23

I am writting tests for FastAPI application. And first time in my life I needed to do loadtesting (with locust).
For load test I've made fixture that launches application with uvicorn in separate process.
But it causes some issues.

I thought: May be I could use FastAPI test client for that, but discovered, that I can not understand how test client works. Because, apparently, I can not call test client from outside.
Can anyone explain why and can I make TestClient available for other calls?
Setting base url as localhost does not help.

from fastapi import FastAPI
from fastapi.testclient import TestClient
import requests

app = FastAPI()


@app.get("/")
def index():
    return "ok"


if __name__ == "__main__":
    test_client = TestClient(app)
    print(f"{test_client.base_url=}")  # http://testserver

    r_client = test_client.get("/")
    r_requests = requests.get(f"{test_client.base_url}/")

    assert r_client.status_code == 200  # True
    assert r_requests.status_code == 200  # False, ConnectionError, Why?

CodePudding user response:

The TestClient isn't a webserver - it's a client that simulates regular http requests. It does this by emulating the ASGI interface and setting up the request context without actually having the overhead of making an HTTP request.

Since there is no server running, you can't make any requests against it from outside itself - it just lets you interact with the ASGI application as any regular outside client would do, without the extra overhead of going through a full http stack. This makes testing more efficient and lets you test your applications without having an active http server running while the tests run.

If you're going to do load testing of an application, use the same http stack as you'd do in production (so uvicorn, gunicorn, etc.), otherwise the test situation won't really reflect how your application and setup will behave under load. If you're doing performance regress testing, using the TestClient would probably be sufficient (since your application will be the one were performance varies).

  • Related