微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

等到容器在 testcontainers 中启动,使用 GenericContainer 自定义 PostgreSQL 镜像

如何解决等到容器在 testcontainers 中启动,使用 GenericContainer 自定义 PostgreSQL 镜像

我正在开发基于 Testcontainers 解决方案的系统/集成测试。我需要使用我们自己的数据库 Postgresql 镜像,并且已经应用​​了数据库架构。

出于这个原因,我使用 Testcontainers GenericContainer。

private static final GenericContainer postgresDb = new GenericContainer(POSTGRES_IMAGE).withExposedPorts(5432);

我正在使用 Spring Boot 开发测试,因此我创建了抽象类,它将为所有测试保存此配置

@ActiveProfiles("test")
@SpringBoottest
public abstract class AbstractTests {

    private static final DockerImageName POSTGRES_IMAGE = DockerImageName.parse("docker-name:latest");
    private static final GenericContainer postgresDb;

    static {
        postgresDb = new GenericContainer(POSTGRES_IMAGE)
            .withExposedPorts(5432);
        postgresDb.withStartupTimeout(Duration.ofSeconds(30))
            .start();
    }

    @DynamicPropertySource
    static void properties(DynamicPropertyRegistry registry) throws InterruptedException {
        final String s = "jdbc:postgresql://"+ postgresDb.getHost() +":"+ postgresDb.getMappedPort(5432) + "/test";
        registry.add("spring.datasource.url",() ->s);
    
    }

}

然而,问题是当测试运行时,容器仍在启动。这 withStartupTimeout(Duration.ofSeconds(30)) 由于某种原因不起作用。

当我在属性方法处停止调试并花几秒钟时间启动容器时,所有测试都运行良好。

当测试失败时,我会看到下一个日志:

org.postgresql.util.PsqlException: FATAL: the database system is starting up

如果我把 Thread.sleep(..) 它也有效,这不是优选的解决方案。

等待的正确解决方案或知道容器已准备就绪的正确策略是什么?

解决方法

我认为答案就在他们的 documentation 中,尤其是这部分:

日志输出等待策略

在某些情况下,容器的日志输出是一种确定它是否准备就绪的简单方法。例如,我们可以等待容器日志中的“就绪”消息,如下所示:

public GenericContainer containerWithLogWait = new GenericContainer(DockerImageName.parse("redis:5.0.3"))
    .withExposedPorts(6379)
    .waitingFor(
        Wait.forLogMessage(".*Ready to accept connections.*\\n",1)
    );

注意:您需要将消息更改为:

".*database system is ready to accept connections.*"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。