Integration tests with MySQL

Launching a MySQL service container

In this example, we will see a NodeJS project that is using MySQL for data storage. For the integration test phase we will launch an instance of MySQL in order to run a simple integration test.

MySQL integration tests with Codefresh

MySQL integration tests with Codefresh

The integration tests look for a MySQL connection at test_mysql_db:3306.

Example NodeJS project

You can see the example project at https://github.com/codefreshdemo/cf-example-unit-tests-with-composition. The repository contains the NodeJS source code and the simple integration test.

You can play with it locally by using Docker compose to launch both the application and the MySQL Database.

Create a pipeline with MySQL integration tests

Here is the whole pipeline:

codefresh.yml

version: "1.0"
stages:
  - prepare
  - build
  - test
steps:
  main_clone:
    type: "git-clone"
    description: "Cloning main repository..."
    repo: "codefreshdemo/cf-example-unit-tests-with-composition"
    revision: "master"
    git: github
    stage: prepare
  build_test_image:
    title: "Building Test Docker Image"
    type: "build"
    image_name: "mysql-tests"
    tag: "master"
    dockerfile: "Dockerfile"
    stage: build
  run_integration_tests:
    title: "Running integration tests"
    stage: test
    image: '${{build_test_image}}'
    environment: &test_mysql_vars
      - MYSQL_ROOT_PASSWORD=admin
      - MYSQL_USER=my_user
      - MYSQL_PASSWORD=admin
      - MYSQL_DATABASE=nodejs
      - MYSQL_HOST=test_mysql_db
    commands:
      # MySQL is certainly up at this point
         - cd /usr/src/app
         - npm test
    services:
      composition:
        test_mysql_db:
          image: mysql:5.7
          ports:
            - 3306
          environment: *test_mysql_vars # Same MYSQL_HOST, MYSQL_USER etc.
      readiness:
        timeoutSeconds: 30
        periodSeconds: 15
        image: '${{build_test_image}}'
        commands:
          - "nslookup test_mysql_db"   
          - "nc -z test_mysql_db 3306"

This pipeline does the following:

  1. Clones the source code through a Git clone step.
  2. Builds a Docker image with the integration test through a build step.
  3. Runs the tests while launching a service container for an active MySQL instance passing the required environment variables (that match what the test is expecting).

Notice that both the DB as well as the tests share a set of variables (MYSQL_PASSWORD, MYSQL_USER etc.) and thus we use YAML anchors to avoid duplication.

Notice that we also use the readiness property in the testing phase so that we can verify MySQL is ready and listening, before running the tests.

CI pipeline examples
Integration test example
Integration tests with Postgres
Integration tests with Redis
Integration tests with Mongo