有时我需要为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) 在为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
我正在尝试将使用 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
我是 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 在运行期间可用?
我在 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.
我这里有两个类似的问题:
withClassPathResourceMapping如果未找到,操作将创建丢失的目录,例如用于"/etc/app/config.name"创建"/etc/app/目录的类路径映射。但它以用户身份创建这些目录root:root,因此应用程序稍后无法在此目录中创建新文件copyFileToContainer不是只读的,可以由应用程序修改。但copyFileToContainer以用户身份创建文件root:root,因此应用程序无法写入这些文件。我尝试chown -R /path在容器启动后执行,但此命令失败,因为执行用户不是root.
在测试容器中设置所有者和权限的正确方法是什么?
我正在使用 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]
http://wiremock:8081并不断获取Connection refused.waitingFor((...)forPort(8081)(...)));发生超时。java spring-boot docker-java testcontainers testcontainers-junit5
我正在尝试针对 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) 我正在尝试使用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) 我有一个弹簧启动应用程序。我正在使用 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) 我对使用测试容器很陌生。我的测试因以下异常而失败。
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
testcontainers ×10
java ×4
spring-boot ×4
docker ×2
docker-java ×1
dropwizard ×1
gradle ×1
hikaricp ×1
java-11 ×1
junit4 ×1
postgresql ×1
scala ×1
spring ×1
unit-testing ×1