Skip to content

Commit

Permalink
Add TestMain to migrations tests
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew-farries committed Jan 2, 2024
1 parent 66ccf91 commit c33c8f5
Showing 1 changed file with 77 additions and 20 deletions.
97 changes: 77 additions & 20 deletions pkg/migrations/op_common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"database/sql"
"errors"
"fmt"
"log"
"math/rand"
"net/url"
"os"
"testing"
"time"
Expand Down Expand Up @@ -37,6 +40,45 @@ type TestCase struct {

type TestCases []TestCase

var tConnStr string

// TestMain starts a postgres container to be used by all tests in the package.
// Each test then connects to the container and creates a new database.
func TestMain(m *testing.M) {
ctx := context.Background()

waitForLogs := wait.
ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(5 * time.Second)

pgVersion := os.Getenv("POSTGRES_VERSION")
if pgVersion == "" {
pgVersion = defaultPostgresVersion
}

ctr, err := postgres.RunContainer(ctx,
testcontainers.WithImage("postgres:"+pgVersion),
testcontainers.WithWaitStrategy(waitForLogs),
)
if err != nil {
os.Exit(1)
}

tConnStr, err = ctr.ConnectionString(ctx, "sslmode=disable")
if err != nil {
os.Exit(1)
}

exitCode := m.Run()

if err := ctr.Terminate(ctx); err != nil {
log.Printf("Failed to terminate container: %v", err)
}

os.Exit(exitCode)
}

func ExecuteTests(t *testing.T, tests TestCases) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -100,50 +142,53 @@ func ExecuteTests(t *testing.T, tests TestCases) {
}
}

// withMigratorAndConnectionToContainer:
// * connects to the test container created in TestMain.
// * creates a new database.
// * initializes pgroll in the new database.
// * runs the supplied test function with a migrator and a connection to the new database.
func withMigratorAndConnectionToContainer(t *testing.T, fn func(mig *roll.Roll, db *sql.DB)) {
t.Helper()
ctx := context.Background()

waitForLogs := wait.
ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(5 * time.Second)

pgVersion := os.Getenv("POSTGRES_VERSION")
if pgVersion == "" {
pgVersion = defaultPostgresVersion
}

ctr, err := postgres.RunContainer(ctx,
testcontainers.WithImage("postgres:"+pgVersion),
testcontainers.WithWaitStrategy(waitForLogs),
)
tDB, err := sql.Open("postgres", tConnStr)
if err != nil {
t.Fatal(err)
}

t.Cleanup(func() {
if err := ctr.Terminate(ctx); err != nil {
t.Fatalf("Failed to terminate container: %v", err)
if err := tDB.Close(); err != nil {
t.Fatalf("Failed to close database connection: %v", err)
}
})

cStr, err := ctr.ConnectionString(ctx, "sslmode=disable")
dbName := randomDBName()

_, err = tDB.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE %s", pq.QuoteIdentifier(dbName)))
if err != nil {
t.Fatal(err)
}

st, err := state.New(ctx, cStr, "pgroll")
u, err := url.Parse(tConnStr)
if err != nil {
t.Fatal(err)
}

u.Path = "/" + dbName
connStr := u.String()

st, err := state.New(ctx, connStr, "pgroll")
if err != nil {
t.Fatal(err)
}

err = st.Init(ctx)
if err != nil {
t.Fatal(err)
}

const lockTimeoutMs = 500
mig, err := roll.New(ctx, cStr, "public", lockTimeoutMs, st)
mig, err := roll.New(ctx, connStr, "public", lockTimeoutMs, st)
if err != nil {
t.Fatal(err)
}
Expand All @@ -154,7 +199,7 @@ func withMigratorAndConnectionToContainer(t *testing.T, fn func(mig *roll.Roll,
}
})

db, err := sql.Open("postgres", cStr)
db, err := sql.Open("postgres", connStr)
if err != nil {
t.Fatal(err)
}
Expand All @@ -168,6 +213,18 @@ func withMigratorAndConnectionToContainer(t *testing.T, fn func(mig *roll.Roll,
fn(mig, db)
}

func randomDBName() string {
const length = 15
const charset = "abcdefghijklmnopqrstuvwxyz"

b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))] // #nosec G404
}

return "testdb_" + string(b)
}

// Common assertions

func ViewMustExist(t *testing.T, db *sql.DB, schema, version, view string) {
Expand Down

0 comments on commit c33c8f5

Please sign in to comment.