为了账号安全,请及时绑定邮箱和手机立即绑定

Golang 使用 migrate with dockertest

Golang 使用 migrate with dockertest

Go
暮色呼如 2023-02-06 10:27:04
目标是测试数据库上的逻辑。看来dockertest可能对它有用,他们提供了如何设置测试的示例。但是,这些临时数据库是空的(没有完成迁移)。使用dockertest时如何迁移数据库?
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

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


下面TestMain是设置 Dockertest 与 postgres 数据库连接的设置函数。就在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

}



查看完整回答
反对 回复 2023-02-06
  • 1 回答
  • 0 关注
  • 204 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号