Testing your RESTful API
Testing is a critical part of API development. In FastAPI, you can use various testing frameworks such as pytest
to write tests for your API endpoints.
In this recipe, we are going to write unit tests for each of the endpoints we created earlier.
Getting ready…
If not done yet, ensure you have pytest
installed in your environment by running:
$ pip install pytest
It’s a good practice in testing to use a dedicated database to avoid interaction with the production one. To accomplish this, we will create a test fixture that generates the database before each test.
We will define this in a conftest.py
module so that the fixture is applied to all tests under the project’s root folder. Let’s create the module in the project root folder and start by defining a list of test tasks and the name of the CSV file used for the tests:
TEST_DATABASE_FILE = "test_tasks.csv" TEST_TASKS_CSV = [ ...