Golang使用带有dockertest的migrate



目标是在数据库上测试逻辑。dockertest似乎对它很有用,它们提供了如何设置测试的示例。但是,这些临时数据库是空的(没有进行迁移(。

使用dockertest时如何迁移数据库?

不确定这是最好的方法,但我已经连接了几个例子,并在测试设置中通过[golang migrate]lib提出了一个完整的迁移。

TestMain下面是设置函数,用于设置带有postgres DB连接的Dockertest。就在运行测试的m.Run()之前,还有runMigrations,它使用golang migrate来提取本地目录中的所有脚本,并将它们应用到数据库。它有效,但相当慢。

func TestMain(m *testing.M) {
// uses a sensible default on windows (tcp/http) and linux/osx (socket)
pool, err := dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// pulls an image, creates a container based on it and runs it
resource, err := pool.RunWithOptions(&dockertest.RunOptions{
Repository: "postgres",
Tag:        "11",
Env: []string{
"POSTGRES_PASSWORD=secret",
"POSTGRES_USER=user_name",
"POSTGRES_DB=dbname",
"listen_addresses = '*'",
},
}, func(config *docker.HostConfig) {
// set AutoRemove to true so that stopped container goes away by itself
config.AutoRemove = true
config.RestartPolicy = docker.RestartPolicy{Name: "no"}
})
if err != nil {
log.Fatalf("Could not start resource: %s", err)
}
hostAndPort := resource.GetHostPort("5432/tcp")
databaseUrl := fmt.Sprintf("postgres://user_name:secret@%s/dbname?sslmode=disable", hostAndPort)
log.Println("Connecting to database on url: ", databaseUrl)
resource.Expire(120) // Tell docker to hard kill the container in 120 seconds
// exponential backoff-retry, because the application in the container might not be ready to accept connections yet
pool.MaxWait = 120 * time.Second
if err = pool.Retry(func() error {
db, err = sql.Open("postgres", databaseUrl)
if err != nil {
return err
}
return db.Ping()
}); err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
// Migrating DB
if err := runMigrations("../migrations", db); err != nil {
log.Fatalf("Could not migrate db: %s", err)
}
//Run tests
code := m.Run()
// You can't defer this because os.Exit doesn't care for defer
if err := pool.Purge(resource); err != nil {
log.Fatalf("Could not purge resource: %s", err)
}
os.Exit(code)
}
func runMigrations(migrationsPath string, db *sql.DB) error {
if migrationsPath == "" {
return errors.New("missing migrations path")
}
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
return err
}
m, err := migrate.NewWithDatabaseInstance("file://"+migrationsPath, "postgres", driver)
if err != nil {
return err
}
err = m.Up()
if err != nil && err != migrate.ErrNoChange {
return err
}
return nil
}

最新更新