Running FastAPI Tests in ‘Test’ Mode

When developing and testing FastAPI applications, it’s often desirable to run the application in a ‘test’ mode with specific configurations or behaviors. This can help isolate tests, prevent unintended side effects, and streamline the development process.

Creating a Test Configuration

Define a Configuration Model:

Python

from pydantic import BaseModel

class Settings(BaseModel):
debug: bool = True
test_mode: bool = False

Load the Configuration:

Python

from dotenv import load_dotenv
from pathlib import Path

def get_settings():
load_dotenv()
return Settings()

Inject the Configuration into Endpoints:

Python

from fastapi import Depends

def get_settings(settings: Settings = Depends(get_settings)):
return settings

Running Tests in Test Mode

Set the TEST_MODE Environment Variable:

Bash

export TEST_MODE=True

Use the Configuration in Tests:

Python

def test_read_root(client, settings: Settings = Depends(get_settings)):
assert settings.test_mode
# Perform test logic

Conditional Logic in Endpoints

You can use the test_mode flag to conditionally modify the behavior of your endpoints:

Python

@app.get("/")
def read_root(settings: Settings = Depends(get_settings)):
    if settings.test_mode:
        return {"message": "This is test mode"}
    else:
        # Regular endpoint logic

By running FastAPI tests in ‘test’ mode, you can create a controlled environment for testing your application’s functionality, ensuring that it behaves as expected in different scenarios.

Utilizing Databases in FastAPI Routers
Database Connections Using Lifespan Events in FastAPI

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?