Categorygithub.com/Hemiun/testcontainer
modulepackage
0.0.0-20240904125030-503b973c3c85
Repository: https://github.com/hemiun/testcontainer.git
Documentation: pkg.go.dev

# README

Test containers

Introduction

Package that makes it simple to create and clean up container-based dependencies for automated integration/smoke tests. For implementation used testcontainers-go library.
Implemented containers for postgres and apache kafka (KRaft mode)

Features

Postgresql

  • Starting and stopping a container
  • Database preparation (database creation, users creation, schema creation)
  • applying all up migrations

Kafka

  • Starting and stopping a container (kafka broker). A new network is created for each instance of the KafkaContainer. This avoids concurrent tests.
  • Custom strategy for kafka broker readiness check (through metadata acquisition) implemented

Installation

 go get github.com/Hemiun/testcontainer

Getting Started

  1. Copy "scripts" folder to your project Or create your own struct. In this case you must set path variables
testcontainer.CreateDatabasePath = "..."
testcontainer.CreateSchemaPath = "..."
testcontainer.MigrationPath = "..."
  1. By default, folder script/migrations is empty and migrations are not applied (param ApplyMigrations == false). You can put your migrations to this folder and change param ApplyMigrations
testcontainer.ApplyMigrations = true
  1. By default, we use testcontainers-go. If your prefer another tool your can implement your own MigrationApplyFn function For example, for goose should be something like this:
testcontainer.MigrationApplyFn  = func(dsn string) error {
        db, err = sql.Open("postgres", dsn)
        if err != nil {
           panic(err)
        }
        defer db.Close()
        goose.SetBaseFS(embedMigrations)
        if err := goose.SetDialect("postgres"); err != nil {
            panic(err)
        }
        if err := goose.Up(db, path.Clean(buildPath(migrationPath))); err != nil {
            return err
        }
		return nil
   }
  1. Using
    db, err := testcontainer.NewDatabaseContainer(ctx, postgresConfig, nil)
	if err != nil {
		fmt.Printf("can't init db container: %v", err)
	}
	err = db.PrepareDB(ctx)
	if err != nil {
		panic("can't prepare db")
	}
	defer db.Close(ctx)
	dsn := db.ConnectionString(ctx)

	//  your database is ready/ Use dsn for connect
	conn, err := pgx.Connect(ctx, dsn)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		os.Exit(1)
	}
	defer conn.Close(context.Background())

	var num int64
	err = conn.QueryRow(context.Background(), "select 10").Scan(&num)
	if err != nil {
		fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println(num)

# Functions

NewDatabaseContainer returns new DatabaseContainer ctx and cfg are mandatory params Optionally you can pass logger.
NewKafkaContainer - returns new KafkaContainer.
NewMetadataWaitStrategy returns new MetadataWaitStrategy.

# Variables

ApplyMigrations - if false migrations doesn't apply.
BrokerExternalPort - broker port for external communications.
BrokerInternalPort - broker port for internal communications.
CreateDatabasePath - path to database creation script template (see ./script/init/01.database.sql for example).
CreateSchemaPath - path to database schema creation script template (see ./script/init/02.schema.sql for example).
DefaultDB - default database name (used for first connection).
DefaultDBPass - pass for DefaultDBUser.
DefaultDBUser - database user.
No description provided by the author
No description provided by the author
No description provided by the author
ExposePostgresPort - database port for expose from container.
KafkaBrokerImage - docker image name for apache kafka broker.
No description provided by the author
MigrationPath - path to migration scripts.
PostgresImage - docker image name for postgres.

# Structs

DatabaseContainer - struct for db container.
DatabaseContainerConfig - configuration for database container (postgresql) Usually we use the couple of users.
KafkaContainer - test container for kafka broker.
KafkaContainerConfig - config struct for container with kafka broker.
MetadataWaitStrategy - strategy for waiting kafka readiness.

# Interfaces

Logger - interface for logging inside module testcontainers .

# Type aliases

No description provided by the author