This article explains how to create tests for user creation functionality in a FastAPI application using TestClient.
In this lesson, we will create tests to verify the user creation functionality of our API using FastAPI’s TestClient. We simulate GET and POST requests to ensure that the API responds correctly.
Before testing user creation, we first verify that the API’s root endpoint is operational. The following test sends a GET request to the ”/” route and asserts that the response includes the message “Hello World” with a status code of 200.
Next, we validate the user creation route. This route expects a POST request to /users/ with JSON data containing an email and a password.Initially, a simple version of the test might look like this:
Copy
Ask AI
from fastapi.testclient import TestClientdef register(): r = 'Hello World'
Now, update the test to send a POST request with a JSON payload. In our endpoint, the schema requires an email and password. We verify that the response status is 201 (Created).
The user creation endpoint is designed to return data that follows a specific schema, including an ID, email, and a created_at timestamp. The expected Pydantic model is defined as follows:
Copy
Ask AI
from pydantic import BaseModel, EmailStrfrom datetime import datetimeclass PostCreate(PostBase): passclass UserOut(BaseModel): id: int email: EmailStr created_at: datetime class Config: orm_mode = Trueclass Post(PostBase): pass
To ensure that the response conforms to this schema, the test imports the schemas and instantiates a UserOut model with the returned JSON data. This method automatically validates the structure of the response.
Copy
Ask AI
from fastapi.testclient import TestClientfrom app.main import appfrom app import schemas # Import schemas to use the UserOut modelclient = TestClient(app)def test_create_user(): res = client.post( "/users/", json={"email": "[email protected]", "password": "password123"} ) # Validate the response using the UserOut schema new_user = schemas.UserOut(**res.json()) # Confirm that the email is correct and the status code is 201 assert new_user.email == "[email protected]" assert res.status_code == 201
To avoid duplicate key errors, ensure that users are either removed from the database between tests or that you use unique email addresses for each test run.
You can run the following SQL command in PgAdmin to view current user entries:
Copy
Ask AI
SELECT * FROM public.usersORDER BY "id" ASC;
After deleting the user entry with the email “[email protected]”, re-running the test should result in a successful user creation.
This approach leverages FastAPI’s TestClient and Pydantic for automatic schema validation, reducing the need for multiple manual assertions and ensuring the correctness of the API responses.