test: Use a template to prevent migrations from running for every test (#2462)

* test: Use a template to prevent migrations from running for every test

* Create a single makefile target

* Fix built-in race

* Extend timeout of built-in PostgreSQL fetch
This commit is contained in:
Kyle Carberry
2022-06-27 12:07:39 -05:00
committed by GitHub
parent d9da96cad0
commit 6429dfee1f
7 changed files with 63 additions and 38 deletions

View File

@ -13,6 +13,7 @@ import (
"github.com/ory/dockertest/v3/docker"
"golang.org/x/xerrors"
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/cryptorand"
)
@ -22,7 +23,7 @@ var openPortMutex sync.Mutex
// Open creates a new PostgreSQL server using a Docker container.
func Open() (string, func(), error) {
if os.Getenv("DB") == "ci" {
if os.Getenv("DB_FROM") != "" {
// In CI, creating a Docker container for each test is slow.
// This expects a PostgreSQL instance with the hardcoded credentials
// available.
@ -39,9 +40,9 @@ func Open() (string, func(), error) {
}
dbName = "ci" + dbName
_, err = db.Exec("CREATE DATABASE " + dbName)
_, err = db.Exec("CREATE DATABASE " + dbName + " WITH TEMPLATE " + os.Getenv("DB_FROM"))
if err != nil {
return "", nil, xerrors.Errorf("create db: %w", err)
return "", nil, xerrors.Errorf("create db with template: %w", err)
}
deleteDB := func() {
@ -74,7 +75,7 @@ func Open() (string, func(), error) {
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "postgres",
Tag: "11",
Tag: "13",
Env: []string{
"POSTGRES_PASSWORD=postgres",
"POSTGRES_USER=postgres",
@ -133,6 +134,10 @@ func Open() (string, func(), error) {
if err != nil {
return xerrors.Errorf("ping postgres: %w", err)
}
err = database.MigrateUp(db)
if err != nil {
return xerrors.Errorf("migrate db: %w", err)
}
return nil
})