This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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