Follow

Follow

DockerTest + postgreSQL Testing

Maheshwar Ligade's photo
Maheshwar Ligade
·May 20, 2023·

3 min read

Play this article

Table of contents

  • Prerequisites
  • Installation
  • Usage
  • Conclusion

When developing applications that rely on a database or other external dependencies, it's often useful to have automated tests that can verify that everything is working as expected. However, setting up and tearing down these dependencies can be a hassle, especially when running tests locally. This is where Dockertest comes in. Dockertest is a Go library that provides a simple way to spin up Docker containers for use in integration testing.

In this article, we'll go through an example of using Dockertest in a Go application to test a PostgreSQL database.

Prerequisites

Before we get started, make sure that you have the following software installed on your system:

  • Go (version 1.13 or higher)

  • Docker

  • Docker Compose

Installation

To install Dockertest, run the following command:

go get github.com/ory/dockertest/v3

Usage

Step 1: Create a test file

First, let's create a test file that will use Dockertest to spin up a PostgreSQL database for our integration tests. Create a new file called database_test.go and add the following code:

package main

import (
    "context"
    "database/sql"
    "fmt"
    "log"
    "testing"
    "time"

    _ "github.com/lib/pq"
    "github.com/ory/dockertest/v3"
    "github.com/stretchr/testify/assert"
)

var db *sql.DB

func TestMain(m *testing.M) {
    pool, err := dockertest.NewPool("")
    if err != nil {
        log.Fatalf("Could not connect to Docker: %s", err)
    }

    resource, err := pool.Run("postgres", "latest", []string{
        "POSTGRES_PASSWORD=secret",
        "POSTGRES_USER=user",
        "POSTGRES_DB=testdb",
    })
    if err != nil {
        log.Fatalf("Could not start resource: %s", err)
    }

    hostPort := resource.GetHostPort("5432/tcp")

    if err := pool.Retry(func() error {
        var err error
        db, err = sql.Open("postgres", fmt.Sprintf("host=localhost port=%s user=user password=secret dbname=testdb sslmode=disable", hostPort))
        if err != nil {
            return err
        }
        return db.Ping()
    }); err != nil {
        log.Fatalf("Could not connect to Docker: %s", err)
    }

    code := m.Run()

    if err := pool.Purge(resource); err != nil {
        log.Fatalf("Could not purge resource: %s", err)
    }

    os.Exit(code)
}

func TestDatabase(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    rows, err := db.QueryContext(ctx, "SELECT 1")
    assert.NoError(t, err)
    assert.True(t, rows.Next())
}

This code sets up a PostgreSQL container using Dockertest and ensures that the container is ready for use before running the tests. The tests themselves simply check that we can execute a simple SQL query against the database.

Step 2: Run the tests

To run the tests, execute the following command:

go test -v ./...

This will output information about the tests as they run, and should ultimately show that the tests passed.

Step 3: Clean up

After the tests have run, the Docker container will still be running. To clean up the container, you can run the following command:

docker stop $(docker ps -aq)

This will stop all running containers on your system.

Conclusion

In conclusion, dockertest is a powerful Go library that makes it easy to write unit and integration tests for database-driven applications. By using this library, you can spin up real Docker containers for your databases in your test environment, and run tests against them, giving you a more accurate and reliable test suite.

We have covered the basics of dockertest in this article, including how to set up and use the library, and how to write test cases for PostgreSQL and MySQL databases. We have also seen how dockertest can be used with other Go testing frameworks like testing and Ginkgo.

Overall, dockertest is a great tool for any Go developer who needs to write database-driven applications and wants to have a robust testing framework. By using dockertest, you can be confident that your tests are running against real databases, and that your application will work correctly in production.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this