Best Testcontainers-java code snippet using org.testcontainers.dockerclient.DockerClientProviderStrategy.test
Source:DockerClientProviderStrategy.java
1package org.testcontainers.dockerclient;2import com.github.dockerjava.api.DockerClient;3import com.github.dockerjava.core.DockerClientBuilder;4import com.github.dockerjava.core.DockerClientConfig;5import com.google.common.base.Throwables;6import org.apache.commons.io.IOUtils;7import org.jetbrains.annotations.Nullable;8import org.rnorth.ducttape.TimeoutException;9import org.rnorth.ducttape.ratelimits.RateLimiter;10import org.rnorth.ducttape.ratelimits.RateLimiterBuilder;11import org.rnorth.ducttape.unreliables.Unreliables;12import org.slf4j.Logger;13import org.slf4j.LoggerFactory;14import org.testcontainers.dockerclient.transport.TestcontainersDockerCmdExecFactory;15import org.testcontainers.utility.TestcontainersConfiguration;16import java.util.ArrayList;17import java.util.Comparator;18import java.util.List;19import java.util.Objects;20import java.util.concurrent.TimeUnit;21import java.util.concurrent.atomic.AtomicBoolean;22import java.util.stream.Stream;23/**24 * Mechanism to find a viable Docker client configuration according to the host system environment.25 */26public abstract class DockerClientProviderStrategy {27 protected DockerClient client;28 protected DockerClientConfig config;29 private static final RateLimiter PING_RATE_LIMITER = RateLimiterBuilder.newBuilder()30 .withRate(2, TimeUnit.SECONDS)31 .withConstantThroughput()32 .build();33 private static final AtomicBoolean FAIL_FAST_ALWAYS = new AtomicBoolean(false);34 /**35 * @throws InvalidConfigurationException if this strategy fails36 */37 public abstract void test() throws InvalidConfigurationException;38 /**39 * @return a short textual description of the strategy40 */41 public abstract String getDescription();42 protected boolean isApplicable() {43 return true;44 }45 protected boolean isPersistable() {46 return true;47 }48 /**49 * @return highest to lowest priority value50 */51 protected int getPriority() {52 return 0;53 }54 protected static final Logger LOGGER = LoggerFactory.getLogger(DockerClientProviderStrategy.class);55 /**56 * Determine the right DockerClientConfig to use for building clients by trial-and-error.57 *58 * @return a working DockerClientConfig, as determined by successful execution of a ping command59 */60 public static DockerClientProviderStrategy getFirstValidStrategy(List<DockerClientProviderStrategy> strategies) {61 if (FAIL_FAST_ALWAYS.get()) {62 throw new IllegalStateException("Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration");63 }64 List<String> configurationFailures = new ArrayList<>();65 return Stream66 .concat(67 Stream68 .of(TestcontainersConfiguration.getInstance().getDockerClientStrategyClassName())69 .filter(Objects::nonNull)70 .flatMap(it -> {71 try {72 Class<? extends DockerClientProviderStrategy> strategyClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(it);73 return Stream.of(strategyClass.newInstance());74 } catch (ClassNotFoundException e) {75 LOGGER.warn("Can't instantiate a strategy from {} (ClassNotFoundException). " +76 "This probably means that cached configuration refers to a client provider " +77 "class that is not available in this version of Testcontainers. Other " +78 "strategies will be tried instead.", it);79 return Stream.empty();80 } catch (InstantiationException | IllegalAccessException e) {81 LOGGER.warn("Can't instantiate a strategy from {}", it, e);82 return Stream.empty();83 }84 })85 // Ignore persisted strategy if it's not persistable anymore86 .filter(DockerClientProviderStrategy::isPersistable)87 .peek(strategy -> LOGGER.info("Loaded {} from ~/.testcontainers.properties, will try it first", strategy.getClass().getName())),88 strategies89 .stream()90 .filter(DockerClientProviderStrategy::isApplicable)91 .sorted(Comparator.comparing(DockerClientProviderStrategy::getPriority).reversed())92 )93 .flatMap(strategy -> {94 try {95 strategy.test();96 LOGGER.info("Found Docker environment with {}", strategy.getDescription());97 if (strategy.isPersistable()) {98 TestcontainersConfiguration.getInstance().updateGlobalConfig("docker.client.strategy", strategy.getClass().getName());99 }100 return Stream.of(strategy);101 } catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) {102 @Nullable String throwableMessage = e.getMessage();103 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")104 Throwable rootCause = Throwables.getRootCause(e);105 @Nullable String rootCauseMessage = rootCause.getMessage();106 String failureDescription;107 if (throwableMessage != null && throwableMessage.equals(rootCauseMessage)) {108 failureDescription = String.format("%s: failed with exception %s (%s)",109 strategy.getClass().getSimpleName(),110 e.getClass().getSimpleName(),111 throwableMessage);112 } else {113 failureDescription = String.format("%s: failed with exception %s (%s). Root cause %s (%s)",114 strategy.getClass().getSimpleName(),115 e.getClass().getSimpleName(),116 throwableMessage,117 rootCause.getClass().getSimpleName(),118 rootCauseMessage119 );120 }121 configurationFailures.add(failureDescription);122 LOGGER.debug(failureDescription);123 return Stream.empty();124 }125 })126 .findAny()127 .orElseThrow(() -> {128 LOGGER.error("Could not find a valid Docker environment. Please check configuration. Attempted configurations were:");129 for (String failureMessage : configurationFailures) {130 LOGGER.error(" " + failureMessage);131 }132 LOGGER.error("As no valid configuration was found, execution cannot continue");133 FAIL_FAST_ALWAYS.set(true);134 return new IllegalStateException("Could not find a valid Docker environment. Please see logs and check configuration");135 });136 }137 /**138 * @return a usable, tested, Docker client configuration for the host system environment139 */140 public DockerClient getClient() {141 return new AuditLoggingDockerClient(client);142 }143 protected DockerClient getClientForConfig(DockerClientConfig config) {144 return DockerClientBuilder145 .getInstance(config)146 .withDockerCmdExecFactory(new TestcontainersDockerCmdExecFactory())147 .build();148 }149 protected void ping(DockerClient client, int timeoutInSeconds) {150 try {151 Unreliables.retryUntilSuccess(timeoutInSeconds, TimeUnit.SECONDS, () -> {152 return PING_RATE_LIMITER.getWhenReady(() -> {...
Source:DockerRunTest.java
1package org.testcontainers.did;2import com.github.dockerjava.api.DockerClient;3import com.github.dockerjava.api.command.CreateContainerCmd;4import com.github.dockerjava.api.exception.InternalServerErrorException;5import com.github.dockerjava.api.exception.NotFoundException;6import com.github.dockerjava.core.command.LogContainerCmdImpl;7import com.github.dockerjava.core.command.LogContainerResultCallback;8import org.junit.jupiter.api.DisplayName;9import org.junit.jupiter.api.Test;10import org.junit.jupiter.api.Timeout;11import org.slf4j.Logger;12import org.slf4j.LoggerFactory;13import org.testcontainers.dockerclient.DockerClientProviderStrategy;14import org.testcontainers.dockerclient.LogToStringContainerCallback;15import org.testcontainers.utility.TestcontainersConfiguration;16import java.util.ArrayList;17import java.util.List;18import java.util.ServiceLoader;19import static java.util.concurrent.TimeUnit.SECONDS;20import static org.junit.Assert.assertTrue;21import static org.testcontainers.DockerClientFactory.DEFAULT_LABELS;22class DockerRunTest {23 @Test24 @DisplayName("Test run and exit docker container")25 @Timeout(value = 30, unit = SECONDS)26 void testRunDockerInDocker() {27 final Logger logger = LoggerFactory.getLogger(this.getClass());28 final List<DockerClientProviderStrategy> configurationStrategies = new ArrayList<>();29 final ServiceLoader<DockerClientProviderStrategy> load = ServiceLoader.load(DockerClientProviderStrategy.class);30 load.forEach(configurationStrategies::add);31 final DockerClientProviderStrategy strategy = DockerClientProviderStrategy.getFirstValidStrategy(configurationStrategies);32 final DockerClient strategyDockerClient = strategy.getClient();33 final String TINY_IMAGE = TestcontainersConfiguration.getInstance().getTinyImage();34 logger.info("Pulling {} image", TINY_IMAGE);35 logger.info("Image {} pulled successfully", TINY_IMAGE);36 strategyDockerClient.pullImageCmd(TINY_IMAGE);37 final CreateContainerCmd createContainerCmd = strategyDockerClient38 .createContainerCmd(TINY_IMAGE)39 .withLabels(DEFAULT_LABELS)40 .withCmd("sh", "-c", "ip route|awk '/default/ { print $3 }' ; exit");...
test
Using AI Code Generation
1import org.testcontainers.DockerClientFactory;2import org.testcontainers.dockerclient.DockerClientProviderStrategy;3public class 1 {4 public static void main(String[] args) {5 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();6 strategy.test();7 }8}9import org.testcontainers.DockerClientFactory;10import org.testcontainers.dockerclient.DockerClientProviderStrategy;11public class 2 {12 public static void main(String[] args) {13 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();14 strategy.test();15 }16}17import org.testcontainers.DockerClientFactory;18import org.testcontainers.dockerclient.DockerClientProviderStrategy;19public class 3 {20 public static void main(String[] args) {21 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();22 strategy.test();23 }24}25import org.testcontainers.DockerClientFactory;26import org.testcontainers.dockerclient.DockerClientProviderStrategy;27public class 4 {28 public static void main(String[] args) {29 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();30 strategy.test();31 }32}33import org.testcontainers.DockerClientFactory;34import org.testcontainers.dockerclient.DockerClientProviderStrategy;35public class 5 {36 public static void main(String[] args) {37 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();38 strategy.test();39 }40}41import org.testcontainers.DockerClientFactory;42import org.testcontainers.dockerclient.DockerClientProviderStrategy;43public class 6 {44 public static void main(String[] args) {45 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();46 strategy.test();47 }48}
test
Using AI Code Generation
1import org.testcontainers.dockerclient.DockerClientProviderStrategy;2import org.testcontainers.utility.DockerMachineClient;3import org.testcontainers.utility.DockerMachineClientProviderStrategy;4import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig;5import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder;6import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProvider;7import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl;8import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilder;9import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilder.DockerMachineClientConfigBuilderProviderImplBuilderProvider;10import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilder.DockerMachineClientConfigBuilderProviderImplBuilderProviderImpl;11import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilder.DockerMachineClientConfigBuilderProviderImplBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilderProviderImplBuilder;12import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilder.DockerMachineClientConfigBuilderProviderImplBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilderProviderImplBuilder.DockerMachineClientConfigBuilderProviderImplBuilderProviderImplBuilderImpl;13import org.testcontainers.utility.DockerMachineClientProviderStrategy.DockerMachineClientConfig.DockerMachineClientConfigBuilder.DockerMachineClientConfigBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilder.DockerMachineClientConfigBuilderProviderImplBuilderProviderImpl.DockerMachineClientConfigBuilderProviderImplBuilderProviderImplBuilderImpl.DockerMachineClientConfigBuilderProviderImplBuilderProviderImplBuilderImplBuilder;14import org.testcontainers.utility
test
Using AI Code Generation
1import org.testcontainers.DockerClientFactory;2import org.testcontainers.dockerclient.DockerClientProviderStrategy;3import org.testcontainers.utility.DockerImageName;4public class TestContainerTest {5 public static void main(String[] args) {6 DockerClientProviderStrategy strategy = DockerClientFactory.instance().strategy();7 DockerImageName imageName = DockerImageName.parse("mysql:8.0.22");8 strategy.test(
test
Using AI Code Generation
1import org.testcontainers.DockerClientFactory;2import org.testcontainers.dockerclient.DockerClientProviderStrategy;3public class Test {4 public static void main(String[] args) {5 DockerClientProviderStrategy d = DockerClientFactory.instance().strategy();6 d.test();7 }8}9 at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:165)10 at org.testcontainers.DockerClientFactory.client(DockerClientFactory.java:151)11 at org.testcontainers.DockerClientFactory.instance(D
test
Using AI Code Generation
1import org.testcontainers.dockerclient.DockerClientProviderStrategy;2public class TestClient {3 public static void main(String[] args) {4 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();5 strategy.test();6 }7}8import org.testcontainers.dockerclient.DockerClientConfigUtils;9public class TestClient {10 public static void main(String[] args) {11 DockerClientConfigUtils.test();12 }13}14import org.testcontainers.dockerclient.EnvironmentAndSystemPropertyClientProviderStrategy;15public class TestClient {16 public static void main(String[] args) {17 EnvironmentAndSystemPropertyClientProviderStrategy strategy = new EnvironmentAndSystemPropertyClientProviderStrategy();18 strategy.test();19 }20}21import org.testcontainers.dockerclient.UnixSocketClientProviderStrategy;22public class TestClient {23 public static void main(String[] args) {24 UnixSocketClientProviderStrategy strategy = new UnixSocketClientProviderStrategy();25 strategy.test();26 }27}28import org.testcontainers.dockerclient.WindowsClientProviderStrategy;29public class TestClient {30 public static void main(String[] args) {31 WindowsClientProviderStrategy strategy = new WindowsClientProviderStrategy();32 strategy.test();33 }34}
test
Using AI Code Generation
1import org.testcontainers.dockerclient.DockerClientProviderStrategy;2import org.testcontainers.utility.DockerMachineClient;3import org.testcontainers.utility.DockerMachineClientProviderStrategy;4public class TestDocker {5 public static void main(String[] args) {6 DockerMachineClientProviderStrategy dockerMachineClientProviderStrategy = new DockerMachineClientProviderStrategy();7 DockerMachineClient dockerMachineClient = dockerMachineClientProviderStrategy.getClient();8 DockerClientProviderStrategy dockerClientProviderStrategy = new DockerClientProviderStrategy(dockerMachineClient);9 boolean isDockerRunning = dockerClientProviderStrategy.test();10 System.out.println("Is Docker Running? " + isDockerRunning);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!!