FastAPI 测试客户端可以被外部调用吗?

Can FastAPI test client be called by something external?

我正在为 FastAPI 应用程序编写测试。我有生以来第一次需要进行负载测试(使用蝗虫)。
对于负载测试,我制作了在单独的进程中使用 uvicorn 启动应用程序的装置。
但它会导致一些问题。

我想:也许我可以为此使用 FastAPI 测试客户端,但发现我无法理解测试客户端的工作原理。因为,显然,我无法从外部调用测试客户端。
任何人都可以解释为什么以及我可以让 TestClient 可用于其他调用吗?
将 base url 设置为 localhost 没有帮助。

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?

TestClient 不是网络服务器 - 它是 模拟 常规 http 请求的客户端。它通过模拟 ASGI 接口和设置请求上下文来实现这一点,而实际上没有发出 HTTP 请求的开销。

由于没有服务器 运行ning,您不能从外部对它发出任何请求 - 它只是让您与 ASGI 应用程序交互,就像任何常规外部客户端所做的那样,没有额外的通过完整的 http 堆栈的开销。这使测试更加高效,并让您在测试 运行.

时无需活动的 http 服务器 运行ning 即可测试您的应用程序

如果您要对应用程序进行负载测试,请使用与生产中相同的 http 堆栈(例如 uvicorn、gunicorn 等),否则测试情况将无法真正反映出如何您的应用程序和设置将在负载下运行。如果您正在进行性能回归测试,使用 TestClient 可能就足够了(因为您的应用程序将是性能变化的应用程序)。