Best Testcontainers-java code snippet using org.testcontainers.containers.DockerComposeContainer.ContainerisedDockerCompose
Source:DockerComposeContainer.java
...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");187 ambassadorContainer.start();188 profiler.stop().log();189 }190 private Logger logger() {191 return LoggerFactory.getLogger(DockerComposeContainer.class);192 }193 @Override194 @VisibleForTesting195 public void finished(Description description) {196 synchronized (MUTEX) {197 try {198 // shut down the ambassador container199 ambassadorContainer.stop();200 // Kill the services using docker-compose201 try {202 runWithCompose("down -v");203 // If we reach here then docker-compose down has cleared networks and containers;204 // we can unregister from ResourceReaper205 spawnedContainerIds.forEach(ResourceReaper.instance()::unregisterContainer);206 spawnedNetworkIds.forEach(ResourceReaper.instance()::unregisterNetwork);207 } catch (Exception e) {208 // docker-compose down failed; use ResourceReaper to ensure cleanup209 // kill the spawned service containers210 spawnedContainerIds.forEach(ResourceReaper.instance()::stopAndRemoveContainer);211 // remove the networks after removing the containers212 spawnedNetworkIds.forEach(ResourceReaper.instance()::removeNetworkById);213 }214 spawnedContainerIds.clear();215 spawnedNetworkIds.clear();216 } finally {217 project = randomProjectId();218 }219 }220 }221 public SELF withExposedService(String serviceName, int servicePort) {222 return withExposedService(serviceName, servicePort, Wait.defaultWaitStrategy());223 }224 public DockerComposeContainer withExposedService(String serviceName, int instance, int servicePort) {225 return withExposedService(serviceName + "_" + instance, servicePort);226 }227 public DockerComposeContainer withExposedService(String serviceName, int instance, int servicePort, WaitStrategy waitStrategy) {228 return withExposedService(serviceName + "_" + instance, servicePort, waitStrategy);229 }230 public SELF withExposedService(String serviceName, int servicePort, @NonNull WaitStrategy waitStrategy) {231 String serviceInstanceName = getServiceInstanceName(serviceName);232 /*233 * For every service/port pair that needs to be exposed, we register a target on an 'ambassador container'.234 *235 * The ambassador container's role is to link (within the Docker network) to one of the236 * compose services, and proxy TCP network I/O out to a port that the ambassador container237 * exposes.238 *239 * This avoids the need for the docker compose file to explicitly expose ports on all the240 * services.241 *242 * {@link GenericContainer} should ensure that the ambassador container is on the same network243 * as the rest of the compose environment.244 */245 // Ambassador container will be started together after docker compose has started246 int ambassadorPort = nextAmbassadorPort.getAndIncrement();247 ambassadorPortMappings.computeIfAbsent(serviceInstanceName, __ -> new ConcurrentHashMap<>()).put(servicePort, ambassadorPort);248 ambassadorContainer.withTarget(ambassadorPort, serviceInstanceName, servicePort);249 ambassadorContainer.addLink(new FutureContainer(this.project + "_" + serviceInstanceName), serviceInstanceName);250 addWaitStrategy(serviceInstanceName, waitStrategy);251 return self();252 }253 private String getServiceInstanceName(String serviceName) {254 String serviceInstanceName = serviceName;255 if (!serviceInstanceName.matches(".*_[0-9]+")) {256 serviceInstanceName += "_1"; // implicit first instance of this service257 }258 return serviceInstanceName;259 }260 /*261 * can have multiple wait strategies for a single container, e.g. if waiting on several ports262 * if no wait strategy is defined, the WaitAllStrategy will return immediately.263 * The WaitAllStrategy uses an long timeout, because timeouts should be handled by the inner strategies.264 */265 private void addWaitStrategy(String serviceInstanceName, @NonNull WaitStrategy waitStrategy) {266 final WaitAllStrategy waitAllStrategy = waitStrategyMap.computeIfAbsent(serviceInstanceName, __ ->267 (WaitAllStrategy) new WaitAllStrategy().withStartupTimeout(Duration.ofMinutes(30)));268 waitAllStrategy.withStrategy(waitStrategy);269 }270 /**271 Specify the {@link WaitStrategy} to use to determine if the container is ready.272 *273 * @see org.testcontainers.containers.wait.strategy.Wait#defaultWaitStrategy()274 * @param serviceName the name of the service to wait for275 * @param waitStrategy the WaitStrategy to use276 * @return this277 */278 public SELF waitingFor(String serviceName, @NonNull WaitStrategy waitStrategy) {279 String serviceInstanceName = getServiceInstanceName(serviceName);280 addWaitStrategy(serviceInstanceName, waitStrategy);281 return self();282 }283 /**284 * Get the host (e.g. IP address or hostname) that an exposed service can be found at, from the host machine285 * (i.e. should be the machine that's running this Java process).286 * <p>287 * The service must have been declared using DockerComposeContainer#withExposedService.288 *289 * @param serviceName the name of the service as set in the docker-compose.yml file.290 * @param servicePort the port exposed by the service container.291 * @return a host IP address or hostname that can be used for accessing the service container.292 */293 public String getServiceHost(String serviceName, Integer servicePort) {294 return ambassadorContainer.getContainerIpAddress();295 }296 /**297 * Get the port that an exposed service can be found at, from the host machine298 * (i.e. should be the machine that's running this Java process).299 * <p>300 * The service must have been declared using DockerComposeContainer#withExposedService.301 *302 * @param serviceName the name of the service as set in the docker-compose.yml file.303 * @param servicePort the port exposed by the service container.304 * @return a port that can be used for accessing the service container.305 */306 public Integer getServicePort(String serviceName, Integer servicePort) {307 return ambassadorContainer.getMappedPort(ambassadorPortMappings.get(getServiceInstanceName(serviceName)).get(servicePort));308 }309 public SELF withScaledService(String serviceBaseName, int numInstances) {310 scalingPreferences.put(serviceBaseName, numInstances);311 return self();312 }313 public SELF withEnv(String key, String value) {314 env.put(key, value);315 return self();316 }317 public SELF withEnv(Map<String, String> env) {318 env.forEach(this.env::put);319 return self();320 }321 /**322 * Use a local Docker Compose binary instead of a container.323 *324 * @return this instance, for chaining325 */326 public SELF withLocalCompose(boolean localCompose) {327 this.localCompose = localCompose;328 return self();329 }330 /**331 * Whether to pull images first.332 *333 * @return this instance, for chaining334 */335 public SELF withPull(boolean pull) {336 this.pull = pull;337 return self();338 }339 /**340 * Whether to tail child container logs.341 *342 * @return this instance, for chaining343 */344 public SELF withTailChildContainers(boolean tailChildContainers) {345 this.tailChildContainers = tailChildContainers;346 return self();347 }348 /**349 * Attach an output consumer at container startup, enabling stdout and stderr to be followed, waited on, etc.350 * <p>351 * More than one consumer may be registered.352 *353 * @param serviceName the name of the service as set in the docker-compose.yml file354 * @param consumer consumer that output frames should be sent to355 * @return this instance, for chaining356 */357 public SELF withLogConsumer(String serviceName, Consumer<OutputFrame> consumer) {358 String serviceInstanceName = getServiceInstanceName(serviceName);359 final List<Consumer<OutputFrame>> consumers = this.logConsumers.getOrDefault(serviceInstanceName, new ArrayList<>());360 consumers.add(consumer);361 this.logConsumers.putIfAbsent(serviceInstanceName, consumers);362 return self();363 }364 private void followLogs(String containerId, Consumer<OutputFrame> consumer) {365 LogUtils.followOutput(DockerClientFactory.instance().client(), containerId, consumer);366 }367 private SELF self() {368 return (SELF) this;369 }370 private String randomProjectId() {371 return identifier + Base58.randomString(6).toLowerCase();372 }373}374interface DockerCompose {375 String ENV_PROJECT_NAME = "COMPOSE_PROJECT_NAME";376 String ENV_COMPOSE_FILE = "COMPOSE_FILE";377 DockerCompose withCommand(String cmd);378 DockerCompose withEnv(Map<String, String> env);379 void invoke();380 default void validateFileList(List<File> composeFiles) {381 checkNotNull(composeFiles);382 checkArgument(!composeFiles.isEmpty(), "No docker compose file have been provided");383 }384}385/**386 * Use Docker Compose container.387 */388class ContainerisedDockerCompose extends GenericContainer<ContainerisedDockerCompose> implements DockerCompose {389 private static final String DOCKER_SOCKET_PATH = "/var/run/docker.sock";390 private static final String DOCKER_CONFIG_FILE = "/root/.docker/config.json";391 private static final String DOCKER_CONFIG_ENV = "DOCKER_CONFIG_FILE";392 private static final String DOCKER_CONFIG_PROPERTY = "dockerConfigFile";393 public static final char UNIX_PATH_SEPERATOR = ':';394 public ContainerisedDockerCompose(List<File> composeFiles, String identifier) {395 super(TestcontainersConfiguration.getInstance().getDockerComposeContainerImage());396 validateFileList(composeFiles);397 addEnv(ENV_PROJECT_NAME, identifier);398 // Map the docker compose file into the container399 final File dockerComposeBaseFile = composeFiles.get(0);400 final String pwd = dockerComposeBaseFile.getAbsoluteFile().getParentFile().getAbsolutePath();401 final String containerPwd = MountableFile.forHostPath(pwd).getFilesystemPath();402 final List<String> absoluteDockerComposeFiles = composeFiles.stream()403 .map(File::getAbsolutePath)404 .map(MountableFile::forHostPath)405 .map(MountableFile::getFilesystemPath)406 .collect(toList());407 final String composeFileEnvVariableValue = Joiner.on(UNIX_PATH_SEPERATOR).join(absoluteDockerComposeFiles); // we always need the UNIX path separator408 logger().debug("Set env COMPOSE_FILE={}", composeFileEnvVariableValue);...
ContainerisedDockerCompose
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer2import org.testcontainers.containers.wait.strategy.Wait3import org.testcontainers.containers.wait.strategy.WaitAllStrategy4import org.testcontainers.containers.wait.strategy.WaitStrategy5import org.testcontainers.containers.wait.strategy.WaitStrategyTarget6class ContainerisedDockerCompose extends DockerComposeContainer {7 ContainerisedDockerCompose(File composeFile) {8 super(composeFile)9 this.withLocalCompose(true)10 this.withExposedService("selenium-hub", 4444, Wait.forHttp("/wd/hub/status").forStatusCode(200))11 this.withExposedService("selenium-node-chrome", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))12 this.withExposedService("selenium-node-firefox", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))13 this.withExposedService("selenium-node-ie", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))14 this.withExposedService("selenium-node-edge", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))15 this.withExposedService("selenium-node-safari", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))16 this.withExposedService("selenium-node-opera", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))17 this.withExposedService("selenium-node-htmlunit", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))18 this.withExposedService("selenium-node-phantomjs", 5555, Wait.forHttp("/wd/hub/status").forStatusCode(200))19 }20}21import org.testcontainers.containers.BrowserWebDriverContainer22import org.testcontainers.containers.DockerComposeContainer23import org.testcontainers.containers.VncRecordingContainer24import org.testcontainers.containers.wait.strategy.Wait25import org.testcontainers.containers.wait.strategy.WaitAllStrategy26import org.testcontainers.containers.wait.strategy.WaitStrategy27import org.testcontainers.containers.wait.strategy.WaitStrategyTarget28import org.testcontainers.utility.DockerImageName29import java.io.File30import static org.testcontainers.containers.BrowserWebDriverContainer.VncRecordingMode.RECORD_ALL31class DockerComposeContainerised extends Specification {
ContainerisedDockerCompose
Using AI Code Generation
1public class DockerComposeContainerTest {2 private static final String COMPOSE_FILE = "docker-compose.yml";3 private static final String COMPOSE_FILE_PATH = "src/test/resources/docker-compose.yml";4 private static final String LOGS_DIR = "logs";5 private static final String SELENIUM_HUB = "selenium-hub";6 private static final String SELENIUM_CHROME = "chrome";7 private static final String SELENIUM_FIREFOX = "firefox";8 private static final String SELENIUM_CHROME_PORT = "4444";9 private static final String SELENIUM_FIREFOX_PORT = "5555";10 private static final String SELENIUM_HUB_PORT = "4444";11 public DockerComposeContainer container = new DockerComposeContainer(new File(COMPOSE_FILE_PATH))12 .withLocalCompose(true)13 .withExposedService(SELENIUM_HUB, Integer.valueOf(SELENIUM_HUB_PORT))14 .withExposedService(SELENIUM_CHROME, Integer.valueOf(SELENIUM_CHROME_PORT))15 .withExposedService(SELENIUM_FIREFOX, Integer.valueOf(SELENIUM_FIREFOX_PORT))16 .withTailChildContainers(true)17 .withLogConsumer(SELENIUM_HUB, new Slf4jLogConsumer(LoggerFactory.getLogger("selenium-hub")))18 .withLogConsumer(SELENIUM_CHROME, new Slf4jLogConsumer(LoggerFactory.getLogger("selenium-chrome")))19 .withLogConsumer(SELENIUM_FIREFOX, new Slf4jLogConsumer(LoggerFactory.getLogger("selenium-firefox")))20 .withScaledService(SELENIUM_CHROME, 2)21 .withScaledService(SELENIUM_FIREFOX, 2)22 .withPull(false);23 public void test() {24 System.out.println("Selenium Hub URL: " + SELENIUM_HUB_URL);25 }26}
ContainerisedDockerCompose
Using AI Code Generation
1import org.junit.jupiter.api.Test2import org.testcontainers.containers.DockerComposeContainer3import org.testcontainers.junit.jupiter.Container4import org.testcontainers.junit.jupiter.Testcontainers5import java.io.File6class DockerComposeTest {7 companion object {8 val container = ContainerisedDockerCompose(File("docker-compose.yml"))9 }10 fun test() {11 println("Container is up and running")12 }13}14class ContainerisedDockerCompose(file: File) : DockerComposeContainer<ContainerisedDockerCompose>(file) {15 init {16 withExposedService("redis_1", 6379)17 }18}19val container = ContainerisedDockerCompose(File("docker-compose.yml"))20val container = ContainerisedDockerCompose(File("docker-compose.yml"))21val container = ContainerisedDockerCompose(File("docker-compose.yml"))
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!!