// Package pgtest starts one Postgres container per test binary for the // plugin's database tests and migrates the plugin's tables into it. package pgtest import ( "bytes" "context" "database/sql" "sync" "testing" "time" "git.golem15.com/golem15/sm-golem-plugin/updates" "git.golem15.com/golem15/summercms/modules/lagoon" "github.com/go-gormigrate/gormigrate/v2" "github.com/testcontainers/testcontainers-go/modules/postgres" "gorm.io/gorm" ) var ( once sync.Once gdb *gorm.DB sqlDB *sql.DB err error ) // DB returns the shared, migrated database; the column encryption keys // are test-only. Tests that need an empty table delete its rows first. func DB(t testing.TB) *gorm.DB { t.Helper() once.Do(func() { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) defer cancel() if err = lagoon.PublishEncryptionKeys(nil, bytes.Repeat([]byte("G"), 32), nil); err != nil { return } var ctr *postgres.PostgresContainer ctr, err = postgres.Run(ctx, "postgres:16-alpine", postgres.WithDatabase("golem"), postgres.WithUsername("golem"), postgres.WithPassword("golem"), postgres.BasicWaitStrategies(), ) if err != nil { return } var dsn string if dsn, err = ctr.ConnectionString(ctx, "sslmode=disable"); err != nil { return } if sqlDB, err = sql.Open("pgx", dsn); err != nil { return } if gdb, err = lagoon.Use(ctx, sqlDB); err != nil { return } err = gormigrate.New(gdb, &gormigrate.Options{ TableName: "summer_migrations_golem15_golem", UseTransaction: true, }, updates.All()).Migrate() }) if err != nil { t.Fatalf("pgtest: %v", err) } return gdb } // SQL is the database's *sql.DB. func SQL(t testing.TB) *sql.DB { DB(t) return sqlDB }