Best Testcontainers-java code snippet using org.testcontainers.containers.wait.strategy.Wait
Source:TestContainersConfig.java
1package com.rbkmoney.easyway.config;2import com.rbkmoney.easyway.TestContainers;3import com.rbkmoney.easyway.healthcheck.NetworkModeHostWaitStrategy;4import org.rnorth.visibleassertions.VisibleAssertions;5import org.testcontainers.containers.GenericContainer;6import org.testcontainers.containers.wait.strategy.HttpWaitStrategy;7import org.testcontainers.containers.wait.strategy.WaitStrategy;8import java.time.Duration;9public class TestContainersConfig {10 public static void configureAndInit(TestContainers testContainers) {11 if (!testContainers.isLocalDockerContainersEnabled()) {12 testContainers.getPostgresqlTestContainer().ifPresent(13 container -> {14 container15 .withNetworkAliases("postgresql")16 .withExposedPorts(5432)17 .withStartupTimeout(Duration.ofMinutes(1));18 startContainer("postgresql", container);19 }20 );21 testContainers.getCephTestContainer().ifPresent(22 container -> {23 container24 .withNetworkAliases("ceph")25 .withExposedPorts(5000, 8080)26 .withEnv("RGW_NAME", testContainers.getParameters().getCephRgwName())27 .withEnv("NETWORK_AUTO_DETECT", testContainers.getParameters().getCephNetworkAutoDetect())28 .withEnv("CEPH_DAEMON", testContainers.getParameters().getCephDaemon())29 .withEnv("CEPH_DEMO_UID", testContainers.getParameters().getCephDemoUid())30 .withEnv("CEPH_DEMO_ACCESS_KEY", testContainers.getParameters().getCephAccessKey())31 .withEnv("CEPH_DEMO_SECRET_KEY", testContainers.getParameters().getCephSecretKey())32 .withEnv("CEPH_DEMO_BUCKET", testContainers.getParameters().getCephBucketName())33 .waitingFor(getWaitStrategy("/api/v0.1/health", 200, 5000, Duration.ofMinutes(1)));34 startContainer("ceph", container);35 }36 );37 testContainers.getFileStorageTestContainer().ifPresent(38 container -> {39 container40 .withNetworkAliases("file-storage")41 // ÑÑо не ÑÑабоÑÐ°ÐµÑ Ð¿Ñи ÑеÑÑаÑ
на mac os. но ÑÑÐ¾Ñ ÐºÐ¾Ð½ÑÐµÐ¹Ð½ÐµÑ Ð½Ñжен ÑолÑко пÑи инÑегÑаÑионнÑÑ
ÑеÑÑаÑ
Ñ ÑайловÑм Ñ
ÑанилиÑем42 .withNetworkMode("host")43 .withEnv("storage.endpoint", "localhost:" + testContainers.getCephTestContainer().get().getMappedPort(8080))44 .withEnv("storage.signingRegion", testContainers.getParameters().getCephSigningRegion())45 .withEnv("storage.accessKey", testContainers.getParameters().getCephAccessKey())46 .withEnv("storage.secretKey", testContainers.getParameters().getCephSecretKey())47 .withEnv("storage.clientProtocol", testContainers.getParameters().getCephProtocol())48 .withEnv("storage.client.maxErrorRetry", testContainers.getParameters().getCephMaxErrorRetry())49 .withEnv("storage.bucketName", testContainers.getParameters().getCephBucketName())50 .withEnv("server.port", String.valueOf(testContainers.getParameters().getFileStoragePort()))51 .waitingFor(getNetworkModeHostWaitStrategy("/actuator/health", 200, testContainers.getParameters().getFileStoragePort(), Duration.ofMinutes(1)));52 startContainer("file-storage", container);53 }54 );55 testContainers.getKafkaTestContainer().ifPresent(56 container -> {57 container58 .withEmbeddedZookeeper()59 .withNetworkAliases("kafka")60 .withExposedPorts(9093)61 .withStartupTimeout(Duration.ofMinutes(1));62 startContainer("kafka", container);63 }64 );65 } else {66 // docker-compose -f docker-compose-dev.yml up -d67 }68 }69 private static WaitStrategy getWaitStrategy(String path, Integer statusCode, Integer port, Duration duration) {70 return new HttpWaitStrategy()71 .forPath(path)72 .forPort(port)73 .forStatusCode(statusCode)74 .withStartupTimeout(duration);75 }76 private static WaitStrategy getNetworkModeHostWaitStrategy(String path, Integer statusCode, Integer port, Duration duration) {77 return new NetworkModeHostWaitStrategy()78 .withPath(path)79 .withPort(port)80 .withStatusCode(statusCode)81 .withTimeout(duration);82 }83 private static void startContainer(String name, GenericContainer container) {84 VisibleAssertions.pass("STARTING TESTCONTAINER: [" + name + "] ...");85 container.start();86 VisibleAssertions.pass("TESTCONTAINER: [" + name + "] SUCCESSFULLY STARTED");87 VisibleAssertions.pass(container.toString());88 }89}...
Source:Wait.java
...21import com.github.dockerjava.api.DockerClient;22import org.testcontainers.DockerClientFactory;23import org.testcontainers.containers.ContainerLaunchException;24import org.testcontainers.containers.output.OutputFrame;25import org.testcontainers.containers.output.WaitingConsumer;26import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy;27import org.testcontainers.containers.wait.strategy.WaitStrategy;28import org.testcontainers.utility.LogUtils;29public class Wait extends org.testcontainers.containers.wait.strategy.Wait {30 /**31 * Convenience method to return a WaitStrategy for log messages using a predicate.32 *33 * @param predicate the predicate to apply to log messages34 * @param times the number of times the pattern is expected35 * @return WaitStrategy36 */37 public static WaitStrategy forLogPredicate(Predicate<OutputFrame> predicate, int times) {38 return new AbstractWaitStrategy() {39 @Override40 protected void waitUntilReady() {41 final DockerClient client = DockerClientFactory.instance().client();42 final WaitingConsumer waitingConsumer = new WaitingConsumer();43 LogUtils.followOutput(client, waitStrategyTarget.getContainerId(), waitingConsumer);44 try {45 waitingConsumer.waitUntil(46 predicate,47 startupTimeout.getSeconds(),48 TimeUnit.SECONDS,49 times50 );51 } catch (TimeoutException e) {52 throw new ContainerLaunchException("Timed out");53 }54 }55 };56 }57 /**58 * Convenience method to return a WaitStrategy for log messages.59 *60 * @param text the text to find61 * @param times the number of times the pattern is expected62 * @return WaitStrategy63 */64 public static WaitStrategy forLogMessageContaining(String text, int times) {65 return forLogPredicate(u -> u.getUtf8String().contains(text), times);66 }67}...
Wait
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import org.testcontainers.utility.MountableFile;4import java.io.File;5import java.io.IOException;6import java.io.InputStream;7import java.nio.file.Files;8import java.nio.file.Path;9import java.nio.file.Paths;10import java.util.concurrent.TimeUnit;11import java.util.stream.Collectors;12import java.util.stream.Stream;13import org.apache.commons.io.FileUtils;14import org.apache.commons.io.IOUtils;15import org.junit.Test;16import org.junit.runner.RunWith;17import org.springframework.beans.factory.annotation.Autowired;18import org.springframework.boot.test.context.SpringBootTest;19import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;20import org.springframework.core.io.ClassPathResource;21import org.springframework.core.io.Resource;22import org.springframework.test.context.junit4.SpringRunner;23import org.springframework.web.client.RestTemplate;24import com.fasterxml.jackson.databind.ObjectMapper;25import com.fasterxml.jackson.databind.node.ObjectNode;26import com.github.dockerjava.api.DockerClient;27import com.github.dockerjava.api.command.InspectContainerResponse;28import com.github.dockerjava.api.model.Container;29import com.github.dockerjava.api.model.ExposedPort;30import com.github.dockerjava.api.model.Frame;31import com.github.dockerjava.api.model.HostConfig;32import com.github.dockerjava.api.model.PortBinding;33import com.github.dockerjava.api.model.Ports;34import com.github.dockerjava.api.model.Ports.Binding;35import com.github.dockerjava.api.model.Volume;36import com.github.dockerjava.core.DockerClientBuilder;37import com.github.dockerjava.core.command.LogContainerResultCallback;38import com.github.dockerjava.core.command.WaitContainerResultCallback;39import com.github.dockerjava.core.command.WaitContainerResultCallback.WaitResult;40import com.github.dockerjava.core.command.WaitContainerResultCallback.WaitResultCallback;41import com.github.dockerjava.core.command.WaitContainerResultCallback.WaitResultValue;42import com.github.dockerjava.core.command.WaitContainerResultCallback.WaitResultValueCallback;43import com.github.dockerjava.core.command.WaitContainerResultCallback.WaitResultValueCallbackImpl;44import com.github.dockerjava.core.command.WaitContainerResultCallback.WaitResultValueImpl;45import com.github.dockerjava.core.command.WaitContainerResultCallbackImpl;46import com.github.dockerjava.core.command.WaitContainerResultCallbackImpl.WaitResultImpl;47import com.github.dockerjava.core.command.WaitContainerResultCallbackImpl.WaitResultValueCallbackImpl;48import lombok.extern.slf4j.Slf4j;49@RunWith(SpringRunner.class)50@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
Wait
Using AI Code Generation
1import org.testcontainers.containers.DockerComposeContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import java.io.File;4public class DockerCompose {5 public static void main(String[] args) {6 File composeFile = new File("docker-compose.yml");7 DockerComposeContainer container = new DockerComposeContainer(composeFile);8 container.waitingFor("mysql", Wait.forLogMessage(".*mysqld: ready for connections.*\\s", 1));9 container.start();10 container.stop();11 }12}
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!!