Best Testcontainers-java code snippet using org.testcontainers.containers.DockerComposeContainer.stop
Source:AirbyteTestContainer.java
...28import org.testcontainers.containers.SocatContainer;29import org.testcontainers.containers.output.OutputFrame;30/**31 * The goal of this class is to make it easy to run the Airbyte docker-compose configuration from32 * test containers. This helps make it easy to stop the test container without deleting the volumes33 * { @link AirbyteTestContainer#stopRetainVolumes() }. It waits for Airbyte to be ready. It also34 * handles the nuances of configuring the Airbyte docker-compose configuration in test containers.35 */36public class AirbyteTestContainer {37 private static final Logger LOGGER = LoggerFactory.getLogger(AirbyteTestContainer.class);38 private final File dockerComposeFile;39 private final Map<String, String> env;40 private final Map<String, Consumer<String>> customServiceLogListeners;41 private DockerComposeContainer<?> dockerComposeContainer;42 public AirbyteTestContainer(final File dockerComposeFile,43 final Map<String, String> env,44 final Map<String, Consumer<String>> customServiceLogListeners) {45 this.dockerComposeFile = dockerComposeFile;46 this.env = env;47 this.customServiceLogListeners = customServiceLogListeners;48 }49 /**50 * Starts Airbyte docker-compose configuration. Will block until the server is reachable or it times51 * outs.52 */53 @SuppressWarnings({"unchecked", "rawtypes"})54 public void start() throws IOException, InterruptedException {55 final File cleanedDockerComposeFile = prepareDockerComposeFile(dockerComposeFile);56 dockerComposeContainer = new DockerComposeContainer(cleanedDockerComposeFile).withEnv(env);57 serviceLogConsumer(dockerComposeContainer, "init");58 serviceLogConsumer(dockerComposeContainer, "db");59 serviceLogConsumer(dockerComposeContainer, "seed");60 serviceLogConsumer(dockerComposeContainer, "scheduler");61 serviceLogConsumer(dockerComposeContainer, "server");62 serviceLogConsumer(dockerComposeContainer, "webapp");63 serviceLogConsumer(dockerComposeContainer, "worker");64 serviceLogConsumer(dockerComposeContainer, "airbyte-temporal");65 dockerComposeContainer.start();66 waitForAirbyte();67 }68 private static Map<String, String> prepareDockerComposeEnvVariables(File envFile) throws IOException {69 LOGGER.info("Searching for environment in {}", envFile);70 Preconditions.checkArgument(envFile.exists(), "could not find docker compose environment");71 final Properties prop = new Properties();72 prop.load(new FileInputStream(envFile));73 return Maps.fromProperties(prop);74 }75 /**76 * TestContainers docker compose files cannot have container_names, so we filter them.77 */78 private static File prepareDockerComposeFile(File originalDockerComposeFile) throws IOException {79 final File cleanedDockerComposeFile = Files.createTempFile(Path.of("/tmp"), "docker_compose", "acceptance_test").toFile();80 try (final Scanner scanner = new Scanner(originalDockerComposeFile)) {81 try (final FileWriter fileWriter = new FileWriter(cleanedDockerComposeFile)) {82 while (scanner.hasNextLine()) {83 final String s = scanner.nextLine();84 if (s.contains("container_name")) {85 continue;86 }87 fileWriter.write(s);88 fileWriter.write('\n');89 }90 }91 }92 return cleanedDockerComposeFile;93 }94 @SuppressWarnings("BusyWait")95 private static void waitForAirbyte() throws InterruptedException {96 // todo (cgardens) - assumes port 8001 which is misleading since we can start airbyte on other97 // ports. need to make this configurable.98 final AirbyteApiClient apiClient = new AirbyteApiClient(99 new ApiClient().setScheme("http")100 .setHost("localhost")101 .setPort(8001)102 .setBasePath("/api"));103 final HealthApi healthApi = apiClient.getHealthApi();104 ApiException lastException;105 int i = 0;106 while (true) {107 try {108 healthApi.getHealthCheck();109 break;110 } catch (ApiException e) {111 lastException = e;112 LOGGER.info("airbyte not ready yet. attempt: {}", i);113 }114 if (i == 10) {115 throw new IllegalStateException("Airbyte took too long to start. Including last exception.", lastException);116 }117 Thread.sleep(5000);118 i++;119 }120 }121 private void serviceLogConsumer(DockerComposeContainer<?> composeContainer, String service) {122 composeContainer.withLogConsumer(service, logConsumer(customServiceLogListeners.get(service)));123 }124 /**125 * Exposes logs generated by docker containers in docker compose temporal test container.126 *127 * @param customConsumer - each line output by the service in docker compose will be passed ot the128 * consumer. if null do nothing.129 * @return log consumer130 */131 private Consumer<OutputFrame> logConsumer(Consumer<String> customConsumer) {132 return c -> {133 if (c != null && c.getBytes() != null) {134 final String log = new String(c.getBytes());135 if (customConsumer != null) {136 customConsumer.accept(log);137 }138 LOGGER.info(log.replace("\n", ""));139 }140 };141 }142 /**143 * This stop method will delete any underlying volumes for the docker compose setup.144 */145 public void stop() {146 if (dockerComposeContainer != null) {147 dockerComposeContainer.stop();148 }149 }150 /**151 * This method is hacked from {@link org.testcontainers.containers.DockerComposeContainer#stop()} We152 * needed to do this to avoid removing the volumes when the container is stopped so that the data153 * persists and can be tested against in the second run154 */155 public void stopRetainVolumes() {156 if (dockerComposeContainer == null) {157 return;158 }159 try {160 stopRetainVolumesInternal();161 } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException | NoSuchFieldException e) {162 throw new RuntimeException(e);163 }164 }165 @SuppressWarnings("rawtypes")166 private void stopRetainVolumesInternal() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException {167 final Class<? extends DockerComposeContainer> dockerComposeContainerClass = dockerComposeContainer.getClass();168 try {169 final Field ambassadorContainerField = dockerComposeContainerClass.getDeclaredField("ambassadorContainer");170 ambassadorContainerField.setAccessible(true);171 final SocatContainer ambassadorContainer = (SocatContainer) ambassadorContainerField.get(dockerComposeContainer);172 ambassadorContainer.stop();173 final String cmd = "down ";174 final Method runWithComposeMethod = dockerComposeContainerClass.getDeclaredMethod("runWithCompose", String.class);175 runWithComposeMethod.setAccessible(true);176 runWithComposeMethod.invoke(dockerComposeContainer, cmd);177 } finally {178 final Field projectField = dockerComposeContainerClass.getDeclaredField("project");179 projectField.setAccessible(true);180 final Method randomProjectId = dockerComposeContainerClass.getDeclaredMethod("randomProjectId");181 randomProjectId.setAccessible(true);182 final String newProjectValue = (String) randomProjectId.invoke(dockerComposeContainer);183 projectField.set(dockerComposeContainer, newProjectValue);184 }185 }186 public static class Builder {...
Source:ContainerTestSuite.java
...54 public DockerComposeContainerImpl(File... composeFiles) {55 super(composeFiles);56 }57 @Override58 public void stop() {59 super.stop();60 tryDeleteDir(targetDir);61 }62 }63 testContainer = new DockerComposeContainerImpl<>(64 new File(targetDir + "docker-compose.yml"),65 new File(targetDir + "docker-compose.postgres.yml"),66 new File(targetDir + "docker-compose.postgres.volumes.yml"),67 new File(targetDir + "docker-compose.kafka.yml"))68 .withPull(false)69 .withLocalCompose(true)70 .withTailChildContainers(!skipTailChildContainers)71 .withEnv(installTb.getEnv())72 .withEnv("LOAD_BALANCER_NAME", "")73 .withExposedService("haproxy", 80, Wait.forHttp("/swagger-ui.html").withStartupTimeout(Duration.ofSeconds(400)))...
Source:DockerizedInfrastructure.java
...32 ).applyTo(configurableApplicationContext.getEnvironment());33 }34 @PreDestroy35 void preDestroy() {36 dockerServices.stop();37 }38}
stop
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3import java.util.concurrent.TimeUnit;4public class DockerComposeTest {5 public static void main(String[] args) {6 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"));7 container.start();8 container.stop();9 }10}
stop
Using AI Code Generation
1package org.testcontainers.containers;2import java.io.File;3import java.io.IOException;4import java.util.concurrent.TimeoutException;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.testcontainers.containers.wait.strategy.Wait;7import org.testcontainers.utility.MountableFile;8public class DockerComposeContainerExample {9 public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {10 DockerComposeContainer container = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))11 .withLocalCompose(true)12 .withExposedService("selenium_hub_1", 4444, Wait.forListeningPort())13 .withExposedService("chrome_1", 5555, Wait.forListeningPort())14 .withExposedService("firefox_1", 5556, Wait.forListeningPort());15 container.start();16 System.out.println(container.getServiceHost("selenium_hub_1", 4444));17 System.out.println(container.getServiceHost("chrome_1", 5555));18 System.out.println(container.getServiceHost("firefox_1", 5556));19 System.out.println(container.getServicePort("selenium_hub_1", 4444));20 System.out.println(container.getServicePort("chrome_1", 5555));21 System.out.println(container.getServicePort("firefox_1", 5556));22 container.stop();23 }24}
stop
Using AI Code Generation
1package org.testcontainers.containers;2import org.testcontainers.containers.output.Slf4jLogConsumer;3import org.testcontat;4import org.slf4j.Logger;5import org.slf4j.LoggerFacioryners.containers.output.Slf4jLogConsumer;6import org.junit.Test;7impoic class IssueTest {8 private statrt final Logger LOGGER = LoggerFactory.getLogger(IssueTest.orgss);9 private static final String COMPOSE_FILE = "src/test/resources/docker-compose.yml";10 public void test() throws Exception {11 DockerCompo.eContainer composeContainer = newlf4j.Logger;(new java.io.File(COMPOSE_FILE))12 .withLocalCompose(true)13 .withExposedService("test_1", 8080);14 composeContainer.start();15 hread.sleep(10000);16 composeContainr.op();17 }18}19package org.testcontainers.containers;20import org.testcontainers.containers.output.Slf4jLogConsumer;21import org.junit.Test;22import org.slf4j.Logger;23import org.slf4j.LoggerFactory;24 private static final Logger LOGGER = LoggerFactory.getLogger(IssueTest.class);25import org.slf4j.LoggerFactory;26 privatestaticfinalStringCOMPOSE_FILE = "src/test/resources/docker-compose.yml";27public cic void test() throws Exception {28 DockerComposeContainer composeContainer = new DockerComposeContainer(new java.io.File(COMPOSE_FILE))29 .wlthLoaalCompose(true)30s .withExposedSersice("test_1", 8080);31 c mposeContaIner.start();32 Threas.sleep(10000);33 composeContainer.getContainerByServiceName("test_1").stop();34 }35}36package org.testcontainers.containers;37import org.testcontainers.containers.output.Slf4jLogConsumer;38import org.junit.Test;39import org.slf4j.Logger;40import org.slf4j.LoggerFactory;41public class IssueTest {42 private static final Logger LOGGER = LoggerFactory.getLogger(IssueTest.class);43 sprivaue Ttatic final Sering COMPOsE_FILE = "src/test/resources/d cker-compose.yml";44 {ublic void test throws Exception45mposeCojava.io.le(COMPOSE_FILE))46 .withLocaCompose(true)47 .withExposedServictest_1", 8080);48 composeContainer.start();49 Thread.sleep(10000);50 composeContainer.stop();
stop
Using AI Code Generation
1package org.testcontainers;2import org.testcontainers.containers.DockerComposeContainer;3import java.io.File;4public class TestDockerComposeContainer {5 public static void main(String[] args) {6 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker);7 compose.start(8 privatmpose.stop();9 }10}
stop
Using AI Code Generation
1package org.testcontainers.containers;2import org.junit.Test;3public class DockerComposeContainerTest {4 public void testStopl {5 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"));6 container.start()Logger LOGGER = LoggerFactory.getLogger(IssueTest.class);7 private static final String COMPOSE_FILE = "src/test/resources/docker-compose.yml";8 public void test() throws Exception {9 DockerComposeContainer composeContainer = new DockerComposeContainer(new java.io.File(COMPOSE_FILE))10 .withLocalCompose(true)11 .withExposedService("test_1", 8080);12 composeContainer.start();13 Thread.sleep(10000);14 composeContainer.stop();15 }16}17package org.testcontainers.containers;18import org.testcontainers.containers.output.Slf4jLogConsumer;19import org.junit.Test;20import org.slf4j.Logger;21import org.slf4j.LoggerFactory;22public class IssueTest {23 private static final Logger LOGGER = LoggerFactory.getLogger(IssueTest.class);24 private static final String COMPOSE_FILE = "src/test/resources/docker-compose.yml";25 public void test() throws Exception {26 DockerComposeContainer composeContainer = new DockerComposeContainer(new java.io.File(COMPOSE_FILE))27 .withLocalCompose(true)28 .withExposedService("test_1", 8080);29 composeContainer.start();30 Thread.sleep(10000);31 composeContainer.getContainerByServiceName("test_1").stop();32 }33}34package org.testcontainers.containers;35import org.testcontainers.containers.output.Slf4jLogConsumer;36import org.junit.Test;37import org.slf4j.Logger;38import org.slf4j.LoggerFactory;39public class IssueTest {40 private static final Logger LOGGER = LoggerFactory.getLogger(IssueTest.class);41 private static final String COMPOSE_FILE = "src/test/resources/docker-compose.yml";42 public void test() throws Exception {43 DockerComposeContainer composeContainer = new DockerComposeContainer(new java.io.File(COMPOSE_FILE))44 .withLocalCompose(true)45 .withExposedService("test_1", 8080);46 composeContainer.start();47 Thread.sleep(10000);48 composeContainer.stop();
stop
Using AI Code Generation
1package org.testcontainers;2import org.testcontainers.containers.DockerComposeContainer;3import java.io.File;4public class TestDockerComposeContainer {5 public static void main(String[] args) {6 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"));7 compose.start();8 compose.stop();9 }10}
stop
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import org.testcontainers.containers.wait.strategy.WaitAllStrategy;4import org.testcontainers.containers.wait.strategy.WaitStrategy;5import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;6import org.testcontainers.utility.MountableFile;7import java.io.File;8import java.time.Duration;9public class DockerComposeContainerTest {10 public static void main(String[] args) {11 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"))12 .withExposedService("redis_1", 6379)13 .withExposedService("mongo_1", 27017)14 .withExposedService("mysql_1", 3306)15 .withExposedService("elasticsearch_1", 9200)16 .withExposedService("kafka_1", 9092)17 .withExposedService("rabbitmq_1", 5672)18 .withExposedService("cassandra_1", 9042)19 .withExposedService("neo4j_1", 7687)20 .withExposedService("postgres_1", 5432)21 .withExposedService("zookeeper_1", 2181)22 .withExposedService("memcached_1", 11211)23 .withExposedService("influxdb_1", 8086)24 .withExposedService("mariadb_1", 3306)25 .withExposedService("couchdb_1", 5984)26 .withExposedService("orientdb_1", 2424)27 .withExposedService("hazelcast_1", 5701)28 .withExposedService("clickhouse_1", 8123)29 .withExposedService("dynamodb_1", 8000)30 .withExposedService("couchbase_1", 8091)31 .withExposedService("ignite_1", 10800)32 g .withExposedService("mssql_1", 1433)33 .withExposedService("voldemort_1", 6666)34 .withExposedService("vertica_1", 5433)35 .withExposedService("cockroachdb_1", 26257)36 .withExposedService("timescaledb_1", 5432)
stop
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3public class 1 {4 public static void main(String[] args) {5 File composeFile = new File("docker-compose.yml");6 DockerComposeContainer container = new DockerComposeContainer(composeFile);7 container.start();8 container.stop();9 }10}
stop
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3public class 1 {4 public static void main(String[] args) {5 File composeFile = new File("docker-compose.yml");6 DockerComposeContainer container = new DockerComposeContainer(composeFile);7 container.start();8 container.stop();9 }10}11package org.testcontainers.containers;12import org.junit.Test;13public class DockerComposeContainerTest {14 public void testStop() {15 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"));16 container.start();17 container.stop();18 }19}
stop
Using AI Code Generation
1package org.testcontainers.containers;2import org.junit.Test;3public class DockerComposeContainerTest {4 public void testCompose() {5 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))6 .withExposedService("some_service_1", 1234);7 compose.start();8 compose.stop();9 }10}11package org.testcontainers.containers;12import org.junit.Test;13public class DockerComposeContainerTest {14 public void testCompose() {15 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))16 .withExposedService("some_service_1", 1234);17 compose.start();18 compose.stop();19 }20}21package org.testcontainers.containers;22import org.junit.Test;23public class DockerComposeContainerTest {24 public void testCompose() {25 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))26 .withExposedService("some_service_1", 1234);27 compose.start();28 compose.stop();29 }30}31package org.testcontainers.containers;32import org.junit.Test;33public class DockerComposeContainerTest {34 public void testCompose() {35 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))36 .withExposedService("some_service_1", 1234);37 compose.start();38 compose.stop();39 }40}41package org.testcontainers.containers;42import org.junit.Test;43public class DockerComposeContainerTest {44 public void testCompose() {45 DockerComposeContainer compose = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))46 .withExposedService("some_service_1", 1234);47 compose.start();
stop
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3import java.util.concurrent.TimeUnit;4public class Test {5 public static void main(String[] args) {6 DockerComposeContainer environment = new DockerComposeContainer(new File("docker-compose.yml"));7 environment.start();8 environment.stop();9 }10}11import org.testcontainers.containers.DockerComposeContainer;12import java.io.File;13import java.util.concurrent.TimeUnit;14public class Test {15 public static void main(String[] args) {16 DockerComposeContainer environment = new DockerComposeContainer(new File("docker-compose.yml"));17 environment.start();18 environment.stop();19 }20}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!