标签: testcontainers

使用 Testcontainers 时如何设置 Postgresql 的端口?

有时我需要为Postgresql安装一个端口,我在容器中运行该端口进行测试。但测试容器开发者命令Testcontainers删除了这个功能。但在某个地方有一个解决方案,通过设置,但我找不到它。谁有关于如何做到这一点的任何想法或信息?

public class ContainerConfig {

    private static final PostgreSQLContainer postgresSQLContainer;

    static {
        DockerImageName postgres = DockerImageName.parse("postgres:13.1");

        postgresSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer(postgres)
                .withDatabaseName("test")
                .withUsername("root")
                .withPassword("root")
                .withReuse(true);

        postgresSQLContainer.start();
    }

    @SuppressWarnings("rawtypes")
    private static PostgreSQLContainer getPostgresSQLContainer() {
        return postgresSQLContainer;
    }


    @SuppressWarnings("unused")
    @DynamicPropertySource
   public static void registerPgProperties(DynamicPropertyRegistry propertyRegistry) {

        propertyRegistry.add("integration-tests-db", getPostgresSQLContainer()::getDatabaseName);
        propertyRegistry.add("spring.datasource.username", getPostgresSQLContainer()::getUsername);
        propertyRegistry.add("spring.datasource.password", getPostgresSQLContainer()::getPassword);
        propertyRegistry.add("spring.datasource.url",  getPostgresSQLContainer()::getJdbcUrl);
    }

}

Run Code Online (Sandbox Code Playgroud)

postgresql spring-boot testcontainers java-11

10
推荐指数
1
解决办法
8678
查看次数

TestContainer 由于错误而无法启动:等待日志输出匹配超时

在为elasticserach启动testcontainer时,出现“ContainerLaunchException:等待日志输出匹配超时”。我应该如何解决这个问题?

container = new ElasticsearchContainer(ELASTICSEARCH_IMAGE)
            .withEnv("discovery.type", "single-node")
            .withExposedPorts(9200);

    container.start();
Run Code Online (Sandbox Code Playgroud)

12:16:50.370 [主要]错误[docker.elastic.co/elasticsearch/elasticsearch:7.16.3] - 无法启动容器org.testcontainers.containers.ContainerLaunchException:等待日志输出匹配'超时。(“消息”:\ s?“开始”。 |]开始$)'在org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy.waitUntilReady(LogMessageWaitStrategy.java:49)在org.testcontainers.containers.wait.strategy。 AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:51)

更新:我研究了构造函数 ElasticsearchContainer

    public ElasticsearchContainer(DockerImageName dockerImageName) {
    super(dockerImageName);
    this.caCertAsBytes = Optional.empty();
    dockerImageName.assertCompatibleWith(new DockerImageName[]{DEFAULT_IMAGE_NAME, DEFAULT_OSS_IMAGE_NAME});
    this.isOss = dockerImageName.isCompatibleWith(DEFAULT_OSS_IMAGE_NAME);
    this.logger().info("Starting an elasticsearch container using [{}]", dockerImageName);
    this.withNetworkAliases(new String[]{"elasticsearch-" + Base58.randomString(6)});
    this.withEnv("discovery.type", "single-node");
    this.addExposedPorts(new int[]{9200, 9300});
    this.isAtLeastMajorVersion8 = (new ComparableVersion(dockerImageName.getVersionPart())).isGreaterThanOrEqualTo("8.0.0");
    String regex = ".*(\"message\":\\s?\"started\".*|] started\n$)";
    this.setWaitStrategy((new LogMessageWaitStrategy()).withRegEx(regex));
    if (this.isAtLeastMajorVersion8) {
        this.withPassword("changeme");
    }

}
Run Code Online (Sandbox Code Playgroud)

它使用 setWaitStrategy。所以我更新了我的代码如下

container.setWaitStrategy((new LogMessageWaitStrategy()).withRegEx(regex).withTimes(1));
Run Code Online (Sandbox Code Playgroud)

但我仍然遇到同样的错误。这是日志消息的发送范围。

在此输入图像描述

再次更新:我意识到上面的代码更改不会更新任何默认值。

这是新的变化:

        container.setWaitStrategy((new LogMessageWaitStrategy())
                        .withRegEx(regex)
                        .withStartupTimeout(Duration.ofSeconds(180L)));
Run Code Online (Sandbox Code Playgroud)

它适用于这个新的变化。我必须从 …

elasticsearch spring-boot-test testcontainers testcontainers-junit5

10
推荐指数
1
解决办法
4843
查看次数

Spring Boot TestContainers 映射的端口只能在容器启动后获取

我正在尝试将使用 TestContainers 库的自动化测试添加到我的 Spring Boot 项目中

这是我的测试类来测试我的 jpa 存储库:

package com.ubm.mfi.repo;

