我想使用 testcontainers 进行集成测试。我需要针对 Clickhouse 存储进行测试。
docker 镜像是 yandex/clichouse-server
到目前为止我的代码(主要从 testcontainers 网站上的官方 redis 示例导入):
ctx := context.Background()
req := testcontainers.ContainerRequest{
Image: "yandex/clickhouse-server",
ExposedPorts: []string{"9000/tcp"},
}
chContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
require.NoError(t, err, "unexpected error while creating clickhouse container")
endpoint, err := chContainer.Endpoint(ctx, "")
require.NoError(t, err)
这会在获取端点时抛出错误未找到端口
,并且我不确定从哪里开始。
最佳答案
您是否尝试过在 Testcontainers Go 中使用等待 API? https://github.com/testcontainers/testcontainers-go/tree/main/wait
有了它们,您将能够等待多件事(甚至是同时等待):
- 日志条目
- 准备好端口
- SQL 查询
- HTTP 请求
- 在容器中运行程序后的退出代码
您可以在存储库中找到有用的示例。即日志条目的示例:
ctx := context.Background()
req := ContainerRequest{
Image: "docker.io/mysql:latest",
ExposedPorts: []string{"3306/tcp", "33060/tcp"},
Env: map[string]string{
"MYSQL_ROOT_PASSWORD": "password",
"MYSQL_DATABASE": "database",
},
WaitingFor: wait.ForLog("test context timeout").WithStartupTimeout(1 * time.Second),
}
_, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: req,
Started: true,
})
编辑:一个更详细的示例,包括使用 HTTP 请求的等待策略:
const (
dbName = "crazy"
fakeUser = "jondoe"
fakePassword = "bond girl"
)
ctx := context.Background()
req := ContainerRequest{
Image: "clickhouse/clickhouse-server",
Env: map[string]string{
"CLICKHOUSE_DB": dbName,
"CLICKHOUSE_USER": fakeUser,
"CLICKHOUSE_PASSWORD": fakePassword,
},
ExposedPorts: []string{
"8123/tcp",
"9000/tcp",
},
WaitingFor: wait.ForAll(
wait.ForHTTP("/ping").WithPort("8123/tcp").WithStatusCodeMatcher(
func(status int) bool {
return status == http.StatusOK
},
),
),
}
clickhouseContainer, err := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Fatal(err)
}
defer clickhouseContainer.Terminate(ctx)
关于go - 如何使用 testcontainers 启动 clickhouse 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73652833/