Testing the Root Endpoint
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.Testing the Create User Endpoint
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:
Validating the Response Schema
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:UserOut model with the returned JSON data. This method automatically validates the structure of the response.
Handling Duplicate User Creation
At times, using the same email for multiple tests can trigger an IntegrityError due to a duplicate key violation. An example error message might be: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.
Final Test Code
Below is the consolidated version of our test code after all improvements: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.