Setup TestCase using Pytest in FastAPI App
Tags: fastapi, testing, testcase, pytest
Published: 2023-01-28 05:58:16

Setting up test cases for a FastAPI app using pytest can be a straightforward process. Pytest is a popular testing framework for Python that makes it easy to write and run tests for your application. In this article, we will discuss the steps to set up test cases for a FastAPI app using pytest.

Install pytest: The first step is to install pytest. You can do this by running the command `pip install pytest` in your terminal.

Create a test folder: Create a folder named "tests" in your project's root directory. This folder will contain all of your test files.

Create test files: Create test files with a name that starts with "test_" inside the "tests" folder. These files will contain your test cases.

Import your FastAPI app: In each test file, import your FastAPI app using the from keyword. This will allow you to access the endpoints and routes of your app in your test cases.

Use the TestClient: FastAPI provides a TestClient class that allows you to easily test your app's endpoints. You can use this class to send HTTP requests to your endpoints and assert that the correct response is returned.

Write test cases: In each test file, write test cases that test different aspects of your app. For example, you can test that a specific endpoint returns the correct status code, or that a specific route is accessible only to authenticated users.

Run the tests: To run the tests, simply run the command pytest in your terminal from the root directory of your project. This will run all the tests in the "tests" folder and display the results in the terminal.

Use fixtures: Pytest fixtures provide a way to set up a specific test environment. You can use them to prepare the data needed for the test, and to clean up the data after the test.

## Here is the practical example to setup in app

```
tests\
    conftest.py
    test_rotes\
```

Here `conftest.py` will contain all your db and pytest.fixures related code.

`conftest.py`

```
import os
import sys
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# import your Base and get_db from your db_config
from config.db_config import Base, get_db
from main import app

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

SQLALCHEMY_DATABASE_URL = f"sqlite:///./test_db.db"

engine = create_engine(SQLALCHEMY_DATABASE_URL)

TestingSessionLocal = sessionmaker(autocommit=False, autoflush=True, bin=engine)

def override_get_db():
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db

@pytest.fixure
def client():
   Base.metadata.create_all(bind=engine) # create all table
   yield TestClient(app)
   Base.metadata.drop_all(bind=engine) # drop all table

@pytest.fixure
def get_token():
   # code to generate your token 
```

**Conclusion:**
In conclusion, setting up test cases for a FastAPI app using pytest is a simple process that can be done by following the steps discussed above. By writing test cases and running them regularly, you can ensure that your app is working correctly and catch any bugs early on. Using fixtures can help you in preparing the test environment and cleaning up after the test.

Thanks for your valuable time. You can like my post and
you can.

[By me a Coffee](https://www.buymeacoffee.com/saim783)

[My other Blog Website over Technology](https://www.saimtechnews.in)

[My YouTube Vlog Channel](https://www.youtube.com/@abdullavlogs)