Escribe para buscar…

Test

Esta página todavía no se ha traducido — se muestra en su idioma original:English

Project setup

First, create a new project and install the required testing dependencies:

ps
uv init test
cd test
uv add fastapi[standard]
uv add --dev pytest httpx

FastAPI testing is built on HTTPX, which shares a similar design with the popular Requests library. This makes testing familiar and intuitive.

Since HTTPX is compatible with PyTest, you can use pytest directly to test your FastAPI applications.

TestClient

Create your FastAPI application in main.py:

python
main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def get():
    return {"message": "Hello World"}

Then create a test file test_main.py:

python
test_main.py
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)


def test_get():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}

Writing Tests

  1. Create a TestClient instance by passing your FastAPI application to it
  2. Define test functions with names starting with test_ (standard pytest convention)
  3. Make HTTP requests using the TestClient object the same way as you would with httpx
  4. Add assertions using standard Python assert statements to verify the expected behavior
Note

Notice that test functions use regular def, not async def.

Client calls are also synchronous (no await needed).

This allows you to use pytest directly without complications.

Estás leyendo una vista previa.

Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión