Escriu per cercar…

Test

Aquesta pàgina encara no s'ha traduït — es mostra en l'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 llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió