首頁 > 後端開發 > Golang > 主體

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

WBOY
發布: 2024-02-06 11:42:04
轉載
651 人瀏覽過

在带有 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!