FastAPI Backend Development Bootcamp · Lekcja

Testy integracyjne endpointów FastAPI

Wykonają Państwo testy integracyjne endpointów API za pomocą `TestClient` biblioteki FastAPI, aby symulować żądania.

Lekcja 2 z 411 kroki

Testy integracyjne endpointów FastAPI to bezpłatna lekcja FastAPI Backend Development Bootcamp na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej FastAPI Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

What is Integration Testing?

Welcome to integration testing! After learning about unit tests, it's time to see how different parts of your FastAPI application work together.

  • Unit tests check individual functions or components in isolation.
  • Integration tests verify that multiple components of your system interact correctly. For a FastAPI app, this means testing your API endpoints, checking if they handle requests, interact with dependencies, and return expected responses.

These tests ensure your API behaves as expected when all its pieces are connected.

Introducing FastAPI's TestClient

FastAPI provides a powerful tool called TestClient from fastapi.testclient. This client allows you to make HTTP requests to your FastAPI application without needing to run a live server.

  • It simulates requests directly in memory.
  • It's built on top of the popular httpx library.
  • It's perfect for quickly testing your API endpoints during development.

Let's see how to set it up!

Setting Up Your TestClient

To use TestClient, you first need to import your FastAPI application instance and then pass it to the TestClient constructor. This creates a client instance ready to send simulated requests.

Try running this example to see a basic setup:

from fastapi import FastAPI
from fastapi.testclient import TestClient

# 1. Define your FastAPI app
app = FastAPI()

# 2. Define a simple endpoint
@app.get("/hello")
async def read_hello():
    return {"message": "Hello Test!"}

# 3. Create a TestClient instance
client = TestClient(app)

# 4. Define a test function
def test_read_hello():
    # Use the client to make a GET request
    response = client.get("/hello")
    
    # Assertions to check the response
    assert response.status_code == 200
    assert response.json() == {"message": "Hello Test!"}
    print("Test Passed: /hello endpoint works!")

# This block makes the script runnable directly
if __name__ == "__main__":
    print("Running a simple test with TestClient...")
    test_read_hello()

Testing GET Requests

Making GET requests is straightforward. You simply call the .get() method on your TestClient instance, passing the path of the endpoint you want to test.

After making the request, you can access properties of the response object like .status_code and .json() to verify the outcome.

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/")
async def read_items():
    return [{"name": "Laptop"}, {"name": "Mouse"}]

client = TestClient(app)

def test_read_items():
    response = client.get("/items/")
    
    print(f"Status Code: {response.status_code}")
    print(f"Response JSON: {response.json()}")
    
    assert response.status_code == 200
    assert len(response.json()) == 2
    assert response.json()[0]["name"] == "Laptop"
    print("Test Passed: /items/ returns correct data!")

if __name__ == "__main__":
    print("Testing /items/ endpoint...")
    test_read_items()

Testing Path & Query Parameters

TestClient handles path and query parameters just like a real browser. Path parameters are included directly in the URL string, and query parameters can be added to the URL or passed via the params argument.

Using the params argument for query parameters is often cleaner and handles URL encoding automatically.

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

client = TestClient(app)

def test_read_item_with_query():
    # Path param 5, Query param q=hello
    response = client.get("/items/5", params={"q": "hello"})
    assert response.status_code == 200
    assert response.json() == {"item_id": 5, "q": "hello"}
    print("Test Passed: Path & Query params handled!")

def test_read_item_no_query():
    # Only path param 10
    response = client.get("/items/10")
    assert response.status_code == 200
    assert response.json() == {"item_id": 10}
    print("Test Passed: Path param only handled!")

if __name__ == "__main__":
    print("Testing path and query parameters...")
    test_read_item_with_query()
    test_read_item_no_query()

Testing POST Requests with JSON

For endpoints that expect a request body (like POST or PUT), you can pass a Python dictionary directly to the json argument of the client method. TestClient will automatically convert this dictionary into a JSON string and set the appropriate Content-Type header.

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.testclient import TestClient

app = FastAPI()

class Product(BaseModel):
    name: str
    price: float
    description: str | None = None

