FastAPI – Testing API with pytest #10

Posted by


In this tutorial, we will be learning how to test an API built with FastAPI using pytest. FastAPI is a modern web framework for building APIs with Python that is fast, easy to use, and efficient. Pytest is a testing framework that makes it easy to write simple and scalable tests in Python.

Before we begin, make sure you have FastAPI and pytest installed. You can install them using pip:

pip install fastapi pytest

Create a new Python file called main.py and add the following code:

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
async def hello():
    return {"message": "Hello, World!"}

This code creates a simple FastAPI application with one endpoint /hello that returns a JSON response with a message "Hello, World!".

Now, create a new Python file called test_main.py and add the following code:

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_hello():
    response = client.get("/hello")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, World!"}

This code imports the TestClient class from fastapi.testclient and our FastAPI application app from main.py. We then create a test function test_hello() that sends a GET request to the /hello endpoint using the client and asserts that the response status code is 200 and the response JSON matches the expected message.

To run the tests, open a terminal and run the following command:

pytest test_main.py

You should see the output that indicates that the test passed successfully.

This is a basic example of testing a FastAPI API using pytest. You can write more test functions to cover different endpoints and scenarios. FastAPI provides several features to make testing APIs easy and efficient, such as dependency injection, automatic validation, and automatic documentation generation.

In conclusion, testing APIs is an essential part of building reliable and robust applications. By using FastAPI and pytest, you can write tests that are easy to understand, maintain, and execute, ensuring the quality and stability of your API.

0 0 votes
Article Rating

Leave a Reply

27 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@artemshumeiko
12 days ago

💡 Попробуй онлайн-тренажёр для подготовки к техническому собеседованию: https://clck.ru/3B5gwP 💡

Забирай роадмап изучения самого востребованного фреймворка на Python – FastAPI здесь: https://t.me/ArtemShumeikoBot

@user-bf6hz5sf9s
12 days ago

Товарищи сталкивался ли кто нибудь с проблемой написания асинхронной фикстуры со scope='function' и асинхронного теста?
Я уже 3й день не могу понять как заставить их работать вместе. Постоянно лезет ошибка event_loop и прочие

@olter1000
12 days ago

pg admin есть на маке тоже)

@komonrecords
12 days ago

Хочу послушать про pytest

@user-xu5pp7lk5g
12 days ago

Почему-то подключение происходит к основной БД, при чем таблицы не создаются автоматически, подскажите пожалуйста в чем может быть причина?

@ВладиславВасилец-й7е
12 days ago

Для тех кто немного проебался как и я, metadata можно брать из Base…
@pytest.fixture(scope='session', autouse=True)
async def prepare_database():
async with engine_test.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
yield
async with engine_test.begin() as connection:
await connection.run_sync(Base.metadata.drop_all)

@ИльяКондрюков-ф1г
12 days ago

Запиши видос по pytest!

@gayratsaidakhmedov5451
12 days ago

спасибо

@twelfth4927
12 days ago

Всадил несколько часов, пытаясь разобраться почему у меня база не создается, а оказалось что файл то у меня назван conftests.py, а не conftest.py. Капец, уже какой раз я там 's' вставляю на автомате, целый пет проект за плечами, где я сижу и ебу себе мозги почему не работает сетап бд, куков, юзеров и т.д. Будьте внимательные короче, ахахха

@a_korvus
12 days ago

Отличное видео, спасибо! Разбор pytest был бы очень интересен)

@ЛютыйМайнер
12 days ago

не знаю почему, но при тесте с добавлением роли ошибка sqlalchemy.exc.InvalidRequestError: Table 'user' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

@vyacheslav6564
12 days ago

Нужно ли тестировать время создания записи в таблицы, которое задаётся на стороне БД? Такое время не зафризить по понятным причинам.

@python_XVIII
12 days ago

почему он не принимает порт кроме 5432

@busipac1467
12 days ago

async def get_specific_operations – return {
'status': 'success',
'data': result.mappings().all(),
'details': None
}
Теперь только так

@СтасниславНиколаевич
12 days ago

подобное обучение не для новичков уж точно, что то остается за кадром и не всегда понятно, что и от куда. В целом курс хороший.

@berkyt1540
12 days ago

Если у вас после тестов данные пишутся в основную БД, а не в тестовую, попробуйте в файле conftest удалить префиксы src. в импортах!

По крайней мере мне помогло.

@riwi_5200
12 days ago

Здравствуйте, возникла ошибка tests/test_auth.py::test_register – ValueError: set_wakeup_fd only works in main thread. Причем в бд появляются user и role. Не понимаю в чем дело

@olegkorol3127
12 days ago

Если у кого-то падает по AttributeError: 'Package' object has no attribute 'obj' откатите pytest до предыдущей версии – pip install pytest==7.4.4.
На данный момент pytest-asyncio не поддерживает pytest 8.0.0.

@user-yn3fv4hh7k
12 days ago

Спасибо за видео! А как быть в больших проектах, где нужно тестировать API – нужно ли использовать mocking для базы данных, так как от ее состояния зависит исход теста, а это несколько противоречит идее, что тесты долдны быть независимыми. То есть, в Вашем примере последовательность выполнения важна. Или нужно несколько fixtures с разными scopes, чтобы для отдельных тестов базу для каждого удалять и создавать? Спасибо!

@ДианаАимбетова-и6м
12 days ago

Если у кого сыпятся варнинги то добавьте декоратор в асинк тесты @pytest.mark.asyncio(scope="module")

27
0
Would love your thoughts, please comment.x
()
x