import com.ubm.mfi.domain.MasterFileIndexRow;
import org.junit.ClassRule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@ExtendWith(SpringExtension.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
@ContextConfiguration(initializers = { MasterFileIndexRowRepoTest.Initializer.class })
public class MasterFileIndexRowRepoTest {

    @ClassRule
    public static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>("postgres:latest");

    @Autowired
    private MasterFileIndexRowRepo masterFileIndexRowRepo;

    // write test cases here
    @Test
    public void whenFindAllRows_thenSizeIsGreaterThanZero() …
Run Code Online (Sandbox Code Playgroud)

integration-testing automated-tests spring-data-jpa testcontainers

9
推荐指数
2
解决办法
7851
查看次数

用于使用 testcontainers 和 gradle 运行测试的 github 操作

我是 github actions 的新手(来自 gitlab-ci),我正在尝试使用管道中的 testcontainers 运行集成测试,但我陷入了困境。这是我目前的定义。

name: Run Gradle
on: push
jobs:
  gradle:
    strategy:
      matrix:
        os: [ ubuntu-18.04  ]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v1
      - uses: actions/setup-java@v1
        with:
          java-version: 11
      - uses: eskatos/gradle-command-action@v1
        with:
          build-root-directory: backend
          wrapper-directory: backend
          arguments: check assemble
Run Code Online (Sandbox Code Playgroud)

如何确保 testcontainers 项目的 docker deamon 在运行期间可用?

continuous-integration gradle testcontainers github-actions

9
推荐指数
1
解决办法
8334
查看次数

使用 testcontainers 复制资源时更改文件的所有者

我在 Java 测试中使用 testcontainers。要在容器中配置应用程序,我需要放置并安装配置文件:一些文件是静态的,因此我withClassPathResourceMapping在创建新容器时使用安装它们:

container.withClassPathResourceMapping(
  "/path/to/res",
  "/etc/app/config.name",
  BindMode.READ_ONLY
)
Run Code Online (Sandbox Code Playgroud)

其他文件是动态生成的,可以被容器中的应用程序覆盖,因此我copyFileToContainer在容器启动后使用将内容复制到容器:

container.copyFileToContainer(
 Transferable.of(bin /* byte[] */),
 "/var/app/resource.name"
)
Run Code Online (Sandbox Code Playgroud)

app:app该应用程序作为在Dockerfile.

我这里有两个类似的问题:

  1. withClassPathResourceMapping如果未找到,操作将创建丢失的目录,例如用于"/etc/app/config.name"创建"/etc/app/目录的类路径映射。但它以用户身份创建这些目录root:root,因此应用程序稍后无法在此目录中创建新文件
  2. 使用复制到容器中的文件copyFileToContainer不是只读的,可以由应用程序修改。但copyFileToContainer以用户身份创建文件root:root,因此应用程序无法写入这些文件。

我尝试chown -R /path在容器启动后执行,但此命令失败,因为执行用户不是root.

在测试容器中设置所有者和权限的正确方法是什么?

java unit-testing docker testcontainers

9
推荐指数
0
解决办法
1112
查看次数

测试容器无法配置端口绑定

我正在使用 testcontainer 版本1.15.2。测试在 windows 10 上的 intellij 中运行。我有一个wiremock 容器。默认情况下它监听端口8080。我想将此端口映射到8081. 所以我这样做:

public WiremockContainer() {
    super("wiremock/wiremock:2.9.0-alpine");

    self()
            .waitingFor(Wait.forLogMessage(".*port:\\s*8080.*", 1)
                    .withStartupTimeout(Duration.ofSeconds(25L)))
            .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig()
                    .withPortBindings(new PortBinding(Ports.Binding.bindPort(8081), new ExposedPort(8080)))
            )
            .withNetworkAliases("wiremock")
            .withExposedPorts(8081);
}
Run Code Online (Sandbox Code Playgroud)

创建容器时,它会侦听随机端口,而不是8081[1]。我究竟做错了什么 ?我应该怎么做才能让容器监听8081而不是随机端口?

[1]

  1. 我有另一个容器尝试连接http://wiremock:8081并不断获取Connection refused
  2. 当我添加:.waitingFor((...)forPort(8081)(...)));发生超时。

java spring-boot docker-java testcontainers testcontainers-junit5

9
推荐指数
2
解决办法
1万
查看次数

Dropwizard 与 Testcontainers 的集成测试

我正在尝试针对 dockered 数据库运行 dropwizard 的集成测试。

我试过的:

@ClassRule
public static final PostgreSQLContainer postgres = new PostgreSQLContainer();

@ClassRule
    public final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>(
            Application.class,
            CONFIG_PATH,
            ConfigOverride.config("dataSourceFactory.url", postgres.getJdbcUrl()),
            ConfigOverride.config("dataSourceFactory.user", postgres.getUsername()),
            ConfigOverride.config("dataSourceFactory.password", postgres.getPassword())
    );
Run Code Online (Sandbox Code Playgroud)

我得到 Caused by: java.lang.IllegalStateException: Mapped port can only be obtained after the container is started

将这些链接在一起也不起作用

