Based on the awesome Test-Driven Development with FastAPI and Docker
course from testdriven.io, with a few changes: Management of python dependencies is done withpyenv
and poetry
(v2)
instead of pip
; Instead of the general Package registry with a
PAT,
we used the GitHub Container registry ghcr.io
the more secure GITHUB_TOKEN
; and we used docker compose
(the docker-compose-plugin) instead of docker-compose
(the older standalone version).
In the repo root directory (where the docker-compose.yml
is) build the containers with:
$ docker compose up -d --build
View container logs
$ docker compose logs web
Bring down and remove volumes:
$ docker compose down -v
$ docker compose exec web aerich init -t app.db.TORTOISE_ORM
Init:
$ docker compose exec web aerich init-db
Upgrade:
$ docker compose exec web aerich upgrade
Access the database via psql
with:
$ docker compose exec web-db psql -U postgres
Then connect to the database with:
postgres=# \c web_dev
postgres=# \dt
postgres=# select * from textsummary;
postgres=# \q
With the containers up and running, run the tests:
$ docker compose exec web python -m pytest
Coverage report:
$ docker compose exec web python -m pytest --cov="."
$ docker compose exec web black .
$ docker compose exec web flake8 .
$ docker compose exec web isort .
With checks:
$ docker-compose exec web black . --check
$ docker-compose exec web isort . --check-only
$ docker compose logs web
...
fastapi-tdd-docker-web-1 | tortoise.exceptions.OperationalError: relation "textsummary" does not exist
When building a fresh docker container with db and app, make sure to execute migration script during the container building.