Skip to content

Commit

Permalink
chore: use testify assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
mdelapenya committed Feb 14, 2024
1 parent 50a011d commit b7d6e90
Showing 1 changed file with 13 additions and 41 deletions.
54 changes: 13 additions & 41 deletions modules/postgres/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,82 +228,54 @@ func TestSnapshot(t *testing.T) {
WithOccurrence(2).
WithStartupTimeout(5*time.Second)),
)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

// Run any migrations on the database
_, _, err = container.Exec(ctx, []string{"psql", "-U", user, "-d", dbname, "-c", "CREATE TABLE users (id SERIAL, name TEXT NOT NULL, age INT NOT NULL)"})
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

// 2. Create a snapshot of the database to restore later
err = container.Snapshot(ctx, postgres.WithSnapshotName("test-snapshot"))
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

// Clean up the container after the test is complete
t.Cleanup(func() {
if err := container.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
require.NoError(t, container.Terminate(ctx))
})

dbURL, err := container.ConnectionString(ctx)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

t.Run("Test inserting a user", func(t *testing.T) {
t.Cleanup(func() {
// 3. In each test, reset the DB to its snapshot state.
err = container.Restore(ctx)
if err != nil {
t.Fatal(err)
}
require.NoError(t, container.Restore(ctx))
})

conn, err := pgx.Connect(context.Background(), dbURL)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
defer conn.Close(context.Background())

_, err = conn.Exec(ctx, "INSERT INTO users(name, age) VALUES ($1, $2)", "test", 42)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

var name string
var age int64
err = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)

if name != "test" {
t.Fatalf("Expected %s to equal `test`", name)
}
if age != 42 {
t.Fatalf("Expected %d to equal `42`", age)
}
assert.Equal(t, "test", name)
assert.Equal(t, int64(42), age)
})

// 4. Run as many tests as you need, they will each get a clean database
t.Run("Test querying empty DB", func(t *testing.T) {
t.Cleanup(func() {
err = container.Restore(ctx)
if err != nil {
t.Fatal(err)
}
require.NoError(t, container.Restore(ctx))
})

conn, err := pgx.Connect(context.Background(), dbURL)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
defer conn.Close(context.Background())

var name string
Expand Down

0 comments on commit b7d6e90

Please sign in to comment.