Best Testcontainers-java code snippet using org.testcontainers.containers.DockerComposeContainer
Source:ContainerTestSuite.java
...18import org.apache.commons.io.FileUtils;19import org.junit.ClassRule;20import org.junit.extensions.cpsuite.ClasspathSuite;21import org.junit.runner.RunWith;22import org.testcontainers.containers.DockerComposeContainer;23import org.testcontainers.containers.wait.strategy.Wait;24import java.io.File;25import java.io.IOException;26import java.nio.charset.StandardCharsets;27import java.time.Duration;28import java.util.UUID;29import static org.hamcrest.CoreMatchers.containsString;30import static org.hamcrest.CoreMatchers.is;31import static org.hamcrest.CoreMatchers.not;32import static org.hamcrest.MatcherAssert.assertThat;33import static org.junit.Assert.fail;34@RunWith(ClasspathSuite.class)35@ClasspathSuite.ClassnameFilters({"org.thingsboard.server.msa.*Test"})36@Slf4j37public class ContainerTestSuite {38 private static final String SOURCE_DIR = "./../../docker/";39 private static final String TB_CORE_LOG_REGEXP = ".*Starting polling for events.*";40 private static final String TRANSPORTS_LOG_REGEXP = ".*Going to recalculate partitions.*";41 private static DockerComposeContainer<?> testContainer;42 @ClassRule43 public static ThingsBoardDbInstaller installTb = new ThingsBoardDbInstaller();44 @ClassRule45 public static DockerComposeContainer getTestContainer() {46 if (testContainer == null) {47 boolean skipTailChildContainers = Boolean.valueOf(System.getProperty("blackBoxTests.skipTailChildContainers"));48 try {49 final String targetDir = FileUtils.getTempDirectoryPath() + "/" + "ContainerTestSuite-" + UUID.randomUUID() + "/";50 log.info("targetDir {}", targetDir);51 FileUtils.copyDirectory(new File(SOURCE_DIR), new File(targetDir));52 replaceInFile(targetDir + "docker-compose.yml", " container_name: \"${LOAD_BALANCER_NAME}\"", "", "container_name");53 class DockerComposeContainerImpl<SELF extends DockerComposeContainer<SELF>> extends DockerComposeContainer<SELF> {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)))74 .waitingFor("tb-core1", Wait.forLogMessage(TB_CORE_LOG_REGEXP, 1).withStartupTimeout(Duration.ofSeconds(400)))75 .waitingFor("tb-core2", Wait.forLogMessage(TB_CORE_LOG_REGEXP, 1).withStartupTimeout(Duration.ofSeconds(400)))76 .waitingFor("tb-http-transport1", Wait.forLogMessage(TRANSPORTS_LOG_REGEXP, 1).withStartupTimeout(Duration.ofSeconds(400)))77 .waitingFor("tb-http-transport2", Wait.forLogMessage(TRANSPORTS_LOG_REGEXP, 1).withStartupTimeout(Duration.ofSeconds(400)))78 .waitingFor("tb-mqtt-transport1", Wait.forLogMessage(TRANSPORTS_LOG_REGEXP, 1).withStartupTimeout(Duration.ofSeconds(400)))79 .waitingFor("tb-mqtt-transport2", Wait.forLogMessage(TRANSPORTS_LOG_REGEXP, 1).withStartupTimeout(Duration.ofSeconds(400)));80 } catch (Exception e) {81 log.error("Failed to create test container", e);82 fail("Failed to create test container");83 }84 }85 return testContainer;86 }87 private static void tryDeleteDir(String targetDir) {88 try {89 log.info("Trying to delete temp dir {}", targetDir);90 FileUtils.deleteDirectory(new File(targetDir));91 } catch (IOException e) {92 log.error("Can't delete temp directory " + targetDir, e);93 }94 }95 /**96 * This workaround is actual until issue will be resolved:97 * Support container_name in docker-compose file #2472 https://github.com/testcontainers/testcontainers-java/issues/247298 * docker-compose files which contain container_name are not supported and the creation of DockerComposeContainer fails due to IllegalStateException.99 * This has been introduced in #1151 as a quick fix for unintuitive feedback. https://github.com/testcontainers/testcontainers-java/issues/1151100 * Using the latest testcontainers and waiting for the fix...101 * */102 private static void replaceInFile(String sourceFilename, String target, String replacement, String verifyPhrase) {103 try {104 File file = new File(sourceFilename);105 String sourceContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);106 String outputContent = sourceContent.replace(target, replacement);107 assertThat(outputContent, (not(containsString(target))));108 assertThat(outputContent, (not(containsString(verifyPhrase))));109 FileUtils.writeStringToFile(file, outputContent, StandardCharsets.UTF_8);110 assertThat(FileUtils.readFileToString(file, StandardCharsets.UTF_8), is(outputContent));111 } catch (IOException e) {112 log.error("failed to update file " + sourceFilename, e);...
Source:DockerComposeTest.java
1package de.rieckpil.blog.testcontainers;2import org.junit.jupiter.api.Test;3import org.testcontainers.containers.DockerComposeContainer;4import org.testcontainers.containers.wait.strategy.Wait;5import org.testcontainers.junit.jupiter.Container;6import org.testcontainers.junit.jupiter.Testcontainers;7import java.io.File;8import java.time.Duration;9@Testcontainers10public class DockerComposeTest {11 @Container12 static DockerComposeContainer<?> environment =13 new DockerComposeContainer<>(new File("docker-compose.yml"))14 .withExposedService("database_1", 5432, Wait.forListeningPort())15 .withExposedService("keycloak_1", 8080,16 Wait.forHttp("/auth").forStatusCode(200)17 .withStartupTimeout(Duration.ofSeconds(30)));18 @Test19 void dockerComposeTest() {20 System.out.println(environment.getServicePort("database_1", 5432));21 System.out.println(environment.getServicePort("keycloak_1", 8080));22 }23}...
DockerComposeContainer
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 java.io.File;7import java.util.concurrent.TimeUnit;8public class DockerComposeTest {9 public static void main(String[] args) {10 DockerComposeContainer environment = new DockerComposeContainer(11 new File("docker-compose.yml"))12 .withExposedService("redis_1", 6379, Wait.forListeningPort())13 .withExposedService("redis_2", 6379, Wait.forListeningPort())14 .withExposedService("redis_3", 6379, Wait.forListeningPort())15 .withExposedService("redis_4", 6379, Wait.forListeningPort())16 .withExposedService("redis_5", 6379, Wait.forListeningPort())17 .withExposedService("redis_6", 6379, Wait.forListeningPort())18 .withExposedService("redis_7", 6379, Wait.forListeningPort())19 .withExposedService("redis_8", 6379, Wait.forListeningPort())20 .withExposedService("redis_9", 6379, Wait.forListeningPort())21 .withExposedService("redis_10", 6379, Wait.forListeningPort())22 .withExposedService("redis_11", 6379, Wait.forListeningPort())23 .withExposedService("redis_12", 6379, Wait.forListeningPort())24 .withExposedService("redis_13", 6379, Wait.forListeningPort())25 .withExposedService("redis_14", 6379, Wait.forListeningPort())26 .withExposedService("redis_15", 6379, Wait.forListeningPort())27 .withExposedService("redis_16", 6379, Wait.forListeningPort())28 .withExposedService("redis_17", 6379, Wait.forListeningPort())29 .withExposedService("redis_18", 6379, Wait.forListeningPort())30 .withExposedService("redis_19", 6379, Wait.forListeningPort())31 .withExposedService("redis_20", 6379, Wait.forListeningPort())32 .withExposedService("redis_21", 6379, Wait.for
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import java.io.File;4import java.util.concurrent.TimeUnit;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.slf4j.Logger;7import org.slf4j.LoggerFactory;8public class Test {9 private static final Logger logger = LoggerFactory.getLogger(Test.class);10 public static void main(String[] args) throws Exception {11 File composeFile = new File("docker-compose.yml");12 DockerComposeContainer compose = new DockerComposeContainer(composeFile)13 .withExposedService("redis_1", 6379, Wait.forListeningPort())14 .withExposedService("tomcat_1", 8080, Wait.forHttp("/").forStatusCode(200).withStartupTimeout(10, TimeUnit.SECONDS))15 .withExposedService("tomcat_2", 8080, Wait.forHttp("/").forStatusCode(200).withStartupTimeout(10, TimeUnit.SECONDS));16 compose.start();17 compose.followOutput(new Slf4jLogConsumer(logger));18 }19}20import org.testcontainers.containers.DockerComposeContainer;21import org.testcontainers.containers.wait.strategy.Wait;22import java.io.File;23import java.util.concurrent.TimeUnit;24import org.testcontainers.containers.output.Slf4jLogConsumer;25import org.slf4j.Logger;26import org.slf4j.LoggerFactory;27public class Test {28 private static final Logger logger = LoggerFactory.getLogger(Test.class);29 public static void main(String[] args) throws Exception {30 File composeFile = new File("docker-compose.yml");31 DockerComposeContainer compose = new DockerComposeContainer(composeFile)32 .withExposedService("redis_1", 6379, Wait.forListeningPort())33 .withExposedService("tomcat_1", 8080, Wait.forHttp("/").forStatusCode(200).withStartupTimeout(10, TimeUnit.SECONDS))34 .withExposedService("tomcat_2", 8080, Wait.forHttp("/").forStatusCode(200).withStartupTimeout(10, TimeUnit.SECONDS));35 compose.start();36 compose.followOutput(new Slf4jLogConsumer(logger));37 }38}39import org.testcontainers.containers.DockerComposeContainer;40import
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3import org.testcontainers.containers.output.Slf4jLogConsumer;4import org.slf4j.Logger;5import org.slf4j.LoggerFactory;6public class DockerComposeTest {7 private static final Logger logger = LoggerFactory.getLogger(DockerComposeTest.class);8 public static void main(String args[]) {9 DockerComposeContainer container = new DockerComposeContainer(10 new File("docker-compose.yml"))11 .withExposedService("mysql_1", 3306, Wait.forListeningPort())12 .withExposedService("redis_1", 6379, Wait.forListeningPort())13 .withLocalCompose(true);14 container.withLogConsumer("mysql_1", new Slf4jLogConsumer(logger));15 container.withLogConsumer("redis_1", new Slf4jLogConsumer(logger));16 container.start();17 container.stop();18 }19}
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import org.testcontainers.images.builder.ImageFromDockerfile;4import java.io.File;5import java.util.ArrayList;6import java.util.List;7public class Main {8 public static void main(String[] args) {9 String dockerComposePath = "C:\\Users\\user\\docker-compose.yml";10 String dockerFilePath = "C:\\Users\\user\\Dockerfile";11 String imageName = "my-app";12 String containerName = "my-app";13 String serviceName = "my-app";14 String dockerFilePathDirectory = "C:\\Users\\user";15 String dockerComposePathDirectory = "C:\\Users\\user";16 String networkName = "my-app";17 String serviceName2 = "my-app2";18 DockerComposeContainer container = new DockerComposeContainer(new File(dockerComposePath))19 .withLocalCompose(true)20 .withExposedService(serviceName, 8080, Wait.forHttp("/").forStatusCode(200))21 .withPull(false)22 .withDockerCompose(new File(dockerComposePath))23 .withDockerCompose(new File(dockerComposePath), dockerComposePathDirectory)24 .withDockerCompose(new File(dockerComposePath), dockerComposePathDirectory, networkName)25 .withDockerCompose(new File(dockerComposePath), dockerComposePathDirectory, networkName, serviceName2)26 .withDockerCompose(new File(dockerComposePath), dockerComposePathDirectory, serviceName2)27 .withDockerCompose(new File(dockerComposePath), serviceName2)28 .withDockerfile(new File(dockerFilePath))29 .withDockerfile(new File(dockerFilePath), dockerFilePathDirectory)30 .withDockerfile(new File(dockerFilePath), dockerFilePathDirectory, imageName)31 .withDockerfile(new File(dockerFilePath), dockerFilePathDirectory, imageName, containerName
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3public class DockerComposeContainerTest {4 public static void main(String[] args) {5 File file = new File("docker-compose.yml");6 DockerComposeContainer container = new DockerComposeContainer(file);7 container.start();8 }9}10import org.testcontainers.containers.GenericContainer;11public class GenericContainerTest {12 public static void main(String[] args) {13 GenericContainer container = new GenericContainer("alpine:3.3");14 container.withCommand("ping", "
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import org.testcontainers.utility.MountableFile;4import java.io.File;5public class DockerComposeContainerTest {6 public static void main(String[] args) {7 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"))8 .withExposedService("my-service_1", 8080, Wait.forHttp("/").forStatusCode(200));9 container.start();10 System.out.println(container.getServiceHost("my-service_1", 8080));11 System.out.println(container.getServicePort("my-service_1", 8080));12 container.stop();13 }14}
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3public class DockerComposeContainerDemo {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 }9}10import org.testcontainers.containers.DockerComposeContainer;11import java.io.File;12public class DockerComposeContainerDemo {13 public static void main(String[] args) {14 File composeFile = new File("docker-compose.yml");15 DockerComposeContainer container = new DockerComposeContainer(composeFile);16 container.start();17 System.out.println("Tomcat is running on port: " + container.getServicePort("web", 8080));18 }19}20import org.testcontainers.containers.DockerComposeContainer;21import java.io.File;22public class DockerComposeContainerDemo {23 public static void main(String[] args) {24 File composeFile = new File("docker-compose.yml");25 DockerComposeContainer container = new DockerComposeContainer(composeFile);26 container.start();27 System.out.println("Tomcat is running on port: " + container.getServicePort("web", 8080));28 System.out.println("Postgres is running on port: " + container
DockerComposeContainer
Using AI Code Generation
1package com.mycompany.app;2import org.junit.Test;3import org.testcontainers.containers.DockerComposeContainer;4import java.io.File;5{6 public void testApp()7 {8 File dockerComposeFile = new File("docker-compose.yml");9 DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(dockerComposeFile);10 dockerComposeContainer.start();11 }12}13package com.mycompany.app;14import org.junit.Test;15import org.testcontainers.containers.DockerComposeContainer;16import java.io.File;17{18 public void testApp()19 {20 File dockerComposeFile = new File("docker-compose.yml");21 DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(dockerComposeFile);22 dockerComposeContainer.start();23 }24}25package com.mycompany.app;26import org.junit.Test;27import org.testcontainers.containers.DockerComposeContainer;28import java.io.File;29{30 public void testApp()31 {32 File dockerComposeFile = new File("docker-compose.yml");33 DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(dockerComposeFile);34 dockerComposeContainer.start();35 }36}37package com.mycompany.app;38import org.junit.Test;39import org.testcontainers.containers.DockerComposeContainer;40import java.io.File;41{42 public void testApp()43 {44 File dockerComposeFile = new File("docker-compose.yml");45 DockerComposeContainer dockerComposeContainer = new DockerComposeContainer(dockerComposeFile);46 dockerComposeContainer.start();47 }48}49package com.mycompany.app;50import org.junit.Test;51import org.testcontainers.containers.DockerComposeContainer;52import java.io.File;53{54 public void testApp()55 {56 File dockerComposeFile = new File("docker-compose.yml");
DockerComposeContainer
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import java.io.File;3public class TestContainer {4 public static void main(String[] args) {5 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"))6 .withExposedService("web_1", 8080)7 .withExposedService("web_2", 8080)8 .withExposedService("web_3", 8080);9 container.start();10 System.out.println("Container started");11 }12}
DockerComposeContainer
Using AI Code Generation
1package com.testcontainers;2import org.testcontainers.containers.DockerComposeContainer;3import java.io.File;4import java.util.List;5import java.util.stream.Collectors;6import java.util.stream.Stream;7public class ComposeTest {8 public static void main(String[] args) {9 DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"));10 container.start();11 List<String> containerIds = container.getContainerIds();12 System.out.println("List of containers created by docker compose");13 System.out.println(containerIds);14 List<String> serviceNames = container.getServiceNames();15 System.out.println("List of service names created by docker compose");16 System.out.println(serviceNames);17 List<Integer> servicePorts = container.getServicePort("db", 5432);18 System.out.println("List of service ports created by docker compose");19 System.out.println(servicePorts);20 container.stop();21 }22}
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!!