FastAPI and Pytest

In this article i will show you how you can test your FastAPI application, save the following file as main.py , this is a simple REST api…

FastAPI and Pytest
Photo by Scott Graham on Unsplash

In this article, I will show you how you can test your FastAPI application, save the following file as main.py , this is a simple REST API which adds two given numbers and returns the result

FastAPI code

from fastapi import FastAPI 
 
# Create an instance of the FastAPI class 
app = FastAPI() 
 
# Define a route to add two numbers 
@app.get("/add") 
async def add_numbers(num1: float, num2: float): 
    result = num1 + num2 
    return {"result": result}

Pytest Code

To run tests we need to import the pytest and fastapi.testclient library, in the same directory as main.py save the following files as test_main.py

import pytest 
from fastapi.testclient import TestClient 
from main import app  # Import your FastAPI app 
 
# Create a TestClient instance for testing 
client = TestClient(app) 
 
def test_add_numbers(): 
    # Test adding two numbers 
    response = client.get("/add?num1=5.5&num2=3.3") 
    assert response.status_code == 200 
    assert response.json() == {"result": 8.8} 
 
    # Test adding two different numbers 
    response = client.get("/add?num1=10&num2=20") 
    assert response.status_code == 200 
    assert response.json() == {"result": 30} 
 
    # Test adding zero to a number 
    response = client.get("/add?num1=7&num2=0") 
    assert response.status_code == 200 
    assert response.json() == {"result": 7} 
 
    # Test adding negative numbers 
    response = client.get("/add?num1=-2&num2=-5") 
    assert response.status_code == 200 
    assert response.json() == {"result": -7} 
 
def test_invalid_input(): 
    # Test invalid input (non-numeric values) 
    response = client.get("/add?num1=abc&num2=def") 
    assert response.status_code == 422  # Expect a validation error

Each function is a set of one or more tests, the response variable keeps the result of the /add endpoint and the corresponding variables. the assert commands return True in case that comparison is successful and False if the comparison fails, if the comparison fails means that the test is failed!.

Running the tests

To run the tests in the same directory as test_main.py enter pytest -vvv it should verbose output the tests, in this case both test suites passed successfully.

pytest -vvv                                                                                                                                                                              16:07:08 
======================================================================================================== test session starts ========================================================================================================= 
platform darwin -- Python 3.11.5, pytest-7.4.2, pluggy-1.3.0 -- /opt/homebrew/opt/python@3.11/bin/python3.11 
cachedir: .pytest_cache 
rootdir: /Users/kpatronas/Documents/docker/cicd_test 
plugins: asyncio-0.21.1, anyio-3.7.1 
asyncio: mode=Mode.STRICT 
collected 2 items                                                                                                                                                                                                                     
 
test_main.py::test_add_numbers PASSED                                                                                                                                                                                          [ 50%] 
test_main.py::test_invalid_input PASSED                                                                                                                                                                                        [100%] 
 
========================================================================================================= 2 passed in 0.23s ==========================================================================================================

Conclusion

In this article we saw how easy is to test our FastAPI! i hope you enjoyed this article as much as i enjoyed writing it!

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…

In Plain English

Thank you for being a part of our community! Before you go: