Sitemap
Fedor GNETKOV

Fedor GNETKOV

Software developer, founder and creator of Astudium.com

Testing FastAPI Application with Pytest

12 min readAug 27, 2024

--

Today we will look at testing a FastAPI application using Pytest, set up the tests, and go over some good practices. What exactly will we cover?

  1. Fixtures: We will discuss what fixtures are and how they simplify testing.
  2. Using a test database: We will configure the tests to use a PostgreSQL database that is separate from the local development database and intended exclusively for tests.
  3. Creating model Factories: We will simplify the creation of test data in the database. For example, creating a user in the database using a factory like user: User = UserFactory(). Just one line without arguments will create a user with realistic random data in the database.
  4. Creating clients with authorization for API tests. We will create a test client to test protected API routes, i.e. routes requiring authentication.
  5. Tests: We will write a few simple CRUD and API tests.
  6. Tests with external service patching. We will write a test that patches the Google Authentication service to avoid making calls to the Google API during the tests.
  7. Tests with parameterization. We will write a test using different data sets as input to cover various scenarios in a single test.

You can view all the code and run it on your local machine. It is available in the repository: https://gitlab.com/FedorGN/todo-fastapi-reactjs.

I discussed the project “todo-fastapi-reactjs” in more detail in an article: Modern Application Template with FastAPI, ReactJS, Docker.

Backend tests are located in the backend/app/tests folder. The code modifications will be made in this folder.

Fixtures

