首页  >  文章  >  后端开发  >  在带有 postgres 的 go test 容器中使用 tern 迁移

在带有 postgres 的 go test 容器中使用 tern 迁移

WBOY
WBOY转载
2024-02-06 11:42:04629浏览

在带有 postgres 的 go test 容器中使用 tern 迁移

问题内容

我正在尝试为我的 Postgres 数据库编写集成测试。为此,我在 Go 中使用测试容器。我已经在实际数据库中使用 tern 迁移,并将迁移放在迁移文件夹中。问题是我的一些迁移使用 .tern.conf 文件中的属性,因为这些值可能因环境而异。我为本地创建了一个类似的配置文件 local.tern.conf 并尝试设置全局变量。但由于某种原因,当我运行迁移时,这些值没有被选择。这是一个例子-

func SetupTestDatabase() *TestDatabase {
    // Set the TERN_CONFIG environment variable to the path of your local.tern.conf file
    if err := os.Setenv("TERN_CONFIG", "../local.tern.conf"); err != nil {
        // Handle error if setting the environment variable fails
        zap.S().Fatal("failed to set TERN_CONFIG", err)
    }

    // setup db container
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*60)
    defer cancel()

    container, dbInstance, dbAddr, err := createContainer(ctx)
    if err != nil {
        zap.S().Fatal("failed to setup test", err)
    }

    conn, _ := dbInstance.Acquire(ctx)
    m, err := migrate.NewMigrator(ctx, conn.Conn(), "schema_version_table")
    if err != nil {
        zap.S().Fatal("failed to setup migrator", err)
    }

    if err := m.LoadMigrations("../migrations"); err != nil {
        zap.S().Fatal("failed to load migrations", err)
        return nil
    }

    if len(m.Migrations) == 0 {
        zap.S().Fatal("no migrations found")
        return nil
    }

    if err := m.Migrate(ctx); err != nil {
        zap.S().Fatal("failed to migrate", err)
        return nil
    }

    return &TestDatabase{
        container:  container,
        DbInstance: dbInstance,
        DbAddress:  dbAddr,
    }
}

这是我的迁移的一部分 -

....
CREATE TABLE {{.version_table}} (
    version integer NOT NULL
);

alter table {{.version_table}}
    owner to {{.master_user}};
.....

这是 local.tern.conf-

[database]
 host = <host>
 port = 5432
 database = <db name>
 version_table = schema_version_table

[data]
 master_user = <user>

正确答案


我猜配置文件必须针对 testcontainers-go 提供的随机端口,而不是 Postgres 的默认 5432 端口。您可能需要使用容器的 HostMappedPort 方法动态生成该文件,从 testcontainers-go 获取主机和随机端口。请参阅 https://golang.testcontainers.org/features/networking /#获取容器主机

ip, _ := nginxC.Host(ctx)
port, _ := nginxC.MappedPort(ctx, "80")
_, _ = http.Get(fmt.Sprintf("http://%s:%s", ip, port.Port()))

你能尝试一下吗?

另一种选择是使用“Testcontainers Desktop”,它允许定义给定服务(postgres)的端口,以透明的方式将对该端口的任何请求代理到随机端口。请参阅https://www.php.cn/link/9a4d6e8685bd057e4f68930bd7c8ecc0

以上是在带有 postgres 的 go test 容器中使用 tern 迁移的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除