Best Testcontainers-java code snippet using org.testcontainers.containers.DockerComposeContainer.registerContainersForShutdown
Source:DockerComposeContainer.java
...102 final Profiler profiler = new Profiler("Docker Compose container rule");103 profiler.setLogger(logger());104 profiler.start("Docker Compose container startup");105 synchronized (MUTEX) {106 registerContainersForShutdown();107 if (pull) {108 pullImages();109 }110 applyScaling(); // scale before up, so that all scaled instances are available first for linking111 createServices();112 startAmbassadorContainers(profiler);113 waitUntilServiceStarted();114 }115 }116 private void pullImages() {117 runWithCompose("pull");118 }119 private void createServices() {120 // Run the docker-compose container, which starts up the services121 runWithCompose("up -d");122 }123 private void waitUntilServiceStarted() {124 listChildContainers().forEach(this::createServiceInstance);125 serviceInstanceMap.forEach(this::waitUntilServiceStarted);126 }127 private void createServiceInstance(Container container) {128 String serviceName = getServiceNameFromContainer(container);129 final ComposeServiceWaitStrategyTarget containerInstance = new ComposeServiceWaitStrategyTarget(container,130 ambassadorContainer, ambassadorPortMappings.getOrDefault(serviceName, new HashMap<>()));131 String containerId = containerInstance.getContainerId();132 if (tailChildContainers) {133 followLogs(containerId, new Slf4jLogConsumer(logger()).withPrefix(container.getNames()[0]));134 }135 //follow logs using registered consumers for this service136 logConsumers.getOrDefault(serviceName, Collections.emptyList()).forEach(consumer -> followLogs(containerId, consumer));137 serviceInstanceMap.putIfAbsent(serviceName, containerInstance);138 }139 private void waitUntilServiceStarted(String serviceName, ComposeServiceWaitStrategyTarget serviceInstance) {140 final WaitAllStrategy waitAllStrategy = waitStrategyMap.get(serviceName);141 if(waitAllStrategy != null) {142 waitAllStrategy.waitUntilReady(serviceInstance);143 }144 }145 private String getServiceNameFromContainer(Container container) {146 final String containerName = container.getLabels().get("com.docker.compose.service");147 final String containerNumber = container.getLabels().get("com.docker.compose.container-number");148 return String.format("%s_%s", containerName, containerNumber);149 }150 private void runWithCompose(String cmd) {151 final DockerCompose dockerCompose;152 if (localCompose) {153 dockerCompose = new LocalDockerCompose(composeFiles, project);154 } else {155 dockerCompose = new ContainerisedDockerCompose(composeFiles, project);156 }157 dockerCompose158 .withCommand(cmd)159 .withEnv(env)160 .invoke();161 }162 private void applyScaling() {163 // Apply scaling164 if (!scalingPreferences.isEmpty()) {165 StringBuilder sb = new StringBuilder("scale");166 for (Map.Entry<String, Integer> scale : scalingPreferences.entrySet()) {167 sb.append(" ").append(scale.getKey()).append("=").append(scale.getValue());168 }169 runWithCompose(sb.toString());170 }171 }172 private void registerContainersForShutdown() {173 ResourceReaper.instance().registerFilterForCleanup(Arrays.asList(174 new SimpleEntry<>("label", "com.docker.compose.project=" + project)175 ));176 }177 private List<Container> listChildContainers() {178 return dockerClient.listContainersCmd()179 .withShowAll(true)180 .exec().stream()181 .filter(container -> Arrays.stream(container.getNames()).anyMatch(name ->182 name.startsWith("/" + project)))183 .collect(toList());184 }185 private void startAmbassadorContainers(Profiler profiler) {186 profiler.start("Ambassador container startup");...
registerContainersForShutdown
Using AI Code Generation
1package com.example;2import org.testcontainers.containers.DockerComposeContainer;3import org.testcontainers.containers.wait.strategy.Wait;4import java.io.File;5public class DockerComposeTest {6 public static void main(String[] args) {7 DockerComposeContainer container = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))8 .withExposedService("redis_1", 6379, Wait.forListeningPort())9 .withExposedService("redis_2", 6379, Wait.forListeningPort())10 .withExposedService("redis_3", 6379, Wait.forListeningPort());11 container.start();12 Runtime.getRuntime().addShutdownHook(new Thread(container::stop));13 }14}15package com.example;16import org.testcontainers.containers.DockerComposeContainer;17import org.testcontainers.containers.wait.strategy.Wait;18import java.io.File;19public class DockerComposeTest {20 public static void main(String[] args) {21 DockerComposeContainer container = new DockerComposeContainer(new File("src/test/resources/docker-compose.yml"))22 .withExposedService("redis_1", 6379, Wait.forListeningPort())23 .withExposedService("redis_2", 6379, Wait.forListeningPort())24 .withExposedService("redis_3", 6379, Wait.forListeningPort())25 .withScaledService("redis_1", 2);26 container.start();27 Runtime.getRuntime().addShutdownHook(new Thread(container::stop));28 }29}
registerContainersForShutdown
Using AI Code Generation
1DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"))2 .withExposedService("redis_1", 6379)3 .withExposedService("db_1", 5432)4 .withExposedService("db_2", 5432);5container.start();6Integer redisPort = container.getServicePort("redis_1", 6379);7Integer db1Port = container.getServicePort("db_1", 5432);8Integer db2Port = container.getServicePort("db_2", 5432);9String redisHost = container.getServiceHost("redis_1", 6379);10String db1Host = container.getServiceHost("db_1", 5432);11String db2Host = container.getServiceHost("db_2", 5432);12String redisUrl = container.getServiceHost("redis_1", 6379) + ":" + container.getServicePort("redis_1", 6379);13String db1Url = container.getServiceHost("db_1", 5432) + ":" + container.getServicePort("db_1", 5432);14String db2Url = container.getServiceHost("db_2", 5432) + ":" + container.getServicePort("db_2", 5432);15String redisUrl = container.getServiceHost("redis_1", 6379) + ":" + container.getServicePort("redis_1", 6379);16String db1Url = container.getServiceHost("db_1", 5432) + ":" + container.getServicePort("db_1", 5432);17String db2Url = container.getServiceHost("db_2", 5432) + ":" + container.getServicePort("db_2", 5432);18container.stop();19container.start();20container.stop();21DockerComposeContainer container = new DockerComposeContainer(new File("docker-compose.yml"))22 .withExposedService("redis_1", 6379)23 .withExposedService("db_1", 5432)24 .withExposedService("db_2", 5432);25container.start();
registerContainersForShutdown
Using AI Code Generation
1package org.testcontainers.containers;2import org.testcontainers.containers.output.OutputFrame;3import org.testcontainers.containers.output.ToStringConsumer;4import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy;5import org.testcontainers.containers.wait.strategy.Wait;6import org.testcontainers.utility.MountableFile;7import java.io.File;8import java.io.IOException;9import java.util.ArrayList;10import java.util.Arrays;11import java.util.HashMap;12import java.util.List;13import java.util.Map;14import java.util.concurrent.TimeUnit;15import java.util.stream.Collectors;16import static org.testcontainers.utility.MountableFile.forHostPath;17public class DockerComposeContainer<SELF extends DockerComposeContainer<SELF>> extends GenericContainer<SELF> {18 private static final String COMPOSE_PROJECT_NAME = "COMPOSE_PROJECT_NAME";19 private final Map<String, Integer> mappedPorts = new HashMap<>();20 private final Map<String, Integer> exposedPorts = new HashMap<>();21 private final Map<String, List<Integer>> waitingForServices = new HashMap<>();22 private final Map<String, String> env = new HashMap<>();23 private final Map<String, String> labels = new HashMap<>();24 private final Map<String, String> volumes = new HashMap<>();25 private final Map<String, String> links = new HashMap<>();26 private final Map<String, String> extraHosts = new HashMap<>();27 private String composeFile;28 private String identifier = "default";29 private boolean localCompose = false;30 private boolean pullOnStartup = true;31 public DockerComposeContainer(File composeFile) {32 this(composeFile.getAbsolutePath());33 localCompose = true;34 }35 public DockerComposeContainer(String composeFile) {36 super("dduportal/docker-compose:1.8.0");37 this.composeFile = composeFile;38 withCommand("up", "-d");39 waitingFor(new OneShot
registerContainersForShutdown
Using AI Code Generation
1public void testCreateTopic() {2 String topicName = "test";3 int numPartitions = 1;4 int replicationFactor = 1;5 Map<String, String> config = new HashMap<>();6 AdminClient adminClient = null;7 try {8 adminClient = AdminClient.create(getKafkaProperties());9 adminClient.createTopics(Collections.singleton(new NewTopic(topicName, numPartitions, (short) replicationFactor).configs(config))).all().get();10 } catch (InterruptedException | ExecutionException e) {11 e.printStackTrace();12 } finally {13 adminClient.close();14 }15}16private Properties getKafkaProperties() {17 Properties properties = new Properties();18 properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, kafka.getContainerIpAddress() + ":" + kafka.getMappedPort(9092));19 return properties;20}
registerContainersForShutdown
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.output.Slf4jLogConsumer3import org.testcontainers.containers.wait.strategy.Wait4import org.testcontainers.containers.wait.strategy.WaitAllStrategy5import org.testcontainers.lifecycle.Startables6import org.testcontainers.utility.DockerImageName7import org.testcontainers.utility.MountableFile8import org.testcontainers.containers.output.Slf4jLogConsumer9import org.testcontainers.containers.wait.strategy.Wait10import org.testcontainers.containers.wait.strategy.WaitAllStrategy11import org.testcontainers.lifecycle.Startables12import org.testcontainers.utility.DockerImageName13import org.testcontainers.utility.MountableFile14import org.junit.jupiter.api.AfterAll15import org.junit.jupiter.api.BeforeAll16import org.junit.jupiter.api.Test17import org.slf4j.LoggerFactory18import java.io.File19import java.time.Duration20class DockerComposeContainerTest {21 companion object {22 private val logger = LoggerFactory.getLogger(DockerComposeContainerTest::class.java)23 private val dockerComposeContainer = DockerComposeContainer(File("src/test/resources/docker-compose.yml"))24 .withExposedService("redis_1", 6379, Wait.forListeningPort())25 .withExposedService("postgres_1", 5432, Wait.forListeningPort())26 .withExposedService("mongo_1", 27017, Wait.forListeningPort())27 .withExposedService("rabbitmq_1", 5672, Wait.forListeningPort())28 .withExposedService("cassandra_1", 9042, Wait.forListeningPort())29 .withExposedService("kafka_1", 9092, Wait.forListeningPort())30 .withExposedService("zookeeper_1", 2181, Wait.forListeningPort())31 .withExposedService("neo4j_1", 7474, Wait.forListeningPort())32 .withExposedService("elasticsearch_
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!!