Add dbx library: PostgreSQL cluster with master/replica routing, retry, health checking
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
82
dbxtest/dbxtest.go
Normal file
82
dbxtest/dbxtest.go
Normal file
@@ -0,0 +1,82 @@
|
||||
// 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)
|
||||
}
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user