Software test fixtures initialize test functions. They provide a fixed baseline so that tests execute reliably and produce consistent, repeatable results. Initialization may involve setting up services, states, or other operating environments. [https://docs.pytest.org/]

All fixtures in Pytest should be placed in the tests/conftest.py file. conftest.py is a configuration file in Pytest that is used to define fixtures, hooks, and configuration options shared across multiple test modules. conftest.py is a place to centralize reusable test setup logic and configurations.

Here’s a simple example of a fixture and its use:

import pytest

@pytest.fixture
def my_car() -> str:
return "Toyota"

def test_my_car_toyota(my_car: str):
assert my_car == "Toyota" # True

def test_my_car_honda(my_car: str):
assert my_car == "Honda" # False

In this example, we create a fixture my_car that replaces the argument my_car in the tests test_my_car_toyota and test_my_car_honda.

Fixtures can have different scopes, which define how often the fixture is invoked:

  • Function (scope=”function”): (Default) The fixture is created and destroyed for each test function.
  • Class (scope=”class”): The fixture is created once per test class and shared across all methods of the class.
  • Module (scope=”module”): The fixture is created once per module and shared across all tests within that module.
  • Session (scope=”session”): The fixture is created once per test session and shared across all tests in the session.

Fixtures can be automatically applied to all tests within a given scope without having to explicitly include them as arguments by using the autouse=True option.

Here is another example of how to use a fixture:

@pytest.fixture(scope="session", autouse=True)
def setup_test_database():

Creating and Deleting Test Database, Tables, and Data

Initially, Pytest in the project used the local database for tests, meaning it was the same database that the developer uses. This is inconvenient because data already exists in the database, and moreover the tests create new data.

Therefore, it makes sense to set up the tests in such a way:

  • Tests use a separate test database.
  • All tables are created before all tests, because the developer may change the database schema during development.
  • All data is deleted after each test, as tests should be isolated from each other. Data created in one test should not affect the next test.

Let’s configure the database in the tests/conftest.py file.

# Set up a test database URL
TEST_SQLALCHEMY_DATABASE_URL: str = settings.POSTGRESQL_TEST_DATABASE_URI
admin_engine = create_engine(
settings.POSTGRESQL_ADMIN_DATABASE_URI, isolation_level="AUTOCOMMIT"
)

# Create an engine and sessionmaker bound to the test database
engine = create_engine(TEST_SQLALCHEMY_DATABASE_URL)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def create_test_database():
"""Create the test database if it doesn't exist."""
with admin_engine.connect() as connection:
try:
connection.execute(
text(f"CREATE DATABASE {TEST_SQLALCHEMY_DATABASE_URL.split('/')[-1]}")
)
except ProgrammingError:
print("Database already exists, continuing...")


@pytest.fixture(scope="session", autouse=True)
def setup_test_database():
"""
Create the test database schema before any tests run,
and drop it after all tests are done.
"""
create_test_database() # Ensure the test database is created
Base.metadata.create_all(bind=engine) # Create tables
yield
Base.metadata.drop_all(bind=engine) # Drop tables after tests


@pytest.fixture(scope="function")
def db() -> Generator:
"""
Create a new database session for each test and roll it back after the test.
"""
connection = engine.connect()
transaction = connection.begin()
session = TestingSessionLocal(bind=connection)

yield session

session.close()
transaction.rollback()
connection.close()

Please note that we created two engines:

  • admin_engine: This is used to connect to the PostgreSQL server with higher privileges so that we can perform administrative tasks, such as creating and managing databases.
  • engine: This is connected to the specific test database, which is used for running your tests.

The purpose of the admin_engine is to create the test database on the PostgreSQL server using the create_test_database function if the test database does not already exist.

After this, we created two fixtures:

  • setup_test_database: This fixture creates the database with a “Session” scope. It sets up the tables before all tests and removes them after all tests are completed. This function does not use Alembic migrations; it creates schemas based on the current SQLAlchemy model structure.
  • db: This fixture yields a session with the test database. It creates a transaction that is rolled back after each test completes, ensuring that each test is isolated.

Thus, we have configured Pytest to use a separate PostgreSQL test database.

Creating Model Factories

When writing tests for a back-end of web application, we almost always need initial data in the database.

For example, in our specific application, if we want to write a test for the API to get a list of todos, we will at least need a User and a few Todo records. This is the case for almost every test — initial data in the database is always needed. In a FastAPI application, we typically work with SQLAlchemy models.

I will use the popular package factory_boy for this purpose. [https://factoryboy.readthedocs.io/en/stable/]

We have two models in the application: User and Todo. Let’s create a factories for them.

File tests/factories/user.py:

import factory
from app.models.user import User
from app.core.security import get_password_hash
from app.tests.constants.user import UserTestConstants


class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = User # SQLAlchemy model
sqlalchemy_session_persistence = "commit" # Commit the session after creating the user instance.

email = factory.Faker("email")
hashed_password = factory.LazyFunction(
lambda: get_password_hash(UserTestConstants.USER_DEFAULT_PASSWORD)
)
is_active = True
is_superuser = False
first_name = factory.Faker("first_name")
last_name = factory.Faker("last_name")


@classmethod
def _create(cls, model_class, *args, **kwargs):
# Handle the password argument before creating the user
if "password" in kwargs:
kwargs["hashed_password"] = get_password_hash(kwargs.pop("password"))
return super()._create(model_class, *args, **kwargs)

The Meta class is used to configure the Factory.

For generating random values, we use the Faker package. It allows generating realistic values depending on the context (first name, last name, email, random words etc.). [https://faker.readthedocs.io/en/master/]

Take note of the default value for hashed_password. By default, each user will have a password defined in UserTestConstants.USER_DEFAULT_PASSWORD.

However, if a developer wants, they can set any other password simply by writing

user: User = UserFactory(password="my_custom_password")

The new password is set in this case because we override the _create method. This method is called during the creation of the Factory.

Now, let’s create a Factory for Todo in the tests/factories/todo.py file.

import factory
from app.models.todo import Todo
from app.tests.factories.user import UserFactory


class TodoFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = Todo
sqlalchemy_session_persistence = "commit"

title = factory.Faker("word")
is_done = factory.Faker("boolean")
owner = factory.SubFactory(UserFactory)

In this Factory, we set a default value for the owner. What does this mean in practice? It means that if we don’t provide an owner value, the TodoFactory will also create a user in addition to the Todo by default.

Get Fedor GNETKOV’s stories in your inbox

Join Medium for free to get updates from this writer.

For SQLAlchemy Factories, a mandatory parameter in the configuration within the Meta class is sqlalchemy_session. This is the session that will be used to create objects in the database. We haven’t set it in the Factories to avoid circular imports. Instead, we set its value in a fixture in the tests/conftest.py file.

@pytest.fixture(autouse=True)
def set_session_for_factories(db: Session):
UserFactory._meta.sqlalchemy_session = db
TodoFactory._meta.sqlalchemy_session = db

Thus, we have created Factories that can be used for simple and quick generation of objects in the database.

Test API Clients with authentication

FastAPI provides TestClient, which can be used to test endpoints. However, we want to extend the functionality of TestClient as follows:

  • The TestClient should use the test database.
  • We want to have a TestClient with authentication, meaning a user must be created, and the TestClient should have a valid access_token in the headers. We want to have two such TestClient instances: one with a superuser and one with a regular user.

Let’s implement this. We’ll create a TestClient fixture that uses the test database. Add the following to the tests/conftest.py file:

@pytest.fixture(scope="function")
def client(db: Session) -> Generator[TestClient, None, None]:
"""
Provide a TestClient that uses the test database session.
Override the get_db dependency to use the test session.
"""

def override_get_db():
yield db
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()

app.dependency_overrides[get_db] = override_get_db overrides the get_db dependency in the FastAPI app with the override_get_db function. This ensures that whenever the get_db dependency is called (e.g., in API routes), it will use the test session provided by the fixture.

The client fixture can be used for routes not requiring authentication.

Now, let’s create fixtures for authenticated users in the tests/fixtures/authorization.py file.

from typing import Generator
import pytest
from app.models.user import User
from app.tests.constants.user import UserTestConstants
from app.tests.factories.user import UserFactory
from fastapi.testclient import TestClient
from app.core import security


@pytest.fixture(scope="function")
def client_superuser(client: TestClient) -> Generator[TestClient, None, None]:
"""
Fixture that returns a TestClient with superuser authentication headers.
It also creates a user in DB.
"""
user: User = UserFactory(
is_superuser=True,
email=UserTestConstants.CLIENT_SUPERUSER_EMAIL,
password=UserTestConstants.CLIENT_SUPERUSER_PASSWORD,
)
access_token: str = security.create_access_token(user.id)
headers = {"Authorization": f"Bearer {access_token}"}
# Modify the client to automatically include the superuser headers in each request
client.headers.update(headers)
yield client
# Clean up: Remove the superuser headers after the test
client.headers.clear()


@pytest.fixture(scope="function")
def client_user(client: TestClient) -> Generator[TestClient, None, None]:
"""
Fixture that returns a TestClient with authentication headers. It also creates a user in DB.
"""
user: User = UserFactory()
access_token: str = security.create_access_token(user.id)
headers = {"Authorization": f"Bearer {access_token}"}
client.headers.update(headers)
yield client
client.headers.clear()

In the client_superuser function, we create a superuser, generate a token, and add the token to the headers. We do the same in the client_user function.

Now, we can test endpoints with authenticated users.

Tests

Now that tests are set up to use a test database, and we have Factories and authenticated clients, we can write tests that focus solely on testing, without code repetition, thanks to the fixtures.

Let’s write tests for CRUD operations on Todo in the file tests/crud/test_todo.py.

from sqlalchemy.orm import Session  # type: ignore

from app import crud
from app.models.todo import Todo
from app.models.user import User
from app.schemas.todo import TodoCreate
from app.tests.factories.user import UserFactory
from faker import Faker


def test_create_todo(db: Session) -> None:
user: User = UserFactory()
title = Faker().word()
todo_in = TodoCreate(title=title)
todo = crud.todo.create_with_owner(db=db, obj_in=todo_in, owner_id=user.id)
assert todo.title == title
assert todo.owner_id == user.id


def test_get_todo(db: Session, todo: Todo) -> None:
stored_todo = crud.todo.get(db=db, id=todo.id)
assert stored_todo
assert todo.id == stored_todo.id
assert todo.title == stored_todo.title
assert todo.owner_id == stored_todo.owner_id


def test_delete_todo(db: Session, todo: Todo) -> None:
todo2 = crud.todo.remove(db=db, id=todo.id)
todo3 = crud.todo.get(db=db, id=todo.id)
assert todo3 is None
assert todo2.id == todo.id
assert todo2.title == todo.title
assert todo2.owner_id == todo.owner_id

We created simple CRUD tests for Todo using the db and todo fixtures. For example, in the test_delete_todo test, the Todo that we want to delete was created using the todo fixture.

Now, let’s create tests for the login endpoints.

from faker import Faker
from fastapi.testclient import TestClient
from unittest.mock import MagicMock, patch
from app import crud, schemas
from app.core.config import settings
from app.models.user import User
from app.tests.factories.user import UserFactory
from sqlalchemy.orm import Session # type: ignore
from jose import jwt # type: ignore
from app.core import security


def test_get_access_token(client: TestClient) -> None:
password: str = "password"
user: User = UserFactory(password=password)
login_data: dict = {
"username": user.email,
"password": password,
}
r = client.post(f"{settings.API_V1_STR}/login/get-access-token", data=login_data)
tokens: dict = r.json()
assert r.status_code == 200
assert "access_token" in tokens
assert tokens["access_token"]


def test_use_access_token(client: TestClient, client_user: TestClient) -> None:
r = client_user.post(
f"{settings.API_V1_STR}/login/verify-token",
)
result = r.json()
assert r.status_code == 200
assert "email" in result


def test_forgot_email_not_existing_email(client: TestClient) -> None:
email = Faker().email()
r = client.post(f"{settings.API_V1_STR}/login/password-recovery/{email}")
assert r.status_code == 201


def test_forgot_email_existing_email(client: TestClient, ordinary_user: User) -> None:
email = ordinary_user.email
r = client.post(f"{settings.API_V1_STR}/login/password-recovery/{email}")
assert r.status_code == 200

In the test_get_access_token test, we create a user using UserFactory within the function to demonstrate an example of how to use UserFactory. Alternatively, we could have created the user using the ordinary_user fixture. For example:

def test_get_access_token(client: TestClient, ordinary_user: User) -> None:
login_data: dict = {
“username”=UserTestConstants.ORDINARY_USER_EMAIL,
“password”=UserTestConstants.ORDINARY_USER_PASSWORD,
}
r = client.post(f"{settings.API_V1_STR}/login/get-access-token", data=login_data)

A brief note: I use the enum UserTestConstants to gather constants related to users in one place, avoiding the need to write them out each time in a new file, or worse, using the same strings in different parts of the code. Using Enum allows you to change a value once in the Enum and be confident that the code works as expected, without needing to search through the code for repeated strings. When a project becomes large and involves many developers, repeated strings can become a real problem.

File: tests/constants/user.py:

from sqlalchemy import Enum

class UserTestConstants(Enum):
# Default password for UserFactory
USER_DEFAULT_PASSWORD = "password"

# Users used for TestClient with authentification headers
# Credentials super user
CLIENT_SUPERUSER_EMAIL = "client.superuser@email.com"
CLIENT_SUPERUSER_PASSWORD = "client_superuser_password"
# Credentials ordinary user
CLIENT_ORDINARY_USER_EMAIL = "client.ordinary@email.com"
CLIENT_ORDINARY_USER_PASSWORD = "client_ordinary_password"

# Credentials ordinary user
ORDINARY_USER_EMAIL = "user@email.com"
ORDINARY_USER_PASSWORD = "user_password"

Using patch

Let’s test the following endpoint for autentication through Google:

@router.post('/login/google-auth', response_model=schemas.Token)
async def auth_credentials(
credentials: str = Body(..., embed=True),
db: Session = Depends(deps.get_db)):
"""Swap google token to app jwt token."""
try:
idinfo = id_token.verify_oauth2_token(
credentials, requests.Request(), settings.GOOGLE_AUTH_CLIENT_ID)
except Exception:
raise HTTPException(
status_code=400, detail="Incorrect google credentials.")
user_email = idinfo['email']

In this endpoint, there is a call to the Google service to verify the Google token. However, the problem is that the test users do not have Google accounts, and we do not want to test Google’s services because that is beyond our scope. The functionality of Google’s endpoints is tested by Google’s engineers. However, we still want to test this endpoint to ensure that the rest of our code works as expected. How can we do this? For this purpose, we will use the patch function from the unittest package.

Let’s add a test for the /login/google-auth endpoint. This will go into the tests/api/api_v1/test_login.py file.

@patch("app.api.api_v1.endpoints.login.id_token.verify_oauth2_token")
def test_google_auth(
mock_verify_oauth2_token: MagicMock,
client: TestClient,
db: Session,
ordinary_user: User,
):
# Mock data to return from the patched `verify_oauth2_token` function
mock_verify_oauth2_token.return_value = {
"email": ordinary_user.email,
}
data: dict = {"credentials": "string"}
r = client.post(f"{settings.API_V1_STR}/login/google-auth", json=data)
assert r.status_code == 200
access_token: str = r.json()["access_token"]
payload = jwt.decode(
access_token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
token_data = schemas.TokenPayload(**payload)
user = crud.user.get(db, id=token_data.sub)
assert user.id == ordinary_user.id

In this test, we “replaced” the verify_oauth2_token function with mock_verify_oauth2_token, which returns the value we need without making a call to Google services.

This allows us to test the endpoint without making a call to Google’s endpoint.

Patch can be useful in many cases where your application uses third-party services. Additionally, patch can be used to change the values of environment variables.

Parametrizing Tests

Very often, you need to test the same function with different arguments. You could write many tests, but this would lead to an increase in code, code repetition, and reduced readability. All of this would make the tests harder to maintain and understand. To avoid this, you should use the parametrize decorator.

Let’s create a test for the create todo endpoint. File: tests/api/api_v1/test_todo.py.

@pytest.mark.parametrize(
"data, expected_status_code",
[
({"title": "Foo"}, 200), # Test with valid data
({"invalid_key": ""}, 422), # Test without key title
({"title": ""}, 422), # Test with empty title
({"title": None}, 422), # Test with None as title
("title", 422), # Test without dict
],
)
def test_create_todo(
client_user: TestClient, data: Union[dict, str], expected_status_code: int
) -> None:
response = client_user.post(
f"{settings.API_V1_STR}/todos/create-todo",
json=data,
)
assert response.status_code == expected_status_code

This test will run 5 times with different values for data and expected_status_code. We test the create-todo endpoint with different input data. The first test is for successful creation of a todo, while the others are validation errors (e.g., incorrect key in the dictionary, empty title string, etc.).

Instead of writing a new test function, we simply add a new element to the decorator’s list. Using the parametrize decorator reduces repetition, making the tests easier to read and maintain.

Conclusion

We have ended up with the following file structure:

tests/
├── api/ # API related tests
│ ├── api_v1/ # Tests for API version 1
│ │ ├── test_login.py # Tests for login functionality
│ │ ├── test_todos.py # Tests for todos functionality
│ │ ├── test_users.py # Tests for user-related functionality
│
├── constants/ # Storage of test constants
│ └── user.py # Constants related to users
│
├── crud/ # CRUD-related tests
│ ├── test_todo.py # Tests for CRUD operations on todos
│ └── test_user.py # Tests for CRUD operations on users
│
├── factories/ # SQLAlchemy model factories for tests
│ ├── todo.py # Factory for Todo model
│ └── user.py # Factory for User model
│
├── fixtures/ # Test fixtures
│ ├── authorization.py # Fixtures for authorization
│ ├── todo.py # Fixtures for todo-related tests
│ └── user.py # Fixtures for user-related tests

We improved the tests by doing the following:

  • Used a test PostgreSQL database to ensure isolation and repeatability of tests.
  • Added fixtures to set up tests and avoid code repetition.
  • Added Factory to simplify the creation of test data and reduce repetitive code.
  • Created an API Test Client with autentication for testing API endpoints.
  • Wrote a few tests using fixtures.
  • Created a test using patch to avoid calling an external service during tests.
  • Implemented a parameterized test to test the API with different data inputs.

The source code of the project is avaliable on GitLab: https://gitlab.com/FedorGN/todo-fastapi-reactjs .

Press enter or click to view image in full size
Test results.

Useful Links:

  1. https://medium.com/@gnetkov/modern-application-template-with-fastapi-reactjs-docker-2a87e44dc3b0 — article “Modern Application Template with FastAPI, ReactJS, Docker”
  2. https://docs.pytest.org/ — pytest package official website.
  3. https://factoryboy.readthedocs.io/en/stable/ — Factory Boy package official documentation.

--

--

Fedor GNETKOV
Fedor GNETKOV

Software developer, founder and creator of Astudium.com