@ClassRule
    public static TestRule chain = RuleChain.outerRule(postgres = new PostgreSQLContainer())
            .around(RULE = new DropwizardAppRule<>(
                    Application.class,
                    CONFIG_PATH,
                    ConfigOverride.config("dataSourceFactory.url", postgres.getJdbcUrl()),
                    ConfigOverride.config("dataSourceFactory.user", postgres.getUsername()),
                    ConfigOverride.config("dataSourceFactory.password", postgres.getPassword())
            ));
Run Code Online (Sandbox Code Playgroud)

最后这可行,但据我所知,它为每个测试运行新的 DropwizardAppRule,这并不好......

@ClassRule
public static …
Run Code Online (Sandbox Code Playgroud)

dropwizard testcontainers

8
推荐指数
1
解决办法
1874
查看次数

等待容器端口打开超时(本地主机端口:[32773] 应该正在侦听)

我正在尝试使用https://www.testcontainers.org/固有的https://github.com/testcontainers/testcontainers-scala,如下所示:

final class MessageSpec extends BddSpec
  with ForAllTestContainer
  with BeforeAndAfterAll {


  override val container = GenericContainer("sweetsoft/sapmock").configure{ c =>
    c.addExposedPort(8080)
    c.withNetwork(Network.newNetwork())
  }

  override def beforeAll() {
  }


  feature("Process incoming messages") {  
Run Code Online (Sandbox Code Playgroud)

当我使用命令运行测试时sbt test,出现以下异常:

15:22:23.171 [pool-7-thread-2] ERROR  [sweetsoft/sapmock:latest] - Could not start container
org.testcontainers.containers.ContainerLaunchException: Timed out waiting for container port to open (localhost ports: [32775] should be listening)
        at org.testcontainers.containers.wait.strategy.HostPortWaitStrategy.waitUntilReady(HostPortWaitStrategy.java:47)
        at org.testcontainers.containers.wait.strategy.AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:35)
        at org.testcontainers.containers.wait.HostPortWaitStrategy.waitUntilReady(HostPortWaitStrategy.java:23)
        at org.testcontainers.containers.wait.strategy.AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:35)
        at org.testcontainers.containers.GenericContainer.waitUntilContainerStarted(GenericContainer.java:582)
Run Code Online (Sandbox Code Playgroud)

该图像是本地图像:

docker images
REPOSITORY                    TAG                 IMAGE ID            CREATED …
Run Code Online (Sandbox Code Playgroud)

java scala docker testcontainers

8
推荐指数
1
解决办法
7275
查看次数

testcontainers、hikari 和无法验证连接 org.postgresql.jdbc.PgConnection

我有一个弹簧启动应用程序。我正在使用 testcontainers 对其进行测试,以确保 DB (postgres) 和 Repository 实现执行它们应该执行的操作。

我使用以下内容初始化容器并且运行良好。

    @Container
    @SuppressWarnings("rawtypes")
    private static final PostgreSQLContainer POSTGRE_SQL = new PostgreSQLContainer("postgres:9.6")
        .withDatabaseName("xxx")
        .withUsername("xxx")
        .withPassword("xxx");

    static class Initialiser implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            TestPropertyValues.of(
                "spring.datasource.url=" + POSTGRE_SQL.getJdbcUrl(),
                "spring.datasource.username=" + POSTGRE_SQL.getUsername(),
                "spring.jpa.hibernate.ddl-auto=create-drop"
            ).applyTo(applicationContext.getEnvironment());
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是,虽然测试成功,但在课程结束时,当容器关闭时,我从 hikari 收到以下错误消息

[31mWARN [0;39m [36mcom.zaxxer.hikari.pool.PoolBase.isConnectionAlive[0;39m - HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@4d728138 (This connection has been closed.). Possibly consider using a shorter maxLifetime value.
[31mWARN [0;39m [36mcom.zaxxer.hikari.pool.PoolBase.isConnectionAlive[0;39m - HikariPool-1 - Failed to validate …
Run Code Online (Sandbox Code Playgroud)

java spring-boot hikaricp testcontainers

8
推荐指数
1
解决办法
1629
查看次数

由于“找不到有效的 Docker 环境”,测试容器测试用例失败

我对使用测试容器很陌生。我的测试因以下异常而失败。

Running com.mastercard.example.testcontainers.testcontainersexampple.DemoControllerTest
2020-04-08 14:27:08.441  INFO   --- [           main] o.s.t.c.support.AbstractContextLoader    
: Could not detect default resource locations for test class 
resource found for suffixes {-context.xml, Context.groovy}.
2020-04-08 14:27:08.449  INFO   --- [           main] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.mastercard.example.testcontainers.testcontainersexampple.DemoControllerTest]: DemoControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
2020-04-08 14:27:08.611  INFO   --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.mastercard.example.testcontainers.testcontainersexampple.TestContainersExampleApplication for test class com.mastercard.example.testcontainers.testcontainersexampple.DemoControllerTest
2020-04-08 14:27:08.701  INFO   --- [           main] .b.t.c.SpringBootTestContextBootstrapper : …
Run Code Online (Sandbox Code Playgroud)

spring integration-testing junit4 spring-boot testcontainers

8
推荐指数
9
解决办法
1万
查看次数