Unit tests for docker

Setup

  • Install Container Structure Test
    1
    2
    3
    curl -LO https://storage.googleapis.com/container-structure-test/latest/container-structure-test-linux-amd64 && \
    chmod +x container-structure-test-linux-amd64 && \
    sudo mv container-structure-test-linux-amd64 /usr/local/bin/container-structure-test
  • Select test options:
    • Command Tests: execute a command in your image and check the output
    • File Existence Tests: check if a file is, or isn’t, present in the image
    • File Content Tests: check the content of a file
    • Metadata Test: check if a container metadata is correct

Write unit tests

Prerequisites

  • a Dockerfile
  • a .yaml or .json file that contains your test cases

Example

  • Pre-existing code
    • Dockerfile
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      FROM ubuntu:bionic

      RUN apt-get update \
      && apt-get install -y curl gnupg \
      && curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg \
      && mv bazel.gpg /etc/apt/trusted.gpg.d/ \
      && echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" > /etc/apt/sources.list.d/bazel.list \
      && apt-get update \
      && apt-get install -y bazel \
      && rm -rf /var/lib/apt/lists/*

      RUN groupadd -g 1000 user \
      && useradd -d /home/user -m -u 1000 -g 1000 user \
      && chown -R user:user /home/user \
      && mkdir -p /bazel/cache \
      && chown -R user:user /bazel

      RUN echo "build --repository_cache=/bazel/cache">/home/user/.bazelrc
    • Build dockerfile
      1
      docker build -t docker-unit-test .
  • Unit Test code
    • unit-test.yaml
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      schemaVersion: '2.0.0'
      fileExistenceTests:
      - name: 'Check bazel cache folder exists and is owned by the non-root user'
      path: '/bazel/cache'
      shouldExist: true
      uid: 1000
      gid: 1000
      isExecutableBy: 'group'
      fileContentTests:
      - name: 'Validate cache folder config'
      path: '/home/user/.bazelrc'
      expectedContents: ['.*build --repository_cache=/bazel/cache.*']
    • Run the tests
      1
      container-structure-test test --image docker-unit-test --config unit-test.yaml

Automate testing

  • Automation with Ansible
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    - name: unit test Docker Image
    shell: |
    container-structure-test test --image {{ docker_image }} --config {{ test_file }}
    if $?
    then
    echo "Test Failed"
    exit 1
    else
    echo "Test Succeeded"
    exit 0
    fi