Skip to content

Instantly share code, notes, and snippets.

@eekwong
Created June 10, 2022 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eekwong/7df897ddc82d6369d4f23df0d7a56b41 to your computer and use it in GitHub Desktop.
Save eekwong/7df897ddc82d6369d4f23df0d7a56b41 to your computer and use it in GitHub Desktop.
func SetupDatabase(t *testing.T) (func(), *sql.DB) {
pool, _ := dockertest.NewPool("")
# specify the container image here
postgres, _ := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "postgres",
Tag: "13.2",
Env: []string{
"POSTGRES_USER=postgres",
"POSTGRES_PASSWORD=password",
},
}, func(config *docker.HostConfig) {
config.AutoRemove = true
config.RestartPolicy = docker.RestartPolicy{
Name: "no",
}
})
opts := flag.NewDefaultPostgresOpts()
# get the container port
opts.PostgresPort, _ = strconv.Atoi(postgres.GetPort("5432/tcp"))
var conn *sql.DB
if err := pool.Retry(func() error {
conn, err = sql.Open("postgres", opts.ConnectionString())
if err != nil {
return err
}
return conn.Ping()
}); err != nil {
t.Errorf("Could not connect to database: %s", err)
t.FailNow()
}
# this func() is the teardown function after the test
return func() {
if err := pool.Purge(postgres); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}
}, conn
}
# now we can use this function to launch a real database in the test
func TestSomething(t *testing.T) {
teardown, conn := unittest.SetupDatabase(t)
defer teardown()
# use conn
conn.Exec(...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment