88 lines
1.9 KiB
Go
88 lines
1.9 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/testcontainers/testcontainers-go"
|
|
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
|
"github.com/testcontainers/testcontainers-go/wait"
|
|
)
|
|
|
|
func mustStartPostgresContainer() (func(context.Context, ...testcontainers.TerminateOption) error, error) {
|
|
var (
|
|
dbName = "testdb"
|
|
dbPwd = "testpass"
|
|
dbUser = "testuser"
|
|
)
|
|
|
|
dbContainer, err := postgres.Run(
|
|
context.Background(),
|
|
"postgres:latest",
|
|
postgres.WithDatabase(dbName),
|
|
postgres.WithUsername(dbUser),
|
|
postgres.WithPassword(dbPwd),
|
|
testcontainers.WithWaitStrategy(
|
|
wait.ForLog("database system is ready to accept connections").
|
|
WithOccurrence(2).
|
|
WithStartupTimeout(5*time.Second)),
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return dbContainer.Terminate, err
|
|
}
|
|
|
|
func TestMain(m *testing.M) {
|
|
teardown, err := mustStartPostgresContainer()
|
|
if err != nil {
|
|
log.Fatalf("could not start postgres container: %v", err)
|
|
}
|
|
|
|
m.Run()
|
|
|
|
if teardown != nil && teardown(context.Background()) != nil {
|
|
log.Fatalf("could not teardown postgres container: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestNew(t *testing.T) {
|
|
srv := New()
|
|
if srv == nil {
|
|
t.Fatal("New() returned nil")
|
|
}
|
|
}
|
|
|
|
func TestHealth(t *testing.T) {
|
|
srv := New()
|
|
|
|
stats := srv.Health()
|
|
|
|
// Since we don't have any databases configured in test, we expect empty stats
|
|
if len(stats) == 0 {
|
|
t.Log("No databases configured, health check returns empty stats")
|
|
return
|
|
}
|
|
|
|
// If we have databases, check their health
|
|
for dbName, dbStats := range stats {
|
|
if dbStats["status"] != "up" {
|
|
t.Errorf("database %s status is not up: %s", dbName, dbStats["status"])
|
|
}
|
|
if err, ok := dbStats["error"]; ok && err != "" {
|
|
t.Errorf("database %s has error: %s", dbName, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestClose(t *testing.T) {
|
|
srv := New()
|
|
|
|
if srv.Close() != nil {
|
|
t.Fatalf("expected Close() to return nil")
|
|
}
|
|
}
|