Testing Multiple Python Version with Docker on Travis CI

Post by Saul Shanabrook

Travis CI makes it super easy to use Docker [Compose] in your tests.

In a recent Django library I was working on, however, I wanted to test on multiple Python versions, but use Docker. Normally, to test on Python versions in Travis you can do

python:  
  - 2.7
  - 3.5

in your .travis.yml files. This won't work, however, if you are using Python inside Docker. Instead you can add the version as an environmental variable, and generate a new Dockerfile based on that variable, like this:

sudo: required

services:  
  - docker

env:  
  DOCKER_COMPOSE_VERSION: 1.5.0

before_install:  
  - sudo rm /usr/local/bin/docker-compose
  - curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose
  - chmod +x docker-compose
  - sudo mv docker-compose /usr/local/bin

install:  
  - sed -e 's/${PYTHON_VERSION}/'${PYTHON_VERSION}/g -e 's/${DJANGO_VERSION}/'${DJANGO_VERSION}/g Dockerfile.tmpl  > Dockerfile
  - docker-compose build

script: docker-compose run test

env:  
  global:
    - DOCKER_COMPOSE_VERSION=1.5.0
  matrix:
    - DJANGO_VERSION="1.8.*" PYTHON_VERSION=3.5
    - DJANGO_VERSION="1.8.*" PYTHON_VERSION=3.4
    - DJANGO_VERSION="1.8.*" PYTHON_VERSION=3.3
    - DJANGO_VERSION="1.8.*" PYTHON_VERSION=3.2
    - DJANGO_VERSION="1.8.*" PYTHON_VERSION=2.7
    - DJANGO_VERSION="1.7.*" PYTHON_VERSION=2.7

And then just make a Dockerfile template file:

# Dockerfile.tmpl
FROM python:${PYTHON_VERSION}

COPY test_project/requirements.txt /app/requirements.txt  
WORKDIR /app/  
RUN pip install -r requirements.txt

RUN pip install Django==${DJANGO_VERSION}

COPY . /externalliveserver  
RUN pip install -e /externalliveserver

COPY test_project /app/  

Thanks Travis!