下面列出了org.junit.jupiter.api.extension.ExtensionConfigurationException#org.testcontainers.containers.GenericContainer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public TestingKuduServer()
{
Network network = Network.newNetwork();
ImmutableList.Builder<GenericContainer<?>> tServersBuilder = ImmutableList.builder();
this.master = new GenericContainer<>("apache/kudu:1.10.0")
.withExposedPorts(KUDU_MASTER_PORT)
.withCommand("master")
.withNetwork(network)
.withNetworkAliases("kudu-master");
for (int instance = 0; instance < NUMBER_OF_REPLICA; instance++) {
String instanceName = "kudu-tserver-" + instance;
GenericContainer<?> tableServer = new GenericContainer<>("apache/kudu:1.10.0")
.withExposedPorts(KUDU_TSERVER_PORT)
.withCommand("tserver")
.withEnv("KUDU_MASTERS", "kudu-master:" + KUDU_MASTER_PORT)
.withNetwork(network)
.withNetworkAliases("kudu-tserver-" + instance)
.dependsOn(master)
.withEnv("TSERVER_ARGS", "--fs_wal_dir=/var/lib/kudu/tserver --use_hybrid_clock=false --rpc_advertised_addresses=" + instanceName);
tServersBuilder.add(tableServer);
}
this.tServers = tServersBuilder.build();
master.start();
tServers.forEach(GenericContainer::start);
}
@Override
public Map<String, String> start() {
LOGGER.info(TestcontainersConfiguration.getInstance().toString());
try {
container = new GenericContainer<>(CONTAINER_IMAGE)
.withExposedPorts(HOTROD_PORT)
.withEnv("USER", USER)
.withEnv("PASS", PASS)
.waitingFor(Wait.forListeningPort());
container.start();
return CollectionHelper.mapOf(
"quarkus.infinispan-client.server-list", getHostAndPort(container, HOTROD_PORT),
"quarkus.infinispan-client.near-cache-max-entries", "3",
"quarkus.infinispan-client.auth-username", USER,
"quarkus.infinispan-client.auth-password", PASS,
"quarkus.infinispan-client.auth-realm", "default",
"quarkus.infinispan-client.sasl-mechanism", "DIGEST-MD5",
"quarkus.infinispan-client.auth-server-name", "infinispan");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Map<String, String> start() {
LOGGER.info(TestcontainersConfiguration.getInstance().toString());
try {
container = new GenericContainer(CONTAINER_IMAGE)
.withExposedPorts(CONTAINER_PORT)
.withCommand("agent", "-dev", "-server", "-bootstrap", "-client", "0.0.0.0", "-log-level", "trace")
.waitingFor(Wait.forLogMessage(".*Synced node info.*", 1));
container.start();
return CollectionHelper.mapOf(
"camel.consul.test-url",
String.format("http://%s:%d",
container.getContainerIpAddress(),
container.getMappedPort(CONTAINER_PORT)));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void simpleRecursiveClasspathResourceTest() {
// This test combines the copying of classpath resources from JAR files with the recursive TAR approach, to allow JARed classpath resources to be copied in to an image
GenericContainer container = new GenericContainer(
new ImageFromDockerfile()
.withDockerfileFromBuilder(builder ->
builder.from("alpine:3.3")
.copy("/tmp/foo", "/foo")
.cmd("ls -lRt /foo")
.build()
).withFileFromClasspath("/tmp/foo", "/recursive/dir")) // here we use /org/junit as a directory that really should exist on the classpath
.withStartupCheckStrategy(new OneShotStartupCheckStrategy());
container.start();
final String results = container.getLogs();
// ExternalResource.class is known to exist in a subdirectory of /org/junit so should be successfully copied in
assertTrue("The container has a file that was copied in via a recursive copy from a JAR resource", results.contains("content.txt"));
}
@Override
public ServicesControl startZookeeper() {
GenericContainer<?> zookeeper = this.getZookeeper(
null, VersionedPipelines.defaultTags.zookeeperTag);
zookeeper.start();
return new ServicesControl() {
@Override
public GenericContainer<?> getContainer() { return zookeeper; }
@Override
public void close() {
zookeeper.stop();
}
@Override
public int getPort() {
return zookeeper.getMappedPort(ContainersProvider.ZOOKEEPER_PORT);
}
};
}
void configureKafka() {
// If a KafkaContainer is defined, store the bootstrap location
Class<?> KafkaContainer = tryLoad("org.testcontainers.containers.KafkaContainer");
if (KafkaContainer == null)
return;
Set<GenericContainer<?>> kafkaContainers = containers.allContainers.stream()
.filter(c -> KafkaContainer.isAssignableFrom(c.getClass()))
.collect(Collectors.toSet());
if (kafkaContainers.size() == 1) {
try {
GenericContainer<?> kafka = kafkaContainers.iterator().next();
String bootstrapServers = (String) KafkaContainer.getMethod("getBootstrapServers").invoke(kafka);
System.setProperty("org.microshed.kafka.bootstrap.servers", bootstrapServers);
LOG.debug("Discovered KafkaContainer with bootstrap.servers=" + bootstrapServers);
} catch (Exception e) {
LOG.warn("Unable to set kafka boostrap server", e);
}
} else if (kafkaContainers.size() > 1) {
LOG.info("Located multiple KafkaContainer instances. Unable to auto configure kafka clients");
} else {
LOG.debug("No KafkaContainer instances found in configuration");
}
}
@Test
public void copyFileToContainerFolderTest() throws Exception {
try (
GenericContainer alpineCopyToContainer = new GenericContainer("alpine:3.2")
.withCommand("top")
) {
alpineCopyToContainer.start();
final MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt");
alpineCopyToContainer.copyFileToContainer(mountableFile, "/home/");
File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_to_container.txt");
alpineCopyToContainer.copyFileFromContainer("/home/test_copy_to_container.txt", actualFile.getPath());
File expectedFile = new File(mountableFile.getResolvedPath());
assertTrue("Files aren't same ", FileUtils.contentEquals(expectedFile, actualFile));
}
}
@SuppressWarnings("resource")
private GenericContainer<?> createDockerBackend() {
return new GenericContainer<>(
new ImageFromDockerfile()
.withFileFromClasspath("conf/log4j.properties", "backend/conf/log4j.properties")
.withFileFromClasspath("conf/catalina.properties", "backend/conf/catalina.properties")
.withFileFromClasspath("conf/id_rsa", "backend/conf/id_rsa.pri")
.withFileFromClasspath("conf/id_rsa.pub", "backend/conf/id_rsa.pub")
.withFileFromClasspath("Dockerfile", "backend/Dockerfile"))
.withLogConsumer(frame -> LOGGER.debug("<linshare-backend> " + frame.getUtf8String()))
.withNetworkAliases("backend")
.withEnv("SMTP_HOST", "linshare_smtp")
.withEnv("SMTP_PORT", "25")
.withEnv("POSTGRES_HOST", "linshare_database")
.withEnv("POSTGRES_PORT", "5432")
.withEnv("POSTGRES_USER", "linshare")
.withEnv("POSTGRES_PASSWORD", "linshare")
.withEnv("MONGODB_HOST", "linshare_mongodb")
.withEnv("MONGODB_PORT", "27017")
.withEnv("THUMBNAIL_ENABLE", "false")
.withExposedPorts(LINSHARE_BACKEND_PORT)
.waitingFor(Wait.forLogMessage(WAIT_FOR_BACKEND_INIT_LOG, 1)
.withStartupTimeout(Duration.ofMinutes(10)))
.withNetwork(network);
}
@Test
public void copyFolderToContainerFolderTest() throws Exception {
try (
GenericContainer alpineCopyToContainer = new GenericContainer("alpine:3.2")
.withCommand("top")
) {
alpineCopyToContainer.start();
final MountableFile mountableFile = MountableFile.forClasspathResource("mappable-resource/");
alpineCopyToContainer.copyFileToContainer(mountableFile, "/home/test/");
File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_to_container.txt");
alpineCopyToContainer.copyFileFromContainer("/home/test/test-resource.txt", actualFile.getPath());
File expectedFile = new File(mountableFile.getResolvedPath() + "/test-resource.txt");
assertTrue("Files aren't same ", FileUtils.contentEquals(expectedFile, actualFile));
}
}
@Test
public void withTmpFsTest() throws Exception {
try (
GenericContainer container = new GenericContainer()
.withCommand("top")
.withTmpFs(singletonMap("/testtmpfs", "rw"))
) {
container.start();
// check file doesn't exist
String path = "/testtmpfs/test.file";
Container.ExecResult execResult = container.execInContainer("ls", path);
assertEquals("tmpfs inside container works fine", execResult.getStderr(),
"ls: /testtmpfs/test.file: No such file or directory\n");
// touch && check file does exist
container.execInContainer("touch", path);
execResult = container.execInContainer("ls", path);
assertEquals("tmpfs inside container works fine", execResult.getStdout(), path + "\n");
}
}
@Test
public void copyFileToContainerFileTest() throws Exception {
try (
GenericContainer alpineCopyToContainer = new GenericContainer("alpine:3.2")
.withCommand("top")
) {
alpineCopyToContainer.start();
final MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt");
alpineCopyToContainer.copyFileToContainer(mountableFile, "/test.txt");
File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_to_container.txt");
alpineCopyToContainer.copyFileFromContainer("/test.txt", actualFile.getPath());
File expectedFile = new File(mountableFile.getResolvedPath());
assertTrue("Files aren't same ", FileUtils.contentEquals(expectedFile, actualFile));
}
}
@SuppressWarnings("resource")
private GenericContainer<?> createLinshareBackendInit() {
return new GenericContainer<>("linagora/linshare-init:2.3.2")
.withNetworkAliases("init")
.withLogConsumer(frame -> LOGGER.debug("<linshare-init> " + frame.getUtf8String()))
.withEnv("LS_HOST", "backend")
.withEnv("LS_PORT", "8080")
.withEnv("LS_LDAP_NAME", "ldap-local")
.withEnv("LS_LDAP_URL", "ldap://ldap:389")
.withEnv("LS_LDAP_BASE_DN", "ou=People,dc=linshare,dc=org")
.withEnv("LS_LDAP_DN", "cn=linshare,dc=linshare,dc=org")
.withEnv("LS_LDAP_PW", "linshare")
.withEnv("LS_DOMAIN_PATTERN_NAME", "openldap-local")
.withEnv("LS_DOMAIN_PATTERN_MODEL", "868400c0-c12e-456a-8c3c-19e985290586")
.withEnv("NO_REPLY_ADDRESS", "[email protected]")
.withEnv("DEBUG", "1")
.withEnv("FORCE_INIT", "1")
.waitingFor(Wait.forLogMessage(WAIT_FOR_LDAP_INIT_LOG, 1)
.withStartupTimeout(Duration.ofMinutes(10)))
.withNetwork(network);
}
@Bean(name = "graphite", destroyMethod = "stop")
public GenericContainer graphite(
ConfigurableEnvironment environment, WaitStrategy graphiteWaitStrategy) {
GenericContainer container =
new GenericContainer("graphiteapp/graphite-statsd:1.1.5-12")
.withLogConsumer(containerLogsConsumer(log))
.withExposedPorts(PICKLE_RECEIVER_PORT)
.waitingFor(graphiteWaitStrategy)
.withClasspathResourceMapping(
"/external/graphite/storage-schemas.conf",
"/opt/graphite/conf/storage-schemas.conf",
BindMode.READ_ONLY)
.withStartupTimeout(Duration.ofSeconds(30));
container.start();
Map<String, Object> map = registerEnvironment(environment, container);
log.info("Started Graphite server. Connection details: {}", map);
return container;
}
@Test
public void shouldWorkWithMutlipleDependencies() {
InvocationCountingStartable startable1 = new InvocationCountingStartable();
InvocationCountingStartable startable2 = new InvocationCountingStartable();
try (
GenericContainer container = new GenericContainer()
.withStartupCheckStrategy(new OneShotStartupCheckStrategy())
.dependsOn(startable1, startable2)
) {
container.start();
}
VisibleAssertions.assertEquals("Startable1 started once", 1, startable1.getStartInvocationCount().intValue());
VisibleAssertions.assertEquals("Startable2 started once", 1, startable2.getStartInvocationCount().intValue());
}
@Bean(name = "prometheus", destroyMethod = "stop")
public GenericContainer prometheus(
ConfigurableEnvironment environment, WaitStrategy prometheusWaitStrategy) {
GenericContainer container =
new GenericContainer("prom/prometheus:v2.10.0")
.withLogConsumer(containerLogsConsumer(log))
.withExposedPorts(PORT)
.withCopyFileToContainer(
MountableFile.forClasspathResource("/external/prometheus/prometheus.yml"),
"/etc/prometheus/prometheus.yml")
.waitingFor(prometheusWaitStrategy)
.withStartupTimeout(Duration.ofSeconds(30));
container.start();
Map<String, Object> env = registerEnvironment(environment, container.getMappedPort(PORT));
log.info("Started Prometheus server. Connection details: {}", env);
return container;
}
private Set<GenericContainer<?>> discoverContainers(Class<?> clazz) {
Set<GenericContainer<?>> discoveredContainers = new HashSet<>();
for (Field containerField : AnnotationSupport.findAnnotatedFields(clazz, Container.class)) {
if (!Modifier.isPublic(containerField.getModifiers()))
throw new ExtensionConfigurationException("@Container annotated fields must be public visibility");
if (!Modifier.isStatic(containerField.getModifiers()))
throw new ExtensionConfigurationException("@Container annotated fields must be static");
boolean isStartable = GenericContainer.class.isAssignableFrom(containerField.getType());
if (!isStartable)
throw new ExtensionConfigurationException("@Container annotated fields must be a subclass of " + GenericContainer.class);
try {
GenericContainer<?> startableContainer = (GenericContainer<?>) containerField.get(null);
discoveredContainers.add(startableContainer);
} catch (IllegalArgumentException | IllegalAccessException e) {
LOG.warn("Unable to access field " + containerField, e);
}
}
return discoveredContainers;
}
@SuppressWarnings("resource")
@Test
public void testValidDockerignore() throws Exception {
ImageFromDockerfile img = new ImageFromDockerfile()
.withFileFromPath(".", DockerfileBuildTest.RESOURCE_PATH)
.withDockerfile(DockerfileBuildTest.RESOURCE_PATH.resolve("Dockerfile-currentdir"));
try(
final GenericContainer<?> container = new GenericContainer<>(img.get())
.withStartupCheckStrategy(new OneShotStartupCheckStrategy())
.withCommand("ls", "/")
) {
container.start();
final String logs = container.getLogs();
assertTrue("Files in the container indicated the .dockerignore was not applied. Output was: " + logs,
logs.contains("should_not_be_ignored.txt"));
assertTrue("Files in the container indicated the .dockerignore was not applied. Output was: " + logs,
!logs.contains("should_be_ignored.txt"));
}
}
private void initServer() {
server = new GenericContainer(databaseServerInfo.getDatabaseType().toDockerImageName() + ":" + databaseServerInfo.getDockerImageTag())
.withEnv("MYSQL_USER", "mysql")
.withEnv("MYSQL_PASSWORD", "password")
.withEnv("MYSQL_ROOT_PASSWORD", "password")
.withEnv("MYSQL_DATABASE", "testschema")
.withExposedPorts(3306)
.withClasspathResourceMapping("init.sql", "/docker-entrypoint-initdb.d/init.sql", BindMode.READ_ONLY)
.withReuse(true);
if (ssl) {
server.withClasspathResourceMapping("tls/conf", "/etc/mysql/conf.d", BindMode.READ_ONLY);
server.withClasspathResourceMapping("tls/files", "/etc/mysql/tls", BindMode.READ_ONLY);
} else {
server.withClasspathResourceMapping("tls/files", "/etc/mysql/tls", BindMode.READ_ONLY);
String cmd = "--max_allowed_packet=33554432 --max_prepared_stmt_count=16382 --local_infile=true --character-set-server=utf8mb4 --collation-server=utf8mb4_general_ci";
if (isUsingMySQL8()) {
// introduced in MySQL 8.0.3
cmd += " --caching-sha2-password-public-key-path=/etc/mysql/tls/public_key.pem --caching-sha2-password-private-key-path=/etc/mysql/tls/private_key.pem";
}
server.withCommand(cmd);
}
}
@Test
public void simpleRecursiveFileWithPermissionTest() {
GenericContainer container = new GenericContainer(
new ImageFromDockerfile()
.withDockerfileFromBuilder(builder ->
builder.from("alpine:3.3")
.copy("/tmp/foo", "/foo")
.cmd("ls", "-al", "/")
.build()
).withFileFromFile("/tmp/foo", new File("/mappable-resource/test-resource.txt"),
0754))
.withStartupCheckStrategy(new OneShotStartupCheckStrategy());
container.start();
String listing = container.getLogs();
assertThat("Listing shows that file is copied with mode requested.",
Arrays.asList(listing.split("\\n")),
exactlyNItems(1, allOf(containsString("-rwxr-xr--"), containsString("foo"))));
}
protected static Option[] configureDatabase() {
switch (getValidTestDatabase()) {
case POSTGRES:
postgresContainer = new GenericContainer(POSTGRES_IMAGE) //NOSONAR
.withExposedPorts(POSTGRES_PORT)
.withEnv("POSTGRES_USER", DB_USER)
.withEnv("POSTGRES_PASSWORD", DB_PASSWORD)
.withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger(NexusPaxExamSupport.class)))
.withClasspathResourceMapping("initialize-postgres.sql", "/docker-entrypoint-initdb.d/initialize-postgres.sql", READ_ONLY)
.waitingFor(Wait.forLogMessage(".*database system is ready to accept connections.*", 1));
return combine(null,
editConfigurationFilePut(NEXUS_PROPERTIES_FILE, "nexus.orient.enabled", "false"),
systemProperty(TEST_JDBC_URL_PROPERTY).value(configurePostgres())
);
case H2:
return combine(null,
editConfigurationFilePut(NEXUS_PROPERTIES_FILE, "nexus.orient.enabled", "false")
);
case ORIENT:
return new Option[0];
default:
throw new IllegalStateException("No case defined for " + getValidTestDatabase());
}
}
public PrometheusServer()
{
this.dockerContainer = new GenericContainer<>(PROMETHEUS_DOCKER_IMAGE)
.withExposedPorts(PROMETHEUS_PORT)
.waitingFor(Wait.forHttp("/"))
.withStartupTimeout(Duration.ofSeconds(120));
this.dockerContainer.start();
}
public RedisServer()
{
container = new GenericContainer<>("redis:2.8.9")
.withExposedPorts(PORT);
container.start();
jedisPool = new JedisPool(container.getContainerIpAddress(), container.getMappedPort(PORT));
}
private static void testServer(String baseImage, String rpmHostPath, String expectedJavaVersion)
{
String rpm = "/" + new File(rpmHostPath).getName();
String command = "" +
// install RPM
"yum localinstall -q -y " + rpm + "\n" +
// create Hive catalog file
"mkdir /etc/presto/catalog\n" +
"cat > /etc/presto/catalog/hive.properties <<\"EOT\"\n" +
"connector.name=hive-hadoop2\n" +
"hive.metastore.uri=thrift://localhost:9083\n" +
"EOT\n" +
// create JMX catalog file
"cat > /etc/presto/catalog/jmx.properties <<\"EOT\"\n" +
"connector.name=jmx\n" +
"EOT\n" +
// start server
"/etc/init.d/presto start\n" +
// allow tail to work with Docker's non-local file system
"tail ---disable-inotify -F /var/log/presto/server.log\n";
try (GenericContainer<?> container = new GenericContainer<>(baseImage)) {
container.withExposedPorts(8080)
// the RPM is hundreds MB and file system bind is much more efficient
.withFileSystemBind(rpmHostPath, rpm, BindMode.READ_ONLY)
.withCommand("sh", "-xeuc", command)
.waitingFor(forLogMessage(".*SERVER STARTED.*", 1).withStartupTimeout(Duration.ofMinutes(5)))
.start();
QueryRunner queryRunner = new QueryRunner(container.getContainerIpAddress(), container.getMappedPort(8080));
assertEquals(queryRunner.execute("SHOW CATALOGS"), ImmutableSet.of(asList("system"), asList("hive"), asList("jmx")));
// TODO remove usage of assertEventually once https://github.com/prestosql/presto/issues/2214 is fixed
assertEventually(
new io.airlift.units.Duration(1, MINUTES),
() -> assertEquals(queryRunner.execute("SELECT specversion FROM jmx.current.\"java.lang:type=runtime\""), ImmutableSet.of(asList(expectedJavaVersion))));
}
}
@Override
public ServicesControl startHbase() {
Network network = Network.newNetwork();
GenericContainer<?> hbase = this.getContainerHBase(
VersionedPipelines.defaultTags.hbase,
network,
"",
0,
true
);
hbase.start();
return new ServicesControl() {
@Override
public GenericContainer<?> getContainer() { return hbase; }
@Override
public void close() {
hbase.stop();
}
@Override
public int getPort() {
return hbase.getMappedPort(ContainersProvider.HBASE_ZK_PORT);
}
};
}
public synchronized void stop() {
List<GenericContainer> containers = new ArrayList<>();
containers.addAll(workerContainers.values());
containers.addAll(brokerContainers.values());
containers.addAll(bookieContainers.values());
if (externalServices != null) {
containers.addAll(externalServices.values());
}
if (null != proxyContainer) {
containers.add(proxyContainer);
}
if (null != csContainer) {
containers.add(csContainer);
}
if (null != zkContainer) {
containers.add(zkContainer);
}
if (null != prestoWorkerContainer) {
containers.add(prestoWorkerContainer);
}
containers = containers.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
containers.parallelStream().forEach(GenericContainer::stop);
try {
network.close();
} catch (Exception e) {
log.info("Failed to shutdown network for pulsar cluster {}", clusterName, e);
}
}
@Override
public Map<String, String> start() {
LOGGER.info(TestcontainersConfiguration.getInstance().toString());
try {
container = new GenericContainer(COUCHDB_IMAGE).withExposedPorts(COUCHDB_PORT).waitingFor(Wait.forListeningPort());
container.start();
final String authority = container.getContainerIpAddress() + ":" + container.getMappedPort(COUCHDB_PORT).toString();
return CollectionHelper.mapOf("camel.couchdb.test.server.authority", authority);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void shouldWorkWithSimpleDependency() {
InvocationCountingStartable startable = new InvocationCountingStartable();
try (
GenericContainer container = new GenericContainer()
.withStartupCheckStrategy(new OneShotStartupCheckStrategy())
.dependsOn(startable)
) {
container.start();
}
VisibleAssertions.assertEquals("Started once", 1, startable.getStartInvocationCount().intValue());
VisibleAssertions.assertEquals("Does not trigger .stop()", 0, startable.getStopInvocationCount().intValue());
}
@Test
public void shouldCreateFoldersStructureWithCopy() throws Exception {
String resource = "/test_copy_to_container.txt";
try (
GenericContainer container = new GenericContainer<>()
.withCommand("sleep", "3000")
.withClasspathResourceMapping(resource, "/a/b/c/file", BindMode.READ_ONLY)
) {
container.start();
String filesList = container.execInContainer("ls", "/a/b/c/").getStdout();
assertTrue("file list contains the file", filesList.contains("file"));
}
}
@Override
public Map<String, String> start() {
LOGGER.info(TestcontainersConfiguration.getInstance().toString());
try {
container = new GenericContainer<>(ACTIVEMQ_IMAGE)
.withExposedPorts(ACTIVEMQ_PORT)
.withLogConsumer(new Slf4jLogConsumer(LOGGER))
.withEnv("BROKER_CONFIG_MAX_DISK_USAGE", "100")
.waitingFor(Wait.forListeningPort());
container.start();
String brokerUrlTcp = String.format("tcp://127.0.0.1:%d", container.getMappedPort(ACTIVEMQ_PORT));
String brokerUrlWs = String.format("ws://127.0.0.1:%d", container.getMappedPort(ACTIVEMQ_PORT));
return CollectionHelper.mapOf(
"quarkus.artemis.url", brokerUrlTcp,
"quarkus.artemis.username", ACTIVEMQ_USERNAME,
"quarkus.artemis.password", ACTIVEMQ_PASSWORD,
"camel.component.paho.brokerUrl", brokerUrlTcp,
"camel.component.paho.username", ACTIVEMQ_USERNAME,
"camel.component.paho.password", ACTIVEMQ_PASSWORD,
"broker-url.ws", brokerUrlWs);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test @Ignore //TODO investigate intermittent failures
public void failFastWhenContainerHaltsImmediately() throws Exception {
long startingTimeMs = System.currentTimeMillis();
final GenericContainer failsImmediately = new GenericContainer("alpine:3.2")
.withCommand("/bin/sh", "-c", "return false")
.withMinimumRunningDuration(Duration.ofMillis(100));
try {
assertThrows(
"When we start a container that halts immediately, an exception is thrown",
RetryCountExceededException.class,
() -> {
failsImmediately.start();
return null;
});
// Check how long it took, to verify that we ARE bailing out early.
// Want to strike a balance here; too short and this test will fail intermittently
// on slow systems and/or due to GC variation, too long and we won't properly test
// what we're intending to test.
int allowedSecondsToFailure =
GenericContainer.CONTAINER_RUNNING_TIMEOUT_SEC / 2;
long completedTimeMs = System.currentTimeMillis();
assertTrue("container should not take long to start up",
completedTimeMs - startingTimeMs < 1000L * allowedSecondsToFailure);
} finally {
failsImmediately.stop();
}
}