pglive

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2024 License: MIT Imports: 18 Imported by: 0

README

Go Reference Go Coverage CI Status Stability Go Report

pglive

PostgreSQL live database unit testing

Installation

go get github.com/n-r-w/pglive@latest

Introduction

  • This package is used with https://github.com/jackc/pgx, because it returns pgxpool.Pool for database operations.
  • Allow to use parallel unit tests. In this case, each test will have its own database.
  • Test database is created and deleted automatically after the test is finished.

There are two operating modes: using Docker and using an external database.

Using Docker

In this case, the default mapping for PostgreSQL on the host is to port 5433 to avoid conflicts with local PostgreSQL. For Docker Desktop on Linux or macOS, you should define DOCKER_SOCKET_ENDPOINT environment variable with:

  • Linux: unix:///home/<user>/.docker/desktop/docker.sock
  • macOS: unix:///Users/<USER>/.docker/run/docker.sock
Using an external database

This mode is activated in the following cases:

  • at least one parameter in Option are used: WithHost, WithPort, WithDatabase, WithUser, WithPassword
  • at least one environment variable is set: POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD.

Can be activated in GitLab CI with the following settings in .gitlab-ci.yml. Setting POSTGRES_DB in GitLab environment variables doesn't make sense because the default database won't be used. Example of .gitlab-ci.yml file with PostgreSQL service and environment variables for go tests:

go tests:
  services:
    - name: postgres:16.2 # PostgreSQL image name from <https://hub.docker.com/_/postgres>
      alias: test-postgres
      command: ["-c", "max_connections=200"] # Increasing the number of connections (if you have a lot of parallel tests)
  variables: # Environment variables
    POSTGRES_USER: postgres # Username
    POSTGRES_PASSWORD: secret # Password
    POSTGRES_HOST: test-postgres # Hostname
    POSTGRES_HOST_AUTH_METHOD: trust
    GOFLAGS: # Flags for go test if needed (-tags=xxxx)

Known limitations in external database mode:

  • The test database will not be deleted if the test execution is stopped on a breakpoint and not continued.
Parameter filling priority
  • If specific value parameters are set (Host, Port, Database, User, Password), the values from these parameters are used.
  • If environment variables are set and specific value parameters are not set, the values from the environment variables are used.
  • If neither environment variables nor specific value parameters are set, default values are used.

Default values:

PostrgreSQL image: postgres:latest
PostrgreSQL Host: 127.0.0.1
PostrgreSQL port: 5432
PostrgreSQL mapping port: 5433 (Docker mode)
User: postgres
Password: secret

Usage example

import (
  "testing"

  "github.com/jackc/pgx/v5/pgxpool"
  "github.com/n-r-w/pglive"
)

func Test_Example(t *testing.T) {
    var db *pgxpool.Pool

    // Create test database, run migrations and return a database connection
    db = pglive.GetPool(t, "./migrations")

    rows, err := db.Query(context.Background(), "SELECT name FROM test_table")
    if err != nil {
        t.Fatalf("error: %s", err)
    }
    for rows.Next() {
        var name string
        if err := rows.Scan(&name); err != nil {
            t.Fatalf("error: %s", err)
        }
        if name != "test" {
            t.Fatalf("expected 'test', got '%s'", name)
        }
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetPool

func GetPool(tb testing.TB, migrationsDir string, opt ...Option) *pgxpool.Pool

GetPool inits a test database, applies migrations, and returns a connection pool to the database.

Types

type Option

type Option func(*testDBOptions)

Option option for creating a test database.

func WithDatabase

func WithDatabase(database string) Option

WithDatabase sets the database name. The default is a randomly generated name.

func WithDockerImage

func WithDockerImage(dockerImage string) Option

WithDockerImage sets the name of the postgres image from https://hub.docker.com/_/postgres when running locally in docker. The default is latest.

func WithDockerPortMapping

func WithDockerPortMapping(dockerPortMapping string) Option

WithDockerPortMapping sets the port for mapping postgres to the host when running locally in docker. The default is 5433.

func WithDockerSocketEndpoint added in v1.1.0

func WithDockerSocketEndpoint(dockerSocketEndpoint string) Option

WithDockerSocketEndpoint sets the docker socket endpoint for connecting to the docker daemon.

func WithForceDockerMode

func WithForceDockerMode() Option

WithForceDockerMode forces the tests to run in docker.

func WithHost

func WithHost(host string) Option

WithHost sets the host for connecting to the database. The default is 127.0.0.1

func WithPassword

func WithPassword(password string) Option

WithPassword sets the password. The default is "secret".

func WithPort

func WithPort(port string) Option

WithPort sets the port for connecting to the database. The default is 5432.

func WithRetryTimeout

func WithRetryTimeout(retryTimeout time.Duration) Option

WithRetryTimeout sets the timeout for connecting to the database. The default is 30 seconds.

func WithUser

func WithUser(user string) Option

WithUser sets the user name. The default is "postgres".

type TestDB

type TestDB struct {
	// contains filtered or unexported fields
}

TestDB creates a connection to a temporary test cluster databasepg, allows you to deploy migrations on it and run tests.

func NewTDB

func NewTDB(tb testing.TB, opt ...Option) (*TestDB, error)

NewTDB creates a new test database.

func (*TestDB) Close

func (d *TestDB) Close() (err error)

Close closes the test database.

func (*TestDB) DSN

func (d *TestDB) DSN() string

DSN returns the data source name for connecting to the database.

func (*TestDB) MigrationsUp

func (d *TestDB) MigrationsUp(migrationsDir, schema string) error

MigrationsUp applies migrations to the database.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL