All checks were successful
CI / test (push) Successful in 30s
pgxpool.NewWithConfig does not connect eagerly, so NewCluster succeeds even without a running database. Added a Ping check after cluster creation to reliably skip tests when the database cannot be reached. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
88 lines
2.0 KiB
Go
88 lines
2.0 KiB
Go
// Package dbxtest provides test helpers for users of the dbx library.
|
|
package dbxtest
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"testing"
|
|
|
|
"git.codelab.vc/pkg/dbx"
|
|
)
|
|
|
|
const (
|
|
// EnvTestDSN is the environment variable for the test database DSN.
|
|
EnvTestDSN = "DBX_TEST_DSN"
|
|
// DefaultTestDSN is the default DSN used when EnvTestDSN is not set.
|
|
DefaultTestDSN = "postgres://postgres:postgres@localhost:5432/dbx_test?sslmode=disable"
|
|
)
|
|
|
|
// TestDSN returns the DSN from the environment or the default.
|
|
func TestDSN() string {
|
|
if dsn := os.Getenv(EnvTestDSN); dsn != "" {
|
|
return dsn
|
|
}
|
|
return DefaultTestDSN
|
|
}
|
|
|
|
// NewTestCluster creates a Cluster connected to a test database.
|
|
// It skips the test if the database is not reachable.
|
|
// The cluster is automatically closed when the test finishes.
|
|
func NewTestCluster(t testing.TB, opts ...dbx.Option) *dbx.Cluster {
|
|
t.Helper()
|
|
|
|
dsn := TestDSN()
|
|
cfg := dbx.Config{
|
|
Master: dbx.NodeConfig{
|
|
Name: "test-master",
|
|
DSN: dsn,
|
|
Pool: dbx.PoolConfig{MaxConns: 5, MinConns: 1},
|
|
},
|
|
}
|
|
dbx.ApplyOptions(&cfg, opts...)
|
|
|
|
ctx := context.Background()
|
|
cluster, err := dbx.NewCluster(ctx, cfg)
|
|
if err != nil {
|
|
t.Skipf("dbxtest: cannot connect to test database: %v", err)
|
|
}
|
|
|
|
if err := cluster.Ping(ctx); err != nil {
|
|
cluster.Close()
|
|
t.Skipf("dbxtest: cannot reach test database: %v", err)
|
|
}
|
|
|
|
t.Cleanup(func() {
|
|
cluster.Close()
|
|
})
|
|
|
|
return cluster
|
|
}
|
|
|
|
// TestLogger is a Logger that writes to testing.T.
|
|
type TestLogger struct {
|
|
T testing.TB
|
|
}
|
|
|
|
func (l *TestLogger) Debug(_ context.Context, msg string, fields ...any) {
|
|
l.T.Helper()
|
|
l.T.Logf("[DEBUG] %s %v", msg, fields)
|
|
}
|
|
|
|
func (l *TestLogger) Info(_ context.Context, msg string, fields ...any) {
|
|
l.T.Helper()
|
|
l.T.Logf("[INFO] %s %v", msg, fields)
|
|
}
|
|
|
|
func (l *TestLogger) Warn(_ context.Context, msg string, fields ...any) {
|
|
l.T.Helper()
|
|
l.T.Logf("[WARN] %s %v", msg, fields)
|
|
}
|
|
|
|
func (l *TestLogger) Error(_ context.Context, msg string, fields ...any) {
|
|
l.T.Helper()
|
|
l.T.Logf("[ERROR] %s %v", msg, fields)
|
|
}
|
|
|
|
// Compile-time check.
|
|
var _ dbx.Logger = (*TestLogger)(nil)
|