Python, Django and GitHub CI
Sep 30, 2019 // Linkedin // Github#python #django #ci-cd
GitHub Actions was introduced last year, and it’s an API for cause and effect on GitHub. You can orchestrate any workflow, based on any event, you can have your workflow run on push events to master and release branches, or only run on pull_request events that target the master branch, or run every day of the week at Friday 02:00. The workflows are code in a repository, as you will see in this project, so you can create, share, reuse, and fork.
I’m working in a Django project and when I started I found a problem: there was no CI/CD working or integration/unit test. In the past I used the GitLab CI/CD, but now the code was hosted on GitHub. So, my challenge was create tests to my Django project (it was implemented before I got the job) and create CI/CD pipeline for integrating it with GitHub CI/CD. For this tutorial, the application that I’m gonna show you, demonstrates CRUD operations using class based views in Django (you can find it here). It also includes UI for all CRUD views and it’s based on the semaphoreci.com tutorial.
- Local project setup
$ virtualenv -p python3 env- Download the project
$ git clone https://github.com/gabicavalcante/django-test-ci.git- Install pip requirements
$ pip install -r requirements.txt- Create a new psql database
postgres=# create database pydjango;Setup your database credentials and SITE_URL in settings.py file available inside core folder.
Once you have setup your database, open command prompt and run the migrate command to create the application default database and the superuser.
(env) $ python manage.py migrate
(env) $ python manage.py createsuperuserAfter all of the above command run successfully, let’s run:
(env) $ python manage.py runserverAnd visit the web browser with http://127.0.0.1:8000
Environment variables
The following environment variables can be set to override defaults:
SECRET_KEY: Django secret key.DB_ENGINE: Django database backend.DB_NAME: database name.DB_HOST: database hostname.DB_PORT: database port.DB_USER: database user.DB_PASSWORD: database password.
Test with PyTest
To tell pytest which Django settings that should be used for tests runs, we need to setup a pytest configuration file, called pytest.ini in our project root directory. The file contains:
[pytest]
DJANGO_SETTINGS_MODULE=core.test_settings
addopts = --nomigrations --cov=. --cov-report=htmlTo run the tests, we can invoke directly pytest command instead of manage.py test. The pytest-django is designed to run with the pytest command, but in case of you want to use manage.py test with pytest-django, you can create a simple test runner.