@app.post("/products/")
async def create_product(product: Product):
    return product

client = TestClient(app)

def test_create_product():
    product_data = {"name": "Widget", "price": 29.99}
    response = client.post(
        "/products/",
        json=product_data
    )
    assert response.status_code == 200
    assert response.json() == {"name": "Widget", "price": 29.99, "description": None}
    print("Test Passed: POST request with JSON body!")

if __name__ == "__main__":
    print("Testing POST request...")
    test_create_product()

Overriding Dependencies for Testing

One of FastAPI's most powerful testing features is the ability to easily override dependencies. This is crucial for integration tests where you might want to:

  • Mock external services (e.g., a payment gateway).
  • Use a test database instead of the production one.
  • Inject specific test data or configurations.

You can temporarily replace a dependency function with a different one using app.dependency_overrides.

Applying Dependency Overrides

To override a dependency, you assign your mock function to the original dependency function in the app.dependency_overrides dictionary. After your test, it's vital to clear these overrides to prevent them from affecting other tests.

Let's see how to replace a 'real' setting with a 'test' setting:

from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient

app = FastAPI()

# Our 'real' dependency function
def get_current_env():
    return "production"

@app.get("/environment/")
async def get_environment(env: str = Depends(get_current_env)):
    return {"current_environment": env}

client = TestClient(app)

def test_get_environment_default():
    response = client.get("/environment/")
    assert response.status_code == 200
    assert response.json() == {"current_environment": "production"}
    print("Default environment test passed!")

def test_get_environment_override():
    # Our mock dependency function for testing
    def override_get_current_env():
        return "test"
    
    # Apply the override
    app.dependency_overrides[get_current_env] = override_get_current_env
    
    response = client.get("/environment/")
    assert response.status_code == 200
    assert response.json() == {"current_environment": "test"}
    print("Overridden environment test passed!")
    
    # IMPORTANT: Clear overrides after the test
    app.dependency_overrides.clear()

if __name__ == "__main__":
    print("Testing dependency overrides...")
    test_get_environment_default()
    test_get_environment_override()

Ensuring Cleanup of Overrides

Failing to clear app.dependency_overrides can lead to 'leaky' tests, where an override from one test unintentionally affects subsequent tests. Always make sure to reset app.dependency_overrides, typically by setting it back to an empty dictionary or using .clear().

This ensures each test runs in a clean, predictable state.

Test Your Knowledge!

Which of the following statements about FastAPI's TestClient is TRUE?

Recap & Next Steps

Great job! You've learned how to perform integration tests on your FastAPI application:

  • We explored what integration testing is and why it's crucial.
  • You mastered setting up and using FastAPI's TestClient to simulate various HTTP requests.
  • We covered testing GET and POST requests, including handling path, query, and JSON body parameters.
  • You now understand how to effectively use dependency overrides to isolate and control your test environment.

These skills are essential for building robust and reliable FastAPI applications. Keep practicing, and you'll be writing comprehensive tests in no time!

Bezpłatny start

Ucz się FastAPI Backend Development Bootcamp dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
21
Lekcje
84

Często zadawane pytania

Czy lekcja „Testy integracyjne endpointów FastAPI” jest bezpłatna?

Tak — pełny tekst „Testy integracyjne endpointów FastAPI” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu FastAPI Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.

Co nauczysz się w „Testy integracyjne endpointów FastAPI”?

Wykonają Państwo testy integracyjne endpointów API za pomocą `TestClient` biblioteki FastAPI, aby symulować żądania. Ćwiczysz FastAPI Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć FastAPI Backend Development Bootcamp?

Nie wymagamy żadnego doświadczenia. FastAPI Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Testy integracyjne endpointów FastAPI”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji FastAPI Backend Development Bootcamp?

Tak. Każda lekcja FastAPI Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Testy jednostkowe za pomocą Pytest
  2. Testy integracyjne endpointów FastAPI
  3. Debugowanie aplikacji FastAPI
  4. Mockowanie zależności w testach FastAPI
← Powrót do FastAPI Backend Development Bootcamp