How to use forHealthcheck method of org.testcontainers.containers.wait.strategy.Wait class

Best Testcontainers-java code snippet using org.testcontainers.containers.wait.strategy.Wait.forHealthcheck

Source:ServerIntegratedBenchmark.java Github

copy

Full Screen

...85 .withNetworkAliases("elasticsearch")86 .withLabel("name", "elasticsearch")87 .withLabel("storageType", "elasticsearch")88 .withExposedPorts(9200)89 .waitingFor(Wait.forHealthcheck());90 containers.add(elasticsearch);91 runBenchmark(elasticsearch);92 }93 @Test void cassandra3() throws Exception {94 GenericContainer<?> cassandra =95 new GenericContainer<>(parse("ghcr.io/openzipkin/zipkin-cassandra:2.23.2"))96 .withNetwork(Network.SHARED)97 .withNetworkAliases("cassandra")98 .withLabel("name", "cassandra")99 .withLabel("storageType", "cassandra3")100 .withExposedPorts(9042)101 .waitingFor(Wait.forHealthcheck());102 containers.add(cassandra);103 runBenchmark(cassandra);104 }105 @Test void mysql() throws Exception {106 GenericContainer<?> mysql =107 new GenericContainer<>(parse("ghcr.io/openzipkin/zipkin-mysql:2.23.2"))108 .withNetwork(Network.SHARED)109 .withNetworkAliases("mysql")110 .withLabel("name", "mysql")111 .withLabel("storageType", "mysql")112 .withExposedPorts(3306)113 .waitingFor(Wait.forHealthcheck());114 containers.add(mysql);115 runBenchmark(mysql);116 }117 void runBenchmark(@Nullable GenericContainer<?> storage) throws Exception {118 runBenchmark(storage, createZipkinContainer(storage));119 }120 void runBenchmark(@Nullable GenericContainer<?> storage, GenericContainer<?> zipkin)121 throws Exception {122 GenericContainer<?> backend =123 new GenericContainer<>(parse("ghcr.io/openzipkin/brave-example:armeria"))124 .withNetwork(Network.SHARED)125 .withNetworkAliases("backend")126 .withCommand("backend")127 .withExposedPorts(9000)128 .waitingFor(Wait.forHealthcheck());129 GenericContainer<?> frontend =130 new GenericContainer<>(parse("ghcr.io/openzipkin/brave-example:armeria"))131 .withNetwork(Network.SHARED)132 .withNetworkAliases("frontend")133 .withCommand("frontend")134 .withExposedPorts(8081)135 .waitingFor(Wait.forHealthcheck());136 containers.add(frontend);137 // Use a quay.io mirror to prevent build outages due to Docker Hub pull quotas138 // Use same version as in docker/examples/docker-compose-prometheus.yml139 GenericContainer<?> prometheus =140 new GenericContainer<>(parse("quay.io/prometheus/prometheus:v2.23.0"))141 .withNetwork(Network.SHARED)142 .withNetworkAliases("prometheus")143 .withExposedPorts(9090)144 .withCopyFileToContainer(145 MountableFile.forClasspathResource("prometheus.yml"), "/etc/prometheus/prometheus.yml");146 containers.add(prometheus);147 // Use a quay.io mirror to prevent build outages due to Docker Hub pull quotas148 // Use same version as in docker/examples/docker-compose-prometheus.yml149 GenericContainer<?> grafana = new GenericContainer<>(parse("quay.io/app-sre/grafana:7.3.4"))150 .withNetwork(Network.SHARED)151 .withNetworkAliases("grafana")152 .withExposedPorts(3000)153 .withEnv("GF_AUTH_ANONYMOUS_ENABLED", "true")154 .withEnv("GF_AUTH_ANONYMOUS_ORG_ROLE", "Admin");155 containers.add(grafana);156 // This is an arbitrary small image that has curl installed157 // Use a quay.io mirror to prevent build outages due to Docker Hub pull quotas158 // Use same version as in docker/examples/docker-compose-prometheus.yml159 GenericContainer<?> grafanaDashboards =160 new GenericContainer<>(parse("quay.io/rackspace/curl:7.70.0"))161 .withNetwork(Network.SHARED)162 .withWorkingDirectory("/tmp")163 .withLogConsumer(new Slf4jLogConsumer(LOG))164 .withCreateContainerCmdModifier(it -> it.withEntrypoint("/tmp/create.sh"))165 .withCopyFileToContainer(166 MountableFile.forClasspathResource("create-datasource-and-dashboard.sh", 555),167 "/tmp/create.sh");168 containers.add(grafanaDashboards);169 // Use a quay.io mirror to prevent build outages due to Docker Hub pull quotas170 GenericContainer<?> wrk = new GenericContainer<>(parse("quay.io/dim/wrk:stable"))171 .withNetwork(Network.SHARED)172 .withCreateContainerCmdModifier(it -> it.withEntrypoint("wrk"))173 .withCommand("-t4 -c128 -d100s http://frontend:8081 --latency");174 containers.add(wrk);175 grafanaDashboards.dependsOn(grafana);176 wrk.dependsOn(frontend, backend, prometheus, grafanaDashboards, zipkin);177 if (storage != null) wrk.dependsOn(storage);178 Startables.deepStart(Stream.of(wrk)).join();179 System.out.println("Benchmark started.");180 if (zipkin != null) printContainerMapping(zipkin);181 if (storage != null) printContainerMapping(storage);182 printContainerMapping(backend);183 printContainerMapping(frontend);184 printContainerMapping(prometheus);185 printContainerMapping(grafana);186 while (wrk.isRunning()) {187 Thread.sleep(1000);188 }189 // Wait for prometheus to do a final scrape.190 Thread.sleep(5000);191 System.out.println("Benchmark complete, wrk output:");192 System.out.println(wrk.getLogs().replace("\n\n", "\n"));193 WebClient prometheusClient = WebClient.of(194 "h1c://" + prometheus.getContainerIpAddress() + ":" + prometheus.getFirstMappedPort());195 System.out.println(String.format("Messages received: %s", prometheusValue(196 prometheusClient, "sum(zipkin_collector_messages_total)")));197 System.out.println(String.format("Spans received: %s", prometheusValue(198 prometheusClient, "sum(zipkin_collector_spans_total)")));199 System.out.println(String.format("Spans dropped: %s", prometheusValue(200 prometheusClient, "sum(zipkin_collector_spans_dropped_total)")));201 System.out.println("Memory quantiles:");202 printQuartiles(prometheusClient, "jvm_memory_used_bytes{area=\"heap\"}");203 printQuartiles(prometheusClient, "jvm_memory_used_bytes{area=\"nonheap\"}");204 System.out.println(String.format("Total GC time (s): %s",205 prometheusValue(prometheusClient, "sum(jvm_gc_pause_seconds_sum)")));206 System.out.println(String.format("Number of GCs: %s",207 prometheusValue(prometheusClient, "sum(jvm_gc_pause_seconds_count)")));208 System.out.println("POST Spans latency (s)");209 printHistogram(prometheusClient, "http_server_requests_seconds_bucket{"210 + "method=\"POST\",status=\"202\",uri=\"/api/v2/spans\"}");211 if (WAIT_AFTER_BENCHMARK) {212 System.out.println("Keeping containers running until explicit termination. "213 + "Feel free to poke around in grafana.");214 Thread.sleep(Long.MAX_VALUE);215 }216 }217 GenericContainer<?> createZipkinContainer(@Nullable GenericContainer<?> storage)218 throws Exception {219 Map<String, String> env = new LinkedHashMap<>();220 if (storage != null) {221 String name = storage.getLabels().get("name");222 String host = name;223 int port = storage.getExposedPorts().get(0);224 String address = host + ":" + port;225 env.put("STORAGE_TYPE", storage.getLabels().get("storageType"));226 switch (name) {227 case "elasticsearch":228 env.put("ES_HOSTS", "http://" + address);229 break;230 case "cassandra":231 case "cassandra3":232 env.put("CASSANDRA_CONTACT_POINTS", address);233 break;234 case "mysql":235 env.put("MYSQL_HOST", host);236 env.put("MYSQL_TCP_PORT", Integer.toString(port));237 env.put("MYSQL_USER", "zipkin");238 env.put("MYSQL_PASS", "zipkin");239 break;240 default:241 throw new IllegalArgumentException("Unknown storage " + name +242 ". Update startZipkin to map it to properties.");243 }244 }245 final GenericContainer<?> zipkin;246 if (RELEASE_VERSION == null) {247 zipkin = new GenericContainer<>(parse("ghcr.io/openzipkin/java:15.0.1_p9"));248 List<String> classpath = new ArrayList<>();249 for (String item : System.getProperty("java.class.path").split(File.pathSeparator)) {250 Path path = Paths.get(item);251 final String containerPath;252 if (Files.isDirectory(path)) {253 Path root = path.getParent();254 while (root != null) {255 try (Stream<Path> f = Files.list(root)) {256 if (f.anyMatch(p -> p.getFileName().toString().equals("mvnw"))) {257 break;258 }259 }260 root = root.getParent();261 }262 containerPath = root.relativize(path).toString().replace('\\', '/');263 } else {264 containerPath = path.getFileName().toString();265 }266 // Test containers currently doesn't support copying in a path with subdirectories that267 // need to be created, so we mangle directory structure into a single directory with268 // hyphens.269 String classPathItem = "/classpath-" + containerPath.replace('/', '-');270 zipkin.withCopyFileToContainer(MountableFile.forHostPath(item), classPathItem);271 classpath.add(classPathItem);272 }273 zipkin.withCreateContainerCmdModifier(cmd -> cmd.withEntrypoint("java"));274 zipkin.setCommand("-cp", String.join(":", classpath), "zipkin.server.ZipkinServer");275 // Don't fail on classpath problem from missing lens, as we don't use it.276 env.put("ZIPKIN_UI_ENABLED", "false");277 } else {278 zipkin = new GenericContainer<>(parse("ghcr.io/openzipkin/zipkin:" + RELEASE_VERSION));279 }280 zipkin281 .withNetwork(Network.SHARED)282 .withNetworkAliases("zipkin")283 .withExposedPorts(9411)284 .withEnv(env)285 .waitingFor(Wait.forHealthcheck());286 containers.add(zipkin);287 return zipkin;288 }289 static void printContainerMapping(GenericContainer<?> container) {290 System.out.println(String.format(291 "Container %s ports exposed at %s",292 container.getDockerImageName(),293 container.getExposedPorts().stream()294 .map(port -> new SimpleImmutableEntry<>(port,295 "http://" + container.getContainerIpAddress() + ":" + container.getMappedPort(port)))296 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));297 }298 static void printQuartiles(WebClient prometheus, String metric) throws Exception {299 for (double quantile : Arrays.asList(0.0, 0.25, 0.5, 0.75, 1.0)) {...

Full Screen

Full Screen

Source:TestContainerConfiguration.java Github

copy

Full Screen

...20 static final KeycloakContainer KEYCLOAK_CONTAINER;21 static {22 POSTGRE_SQL_CONTAINER = new PostgreSQLContainer("postgres:12.5-alpine");23 POSTGRE_SQL_CONTAINER.start();24 POSTGRE_SQL_CONTAINER.waitingFor(Wait.forHealthcheck()).waitingFor(Wait.forHttp("/"));25 KEYCLOAK_CONTAINER =26 new KeycloakContainer("jboss/keycloak:12.0.4")27 .withRealmImportFile("sample-realm.json")28 .withCopyFileToContainer(29 MountableFile.forClasspathResource("create-keycloak-user.sh", 700),30 "create-keycloak-user.sh");31 KEYCLOAK_CONTAINER.start();32 KEYCLOAK_CONTAINER.waitingFor(Wait.forHealthcheck()).waitingFor(Wait.forHttp("/"));33 try {34 ExecResult result = KEYCLOAK_CONTAINER.execInContainer("sh", "create-keycloak-user.sh");35 log.info(result.toString());36 } catch (Exception e) {37 log.error("error during executing script", e);38 }39 }40 @Autowired KeycloakSpringBootProperties keycloakSpringBootProperties;41 @PostConstruct42 void init() {43 keycloakSpringBootProperties.setAuthServerUrl(KEYCLOAK_CONTAINER.getAuthServerUrl());44 }45 @Primary46 @Bean...

Full Screen

Full Screen

Source:WaitStrategiesTest.java Github

copy

Full Screen

...29 // }30 private static final HttpWaitStrategy TLS_HTTP_WAIT = Wait.forHttp("/all").usingTls();31 // healthcheckWait {32 // }33 private static final WaitStrategy HEALTHCHECK_WAIT = Wait.forHealthcheck();34 @Test35 public void testContainersAllStarted() {36 Assert.assertTrue(nginx.isRunning());37 Assert.assertTrue(nginxWithHttpWait.isRunning());38 Assert.assertTrue(containerWithLogWait.isRunning());39 }40}...

Full Screen

Full Screen

forHealthcheck

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers.wait.strategy;2import com.github.dockerjava.api.command.InspectContainerResponse;3import com.github.dockerjava.api.model.ContainerNetwork;4import com.github.dockerjava.api.model.Frame;5import com.github.dockerjava.api.model.Ports;6import com.github.dockerjava.core.command.LogContainerResultCallback;7import com.github.dockerjava.core.command.WaitContainerResultCallback;8import lombok.extern.slf4j.Slf4j;9import org.jetbrains.annotations.NotNull;10import org.testcontainers.containers.ContainerLaunchException;11import org.testcontainers.containers.GenericContainer;12import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;13import org.testcontainers.utility.MountableFile;14import java.io.IOException;15import java.util.concurrent.TimeUnit;16public class WaitForHealthCheck implements WaitStrategy {17 private final int startupTimeoutSeconds;18 public WaitForHealthCheck() {19 this.startupTimeoutSeconds = 60;20 }21 public WaitForHealthCheck(int startupTimeoutSeconds) {22 this.startupTimeoutSeconds = startupTimeoutSeconds;23 }24 public void waitUntilReady(WaitStrategyTarget waitStrategyTarget) {25 log.debug("Waiting for container to be healthy");26 waitStrategyTarget.waitUntilContainerStarted();27 try {28 InspectContainerResponse containerInfo = waitStrategyTarget.getContainerInfo();29 if (containerInfo.getState().isRunning()) {30 log.debug("Container is running, waiting for healthcheck to pass");31 waitStrategyTarget.getContainerId();32 waitStrategyTarget.waitUntilContainerStarted();33 waitStrategyTarget.waitUntilContainerIsRunning();34 }35 waitStrategyTarget.waitUntilContainerStarted();36 waitStrategyTarget.waitUntilContainerIsRunning();37 waitStrategyTarget.waitUntilContainerIsHealthy();38 } catch (IOException e) {39 throw new ContainerLaunchException("Timed out waiting for container to start", e);40 }41 }42}43package org.testcontainers.containers;44import com.github.dockerjava.api.command.InspectContainerResponse;45import com.github.dockerjava.api.model.ContainerNetwork;46import com.github.dockerjava.api.model.Frame;47import com.github.dockerjava.api.model.Ports;48import com.github.dockerjava.core.command.LogContainerResultCallback;49import com.github.dockerjava.core.command.WaitContainerResultCallback;50import lombok.extern.slf4j.Slf4j;51import org.jetbrains.annotations.NotNull;52import org.testcontainers.containers

Full Screen

Full Screen

forHealthcheck

Using AI Code Generation

copy

Full Screen

1package com.mycompany.app;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.wait.strategy.Wait;4public class App {5 public static void main(String[] args) {6 GenericContainer container = new GenericContainer("nginx:latest")7 .withExposedPorts(80)8 .waitingFor(Wait.forHealthcheck());9 container.start();10 System.out.println("Started container with IP: " + container.getContainerIpAddress());11 System.out.println("Started container with port: " + container.getFirstMappedPort());12 container.stop();13 }14}15package com.mycompany.app;16import org.testcontainers.containers.GenericContainer;17import org.testcontainers.containers.wait.strategy.Wait;18public class App {19 public static void main(String[] args) {20 GenericContainer container = new GenericContainer("nginx:latest")21 .withExposedPorts(80)22 .waitingFor(Wait.forHttp("/"));23 container.start();24 System.out.println("Started container with IP: " + container.getContainerIpAddress());25 System.out.println("Started container with port: " + container.getFirstMappedPort());26 container.stop();27 }28}29package com.mycompany.app;30import org.testcontainers.containers.GenericContainer;31import org.testcontainers.containers.wait.strategy.Wait;32public class App {33 public static void main(String[] args) {34 GenericContainer container = new GenericContainer("nginx:latest")35 .withExposedPorts(80)36 .waitingFor(Wait.forLogMessage(".*starting.*", 1));37 container.start();38 System.out.println("Started container with IP: " + container.getContainerIpAddress());39 System.out.println("Started container with port: " + container.getFirstMappedPort());40 container.stop();41 }42}43package com.mycompany.app;44import org.testcontainers.containers.GenericContainer;45import org.testcontainers.containers.wait.strategy.Wait;46public class App {47 public static void main(String[] args) {48 GenericContainer container = new GenericContainer("nginx:latest")49 .withExposedPorts(80)50 .waitingFor(Wait.forShellScript

Full Screen

Full Screen

forHealthcheck

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import java.net.Socket;3import java.util.concurrent.TimeUnit;4import org.testcontainers.containers.wait.strategy.WaitStrategy;5import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;6public class ForHealthCheck implements WaitStrategy {7 private final String host;8 private final int port;9 private final int timeout;10 public ForHealthCheck(String host, int port, int timeout) {11 this.host = host;12 this.port = port;13 this.timeout = timeout;14 }15 public void waitUntilReady(WaitStrategyTarget waitStrategyTarget) {16 try {17 waitUntilReady();18 } catch (InterruptedException e) {19 throw new RuntimeException(e);20 }21 }22 private void waitUntilReady() throws InterruptedException {23 long start = System.currentTimeMillis();24 while (!isReady()) {25 if (System.currentTimeMillis() - start > TimeUnit.SECONDS.toMillis(timeout)) {26 throw new IllegalStateException("Timed out waiting for container to be ready");27 }28 Thread.sleep(100);29 }30 }31 private boolean isReady() {32 try (Socket ignored = new Socket(host, port)) {33 return true;34 } catch (IOException e) {35 return false;36 }37 }38}39import org.testcontainers.containers.GenericContainer;40import org.testcontainers.containers.wait.strategy.Wait;41public class TestContainer {42 public static void main(String[] args) {43 GenericContainer container = new GenericContainer("postgres:9.6.2")44 .withExposedPorts(5432)45 .waitingFor(new ForHealthCheck("localhost", 5432, 60));46 container.start();47 container.stop();48 }49}

Full Screen

Full Screen

forHealthcheck

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers.wait.strategy;2import org.testcontainers.containers.ContainerState;3import org.testcontainers.containers.GenericContainer;4import java.io.IOException;5public class Wait {6 public static WaitStrategy forHealthcheck() {7 return new WaitStrategy() {8 public void waitUntilReady(GenericContainer container) {9 try {10 } catch (IOException | InterruptedException e) {11 throw new IllegalStateException(e);12 }13 }14 };15 }16}17package org.testcontainers.containers.wait.strategy;18import org.testcontainers.containers.ContainerState;19import org.testcontainers.containers.GenericContainer;20import java.io.IOException;21public class Wait {22 public static WaitStrategy forHealthcheck() {23 return new WaitStrategy() {24 public void waitUntilReady(GenericContainer container) {25 try {26 } catch (IOException | InterruptedException e) {27 throw new IllegalStateException(e);28 }29 }30 };31 }32}33package org.testcontainers.containers.wait.strategy;34import org.testcontainers.containers.ContainerState;35import org.testcontainers.containers.GenericContainer;36import java.io.IOException;37public class Wait {38 public static WaitStrategy forHealthcheck() {39 return new WaitStrategy() {40 public void waitUntilReady(GenericContainer container) {41 try {42 } catch (IOException | InterruptedException e) {43 throw new IllegalStateException(e);44 }45 }46 };47 }48}49package org.testcontainers.containers.wait.strategy;50import org.testcontainers.containers.ContainerState;51import org.testcontainers.containers.GenericContainer

Full Screen

Full Screen

forHealthcheck

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.wait.strategy.Wait;2public class HealthcheckWaitStrategy extends WaitStrategyTarget {3 private static final String DEFAULT_HEALTHCHECK_URL = "/actuator/health";4 private final String healthcheckUrl;5 public HealthcheckWaitStrategy() {6 this(DEFAULT_HEALTHCHECK_URL);7 }8 public HealthcheckWaitStrategy(String healthcheckUrl) {9 this.healthcheckUrl = healthcheckUrl;10 }11 protected void waitUntilReady() {12 getLivenessCheckUrls().forEach(this::waitUntilReady);13 }14 private void waitUntilReady(String url) {15 Unreliables.retryUntilTrue((int) startupTimeout.getSeconds(), TimeUnit.SECONDS, () -> {16 try {17 final Response response = client.target(url).request().get();18 final int status = response.getStatus();19 if (status == 200) {20 final String content = response.readEntity(String.class);21 final Map<String, Object> json = JsonHelper.fromJson(content, Map.class);22 final Object statusValue = json.get("status");23 if (statusValue == null) {24 throw new IllegalStateException("Healthcheck response did not contain a 'status' field");25 }26 return "UP".equals(statusValue.toString());27 } else {28 throw new IllegalStateException("Healthcheck returned a non-200 status code: " + status);29 }30 } catch (ProcessingException e) {31 return false;32 }33 });34 }35 private List<String> getLivenessCheckUrls() {36 return target.getContainerInfo().getNetworkSettings().getPorts().getBindings().entrySet().stream()37 .filter((entry) -> entry.getKey().getProtocol().equals("tcp"))38 .map((entry) -> {

Full Screen

Full Screen

forHealthcheck

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers.wait.strategy;2import com.github.dockerjava.api.command.InspectContainerResponse;3import com.github.dockerjava.api.command.WaitContainerResultCallback;4import com.github.dockerjava.api.model.Container;5import com.github.dockerjava.api.model.ContainerState.Health;6import com.github.dockerjava.api.model.ContainerState.Health.Status;7import com.github.dockerjava.api.model.ContainerState.Healthcheck;8import com.github.dockerjava.api.model.ContainerState.Healthcheck.Result;9import com.github.dockerjava.api.model.ContainerState.Healthcheck.State;10import com.github.dockerjava.api.model.HealthcheckLog;11import com.github.dockerjava.core.command.WaitContainerResultCallback;12import com.github.dockerjava.core.command.WaitContainerResultCallbac

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful