Django Expense Manager 4 - Using GitHub Actions for Testing
I will keep my promise today and write a quick post on using GitHub Actions to run our tests. Now you might think, what’s the point of that? Don’t I run the tests anyway before pushing? Yes, but one day, hopefully, people will contribute to the project, make changes, and when they push their changes, we can see if the existing tests all pass.
The GitHub commit for this quick post/implementation is here. So what did I do? Well, I created a .github folder in the root directory in which I created a workflows folder in which I added a full_tests.yaml file. Let’s have a look at it, part by part.
name: Run Pytest tests with PostgreSQL integration
on: [push]
The first two lines have the name of our workflow and the events that trigger it. For now, they will run whenever somebody pushes to the repo. Each workflow has at least one job, which are run in parallel (by default). Here, we have a “build” job (maybe not the best name).
jobs:
build:
runs-on: ubuntu-latest
steps:
The environment that the job runs in is specified by “runs-on”. For the “build” job, we use the ubuntu-latest image. What happens in a job? A series of steps. Let’s go one by one.
- uses: actions/checkout@v2
The first action in the step checks out the repository so that the workflow can access it.
- uses: actions/setup-python@v2
with:
python-version: '3.8'
architecture: 'x64'
We then install a specific version of Python. We could actually test on a few different version and we’ll get to that later on.
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
Then, we install the dependencies that we need by doing pip install from the requirements.txt file.
- name: Setup PostgreSQL
uses: Harmon758/postgresql-action@v1.0.0
with:
postgresql version: '13'
postgresql db: 'postgres'
postgresql user: 'postgres'
postgresql password: 'postgres' # add this to secret
We then install the PostgreSQL database. These tests will eventually be the “full tests” that are only run sometimes, and some other tests (with mocking) that run all the time.
- name: Wait / Sleep
uses: jakejarvis/wait-action@v0.1.0
with:
time: '10s'
I then wait 10 seconds just because on another project I ran into some issues where the database wasn’t ready…
- name: Collect Docker Logs
uses: jwalton/gh-docker-logs@v1.0.0
- name: Check running containers
run: docker ps -a
Let’s collect some logs and ensure everything is working okay
- name: run the pytest suite
run: |
pytest
Finally, we run the tests. That’s it! Quick post. In the next one we’ll discuss accessing/adding/modifying Category objects through API endpoints (and of course tests).