テストといいつつ、実際はアプリケーションからコンテナを立ち上げるライブラリと言える
ユースケース
- DBを使った統合テストをしたいとき
- ローカル起動時に依存関係を立ち上げたいとき
- DBの他にも
- localstackとかもあげられるよね
go
こんな感じで書くと、コンテナを立ち上げた上で接続文字列を含む構造体を返す関数として定義できる
func CreatePostgresContainer(ctx context.Context) *PostgresContainer {
rootPath := ProjectRoot()
pgContainer, err := postgres.Run(ctx,
"postgres:16.3-alpine",
postgres.WithInitScripts(filepath.Join(rootPath, "db", "schema.sql")),
postgres.WithDatabase("test-db"),
postgres.WithUsername("postgres"),
postgres.WithPassword("postgres"),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).WithStartupTimeout(5*time.Second)),
)
if err != nil {
log.Fatal(err)
}
connStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
if err != nil {
log.Fatal(err)
}
return &PostgresContainer{
PostgresContainer: pgContainer,
ConnectionString: connStr,
}
}