Logo dévoreur 2 code

Tests and Code Quality - Automating All This Is Right Up Our Alley

Written by Fabien SchlegelFabien Schlegel
published 9/22/20195 min

And there you go, it’s already the last lap, we’re close to the finish line.

Our project is checked by a linter, packed with awesome tests, and we keep an eye on the quality of our code.

Now, the problem is that we’ll never have the time / the desire / the courage (cross out whichever doesn’t apply) to run the whole shebang on every commit.

So here comes the big decision: we don’t give up, we’re going to automate CI/CD style, so the server does the work for us (that lazy penguin).

CI/CD, what’s that

The sentence from the Red Hat folks is too beautiful not to quote:

CI/CD is a method to frequently deliver apps to customers by introducing automation into the stages of app development.

Damn, it brings a tear to my eye, it reads like Victor Hugo.

More simply, we can split the idea into two parts:

  • Continuous Integration: this is what lets us add our new developments to our project every day. We automate all the checks on our changes and the merge with the rest of the project.
  • Continuous Deployment: this lets us ship our application to the acceptance and production environments.

Setting it up

There are quite a few tools for setting up this kind of solution.

  • Jenkins
  • TravisCI
  • CircleCi
  • Codeship
  • Gitlab CI

Since most of my repositories are on Gitlab, I’ll use it as an example with a Django project deployed on Heroku.

Gitlab CI, on gitlab.com, works with runners shared between all users. Depending on the time of day, you’ll have to wait for a runner (a docker container) to become free to run the jobs (basically the tasks) of the pipeline (the list of tasks).

On every commit pushed to the repository or every merge request, GitlabCI runs the pipeline.

GitlabCI uses a YAML file that must be named .gitlabci.yml and placed at the root of the project. Nothing complicated. We’ll split our chain of tasks into different stages.

A stage we’ll call test, for tests and code quality, and a deploy stage, used to deploy our project.

stages:
  - test
  - deploy

test:
  stage: test
  image: joyzoursky/python-chromedriver:3.7-selenium
  services:
    - postgres:11.3-alpine
    - docker:dind
  variables:
    DBUS_SESSION_BUS_ADDRESS: "/dev/null"
    SECRET_KEY: "fake_key"
    DEBUG: "False"
    ALLOWED_HOSTS: ".localhost"
    EMAIL_HOST: ""
    EMAIL_PORT: ""
    EMAIL_HOST_USER: ""
    EMAIL_HOST_PASSWORD: ""
    EMAIL_USE_TLS: ""
    DEFAULT_FROM_EMAIL: ""
    DATABASE_URL: "postgres://db_user:fakepassword@postgres:5432/sample"
    POSTGRES_DB: sample
    POSTGRES_USER: db_user
    POSTGRES_PASSWORD: fakepassword

  cache:
    paths:
      - ~/.cache/pip/

  before_script:
    - apt-get update -qy
    - apt-get install -y libpq-dev python-dev python-pip
    - python -V
    - pip install -r requirements/ci.txt
    - mkdir static
    - python manage.py collectstatic
    - gunicorn -D core.wsgi

  script:
    - coverage run --source="." manage.py test -v 3
    - coverage report

codequality:
  stage: test
  image: docker:stable
  variables:
    DOCKER_DRIVER: overlay2
  allow_failure: true
  services:
    - docker:stable-dind
  script:
    - export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
    - docker run
      --env SOURCE_CODE="$PWD"
      --volume "$PWD":/code
      --volume /var/run/docker.sock:/var/run/docker.sock
      "registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
  artifacts:
    reports:
      codequality: gl-code-quality-report.json

staging_deploy:
  stage: deploy
  script:
    - apt-get update -qy
    - apt-get install -y ruby-dev
    - gem install dpl
    - dpl --provider=heroku --app=super-staging --api-key=$HEROKU_SECRET_KEY
  only:
    - develop

production_deploy:
  stage: deploy
  script:
    - apt-get update -qy
    - apt-get install -y ruby-dev
    - gem install dpl
    - dpl --provider=heroku --app=super --api-key=$HEROKU_SECRET_KEY
  only:
    - master

Let’s tackle the heavy part. To run our tests with Django, we’ll use Docker. Some tests indeed need to start a real Django web server and use Chrome and Selenium, see part 1 of the series.

That’s the whole point of Docker Hub: someone has built exactly the container we need. We put the name of the main container in image.

In services, we add the secondary containers we need:

  • postgres:11.3-alpine is for the database part
  • docker:dind isn’t a chicken dinner, it’s docker-in-docker, which lets you start containers inside a container, since the Gitlab runner is one.

variables lets us include the environment variables the project needs. If some variables are secret, like an AWS or Google Maps API key, we add them in the gitlabci settings and retrieve them with $OUR_VARIABLE.

cache lets us store python packages or npm dependencies in a cache.

before_script is the step before. Here we update our container, install our project and start gunicorn, a Python WSGI server.

script is the heart of our step: we run coverage, which executes our tests and generates a report. A GitlabCI feature parses the result with a regular expression to give us the coverage percentage in the merge request.

coverage

If a test fails, the job errors out and fails the whole pipeline.

On to the other step of our test stage: code quality. I didn’t invent anything here, it’s provided by GitlabCI.

allowfailure set to true means that, if the job fails, it doesn’t bring down the whole pipeline.

The code quality result is written to a json file, and we find the result in our merge request.

merge request screenshot

The last step of our automation: deployment.

The two blocks look alike, except for:

  • the name of our heroku app, one for staging and one for production.
  • the branch that triggers the job, through the only setting.

Now, if the pipeline fails on any commit, we get a nice email. Merge requests will only go through automatically if the pipeline passes.

Thanks to this whole process, we’ll save ourselves a ton of work over the life of our project.

It’s already the end

There you go, we’ve reached the end of our series.

I hope I’ve given you enough to dive into several fascinating topics that I’ve only scratched the surface of.

Feel free to leave a comment or a private message on my LinkedIn or Twitter, it will help me improve for what comes next!


Share the post

Table of contents