testutil

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: MIT Imports: 5 Imported by: 0

README

go-toolkit-testutil

Testing utilities for Go: load environment variables from .env.test and build DB/ES/Redis/Kafka/RabbitMQ connection configs for integration tests.

Features

  • Env loading: walk up from the working directory to find the project root (via go.mod), then load .env.test with godotenv. CI-friendly: externally set environment variables still apply when .env.test is absent.
  • Elasticsearch config: read TEST_ES_* env vars into an es.Config.
  • MySQL config: build a MySQL DSN from TEST_MYSQL_DSN for a given database name; generate a Gorm *gorm.DB together with a *simpledb.SimpleDB.
  • Redis config: read TEST_REDIS_* env vars into a redis.Config.
  • Kafka config: read TEST_KAFKA_* env vars into a kafka.Config (brokers list + optional SASL).
  • RabbitMQ config: read TEST_RABBITMQ_* env vars into a rabbitmq.Config.

Installation

go get github.com/auho/go-toolkit-testutil

Environment variables

Create a .env.test at the project root (do not commit it to git). Each tool reads its own variables; missing variables are reported with a clear error.

Elasticsearch
TEST_ES_ADDRESS=http://localhost:9200
TEST_ES_USERNAME=elastic
TEST_ES_PASSWORD=secret
MySQL
TEST_MYSQL_DSN=root:pass@tcp(localhost:3306)/

The DSN may omit the trailing /; LoadDSN inserts it after the address part for MySQL driver compatibility and replaces the DBName with the value passed to LoadDSN / GenGorm. The following formats are all supported:

root:pass@tcp(host:port)/db?charset=utf8mb4&parseTime=True&loc=Local
root:pass@tcp(host:port)/?charset=utf8mb4&parseTime=True&loc=Local
root:pass@tcp(host:port)/db
root:pass@tcp(host:port)
Redis
TEST_REDIS_ADDR=localhost:6379
TEST_REDIS_PASSWORD=secret
TEST_REDIS_DB=0
Kafka
TEST_KAFKA_BROKERS=localhost:9092,localhost:9093
TEST_KAFKA_USERNAME=elastic
TEST_KAFKA_PASSWORD=secret

TEST_KAFKA_BROKERS is a comma-separated list. Whitespace around each broker is trimmed. USERNAME and PASSWORD are optional; when set, they enable SASL authentication.

RabbitMQ
TEST_RABBITMQ_ADDR=localhost:5672
TEST_RABBITMQ_USERNAME=user
TEST_RABBITMQ_PASSWORD=secret
TEST_RABBITMQ_VHOST=vhost
TEST_RABBITMQ_TLS=false

TEST_RABBITMQ_ADDR is required. USERNAME, PASSWORD and VHOST are optional. TLS defaults to false; set it to true to use amqps://. Use cfg.URL() to get a connection URL, or cfg.URLWithVhost(name) to specify a vhost at runtime.

Usage

Load env vars
package main_test

import (
    "testing"

    "github.com/auho/go-toolkit-testutil"
)

func TestExample(t *testing.T) {
    if err := testutil.LoadEnv(); err != nil {
        t.Fatal(err)
    }
    // env vars from .env.test are now visible to os.Getenv
}

LoadEnv is a no-op when .env.test does not exist, so it is safe to call in every test. LoadEnvFromFile accepts a custom file path relative to the project root.

Elasticsearch
cfg, err := es.LoadConfig()
if err != nil {
    panic(err)
}
// use cfg.Address, cfg.Username, cfg.Password to build an ES client
MySQL (Gorm)
gormDB, simpleDB, err := mysql.GenGorm("test_db")
if err != nil {
    panic(err)
}
// gormDB: *gorm.DB configured with a connection pool
// simpleDB: *simpledb.SimpleDB wrapping the same gorm.DB

GenGorm tunes the connection pool (MaxOpenConns=20, MaxIdleConns=20, ConnMaxLifetime=5m) and logs only errors to stdout.

Redis
cfg, err := redis.LoadConfig()
if err != nil {
    panic(err)
}
// use cfg.Addr, cfg.Password, cfg.DB to build a redis client
Kafka
cfg, err := kafka.LoadConfig()
if err != nil {
    panic(err)
}
// use cfg.Brokers, cfg.Username, cfg.Password to build a kafka client
RabbitMQ
cfg, err := rabbitmq.LoadConfig()
if err != nil {
    panic(err)
}
// use cfg.URL() to dial an AMQP connection, or cfg.URLWithVhost(name)
// to connect to a specific vhost at runtime

License

See LICENSE.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetEnv

func GetEnv(key string) (string, error)

GetEnv returns the value of the environment variable named by the key. It returns an error if the variable is not set or empty.

Example
// GetEnv returns the value of an environment variable, or an error
// if the variable is not set or empty.
addr, err := GetEnv("TEST_ES_ADDRESS")
if err != nil {
	// handle missing env var (e.g. skip the test)
	return
}
_ = addr
// Use addr to connect to the service under test.

func LoadEnv

func LoadEnv() error

LoadEnv loads environment variables from .env.test at the project root. It is a no-op if .env.test does not exist; externally set environment variables still apply (CI-friendly). It returns an error only when the file exists but fails to parse, or when the project root cannot be found.

Example
// LoadEnv loads environment variables from .env.test at the project
// root. It is a no-op if the file does not exist, so tests can rely
// on externally set env vars in CI.
if err := LoadEnv(); err != nil {
	// handle error (e.g. skip the test)
	return
}
// Env vars from .env.test are now available via os.Getenv or GetEnv.

func LoadEnvFromFile

func LoadEnvFromFile(filePath string) error

LoadEnvFromFile loads environment variables from the file at the given path, interpreted as relative to the project root. It is the underlying implementation of LoadEnv. It is a no-op if the file does not exist; externally set environment variables still apply (CI-friendly). It returns an error only when the file exists but fails to parse, or when the project root cannot be found.

func MustGetEnv

func MustGetEnv(key string) string

MustGetEnv is like GetEnv but panics if the variable is not set or empty. This is convenient for package-level or TestMain setup where the env var is guaranteed to exist and a missing value indicates a configuration bug.

func ProjectRoot

func ProjectRoot() string

ProjectRoot walks up from the current working directory to find the directory containing go.mod. It returns the absolute path, or "" if not found.

Example
// ProjectRoot walks up from the working directory to find the directory
// containing go.mod. It is useful for locating test fixtures relative
// to the project root.
root := ProjectRoot()
_ = root
// Use root to build paths to test fixtures, e.g.:
//   fixturePath := filepath.Join(root, "testdata", "fixture.json")

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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