Fastapi โก with postgresql and unit tests ๐๏ธ
In this project we will use fastapi to create an api and connect it to postgresql with sqlmodel to finish performing unit tests with pytest. This is an example project that you can download, modify and use to perform your own tests.
Now to execute this project I have used poetry as a virtual environment, which you can download and install according to its documentation, which you can verify in the following link:
๐ป Now with poetry installed we will execute the following commands, you must open a console that points to the root folder of the project ๐.
# This command creates and activates the virtual environment:
poetry shell
# This command installs all dependencies:
poetry install
๐ป Now that we have all the dependencies installed and we can run our project ๐, for which we can use one of the following commands:
Fastapi command:
fastapi dev main.py
Uvicorn command:
uvicorn main:app --reload
๐ก Now that we have our project running, we only need to configure the connection to the database, which you must do in 2 files ๐, one is the api project and the second is the test file.
๐ก This project automatically creates the users table, so there is no need to create it manually ๐ .
And we are ready to test our api, feel free to test each endpoint of the api ๐จ๐ปโ๐ง.
๐ก Finally we need to do our unit testing test, for which we will use pytest ๐ง. You just need to run the command in the console:
pytest
โ Excellent, you are now running your unit tests, but as you can see the prints ๐ข that we have in the test are not shown, if you want to see these prints ๐ข in the console you must execute the following command:
pytest -s
๐ข As an extra bonus I have left the SQLite database connection commented in case you want to test with this database.
๐จ๐ป I hope this small project is very useful for you to practice with fastapi โก, postgresql and unit tests. If it has been useful to you, don't forget to follow me and leave the repo a star ๐.