How to use tryStart method of org.testcontainers.containers.GenericContainer class

Best Testcontainers-java code snippet using org.testcontainers.containers.GenericContainer.tryStart

Source:GenericContainer.java Github

copy

Full Screen

...166 logger().debug("Trying to start container: {}", image.get());167 AtomicInteger attempt = new AtomicInteger(0);168 Unreliables.retryUntilSuccess(startupAttempts, () -> {169 logger().debug("Trying to start container: {} (attempt {}/{})", image.get(), attempt.incrementAndGet(), startupAttempts);170 tryStart(profiler.startNested("Container startup attempt"));171 return true;172 });173 } catch (Exception e) {174 throw new ContainerLaunchException("Container startup failed", e);175 } finally {176 profiler.stop().log();177 }178 }179 private void tryStart(Profiler profiler) {180 try {181 String dockerImageName = image.get();182 logger().debug("Starting container: {}", dockerImageName);183 logger().info("Creating container for image: {}", dockerImageName);184 profiler.start("Create container");185 CreateContainerCmd createCommand = dockerClient.createContainerCmd(dockerImageName);186 applyConfiguration(createCommand);187 containerId = createCommand.exec().getId();188 logger().info("Starting container with ID: {}", containerId);189 profiler.start("Start container");190 dockerClient.startContainerCmd(containerId).exec();191 // For all registered output consumers, start following as close to container startup as possible192 this.logConsumers.forEach(this::followOutput);193 logger().info("Container {} is starting: {}", dockerImageName, containerId);194 // Tell subclasses that we're starting195 profiler.start("Inspecting container");196 containerInfo = dockerClient.inspectContainerCmd(containerId).exec();197 containerName = containerInfo.getName();198 profiler.start("Call containerIsStarting on subclasses");199 containerIsStarting(containerInfo);200 // Wait until the container is running (may not be fully started)201 profiler.start("Wait until container has started properly, or there's evidence it failed to start.");202 if (!this.startupCheckStrategy.waitUntilStartupSuccessful(dockerClient, containerId)) {203 // Bail out, don't wait for the port to start listening.204 // (Exception thrown here will be caught below and wrapped)205 throw new IllegalStateException("Container did not start correctly.");206 }207 profiler.start("Wait until container started properly");208 waitUntilContainerStarted();209 logger().info("Container {} started", dockerImageName);210 containerIsStarted(containerInfo);211 } catch (Exception e) {212 logger().error("Could not start container", e);213 // Log output if startup failed, either due to a container failure or exception (including timeout)214 logger().error("Container log output (if any) will follow:");215 FrameConsumerResultCallback resultCallback = new FrameConsumerResultCallback();216 resultCallback.addConsumer(STDOUT, new Slf4jLogConsumer(logger()));217 resultCallback.addConsumer(STDERR, new Slf4jLogConsumer(logger()));218 dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true).exec(resultCallback);219 // Try to ensure that container log output is shown before proceeding220 try {221 resultCallback.getCompletionLatch().await(1, TimeUnit.MINUTES);222 } catch (InterruptedException ignored) {223 // Cannot do anything at this point224 }225 throw new ContainerLaunchException("Could not create/start container", e);226 } finally {227 profiler.stop();228 }229 }230 /**231 * Stops the container.232 */233 public void stop() {234 if (containerId == null) {235 return;236 }237 String imageName;238 try {239 imageName = image.get();240 } catch (Exception e) {241 imageName = "<unknown>";242 }243 ResourceReaper.instance().stopAndRemoveContainer(containerId, imageName);244 }245 /**246 * Provide a logger that references the docker image name.247 *248 * @return a logger that references the docker image name249 */250 protected Logger logger() {251 return DockerLoggerFactory.getLogger(this.getDockerImageName());252 }253 /**254 * Creates a directory on the local filesystem which will be mounted as a volume for the container.255 *256 * @param temporary is the volume directory temporary? If true, the directory will be deleted on JVM shutdown.257 * @return path to the volume directory258 */259 protected Path createVolumeDirectory(boolean temporary) {260 Path directory = new File(".tmp-volume-" + System.currentTimeMillis()).toPath();261 PathUtils.mkdirp(directory);262 if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> {263 PathUtils.recursiveDeleteDir(directory);264 }));265 return directory;266 }267 protected void configure() {268 }269 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})270 protected void containerIsStarting(InspectContainerResponse containerInfo) {271 }272 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})273 protected void containerIsStarted(InspectContainerResponse containerInfo) {274 }275 /**276 * @return the port on which to check if the container is ready277 * @deprecated see {@link GenericContainer#getLivenessCheckPorts()} for replacement278 */279 @Deprecated280 protected Integer getLivenessCheckPort() {281 // legacy implementation for backwards compatibility282 if (exposedPorts.size() > 0) {283 return getMappedPort(exposedPorts.get(0));284 } else if (portBindings.size() > 0) {285 return Integer.valueOf(PortBinding.parse(portBindings.get(0)).getBinding().getHostPortSpec());286 } else {287 return null;288 }289 }290 /**291 * @return the ports on which to check if the container is ready292 * @deprecated use {@link #getLivenessCheckPortNumbers()} instead293 */294 @NotNull295 @NonNull296 @Deprecated297 protected Set<Integer> getLivenessCheckPorts() {298 final Set<Integer> result = WaitStrategyTarget.super.getLivenessCheckPortNumbers();299 // for backwards compatibility300 if (this.getLivenessCheckPort() != null) {301 result.add(this.getLivenessCheckPort());302 }303 return result;304 }305 @Override306 public Set<Integer> getLivenessCheckPortNumbers() {307 return this.getLivenessCheckPorts();308 }309 private void applyConfiguration(CreateContainerCmd createCommand) {310 // Set up exposed ports (where there are no host port bindings defined)311 ExposedPort[] portArray = exposedPorts.stream()312 .map(ExposedPort::new)313 .toArray(ExposedPort[]::new);314 createCommand.withExposedPorts(portArray);315 // Set up exposed ports that need host port bindings316 PortBinding[] portBindingArray = portBindings.stream()317 .map(PortBinding::parse)318 .toArray(PortBinding[]::new);319 createCommand.withPortBindings(portBindingArray);320 if (commandParts != null) {321 createCommand.withCmd(commandParts);322 }323 String[] envArray = env.entrySet().stream()324 .map(it -> it.getKey() + "=" + it.getValue())325 .toArray(String[]::new);326 createCommand.withEnv(envArray);327 Bind[] bindsArray = binds.stream()328 .toArray(Bind[]::new);329 createCommand.withBinds(bindsArray);330 VolumesFrom[] volumesFromsArray = volumesFroms.stream()331 .toArray(VolumesFrom[]::new);332 createCommand.withVolumesFrom(volumesFromsArray);333 Set<Link> allLinks = new HashSet<>();334 Set<String> allLinkedContainerNetworks = new HashSet<>();335 for (Map.Entry<String, LinkableContainer> linkEntries : linkedContainers.entrySet()) {336 String alias = linkEntries.getKey();337 LinkableContainer linkableContainer = linkEntries.getValue();338 Set<Link> links = findLinksFromThisContainer(alias, linkableContainer);339 allLinks.addAll(links);340 if (allLinks.size() == 0) {341 throw new ContainerLaunchException("Aborting attempt to link to container " +342 linkableContainer.getContainerName() +343 " as it is not running");344 }345 Set<String> linkedContainerNetworks = findAllNetworksForLinkedContainers(linkableContainer);346 allLinkedContainerNetworks.addAll(linkedContainerNetworks);347 }348 createCommand.withLinks(allLinks.toArray(new Link[allLinks.size()]));349 allLinkedContainerNetworks.remove("bridge");350 if (allLinkedContainerNetworks.size() > 1) {351 logger().warn("Container needs to be on more than one custom network to link to other " +352 "containers - this is not currently supported. Required networks are: {}",353 allLinkedContainerNetworks);354 }355 Optional<String> networkForLinks = allLinkedContainerNetworks.stream().findFirst();356 if (networkForLinks.isPresent()) {357 logger().debug("Associating container with network: {}", networkForLinks.get());358 createCommand.withNetworkMode(networkForLinks.get());359 }360 createCommand.withPublishAllPorts(true);361 String[] extraHostsArray = extraHosts.stream()362 .toArray(String[]::new);363 createCommand.withExtraHosts(extraHostsArray);364 if (network != null) {365 createCommand.withNetworkMode(network.getId());366 createCommand.withAliases(this.networkAliases);367 } else if (networkMode != null) {368 createCommand.withNetworkMode(networkMode);369 }370 if (workingDirectory != null) {371 createCommand.withWorkingDir(workingDirectory);372 }373 if (privilegedMode) {374 createCommand.withPrivileged(privilegedMode);375 }376 createContainerCmdModifiers.forEach(hook -> hook.accept(createCommand));377 Map<String, String> labels = createCommand.getLabels();378 labels = new HashMap<>(labels != null ? labels : Collections.emptyMap());379 labels.putAll(DockerClientFactory.DEFAULT_LABELS);380 createCommand.withLabels(labels);381 }382 private Set<Link> findLinksFromThisContainer(String alias, LinkableContainer linkableContainer) {383 return dockerClient.listContainersCmd()384 .withStatusFilter(Arrays.asList("running"))385 .exec().stream()386 .flatMap(container -> Stream.of(container.getNames()))387 .filter(name -> name.endsWith(linkableContainer.getContainerName()))388 .map(name -> new Link(name, alias))389 .collect(Collectors.toSet());390 }391 private Set<String> findAllNetworksForLinkedContainers(LinkableContainer linkableContainer) {392 return dockerClient.listContainersCmd().exec().stream()393 .filter(container -> container.getNames()[0].endsWith(linkableContainer.getContainerName()))394 .filter(container -> container.getNetworkSettings() != null &&395 container.getNetworkSettings().getNetworks() != null)396 .flatMap(container -> container.getNetworkSettings().getNetworks().keySet().stream())397 .distinct()398 .collect(Collectors.toSet());399 }400 /**401 * {@inheritDoc}402 */403 @Override404 public SELF waitingFor(@NonNull org.testcontainers.containers.wait.strategy.WaitStrategy waitStrategy) {405 this.waitStrategy = waitStrategy;406 return self();407 }408 /**409 * The {@link WaitStrategy} to use to determine if the container is ready.410 * Defaults to {@link Wait#defaultWaitStrategy()}.411 *412 * @return the {@link WaitStrategy} to use413 */414 protected org.testcontainers.containers.wait.strategy.WaitStrategy getWaitStrategy() {415 return waitStrategy;416 }417 @Override418 public void setWaitStrategy(org.testcontainers.containers.wait.strategy.WaitStrategy waitStrategy) {419 this.waitStrategy = waitStrategy;420 }421 /**422 * Wait until the container has started. The default implementation simply423 * waits for a port to start listening; other implementations are available424 * as implementations of {@link org.testcontainers.containers.wait.strategy.WaitStrategy}425 *426 * @see #waitingFor(org.testcontainers.containers.wait.strategy.WaitStrategy)427 */428 protected void waitUntilContainerStarted() {429 getWaitStrategy().waitUntilReady(this);430 }431 /**432 * {@inheritDoc}433 */434 @Override435 public void setCommand(@NonNull String command) {436 this.commandParts = command.split(" ");437 }438 /**439 * {@inheritDoc}440 */441 @Override442 public void setCommand(@NonNull String... commandParts) {443 this.commandParts = commandParts;444 }445 @Override446 public Map<String, String> getEnvMap() {447 return env;448 }449 /**450 * {@inheritDoc}451 */452 @Override453 public List<String> getEnv() {454 return env.entrySet().stream()455 .map(it -> it.getKey() + "=" + it.getValue())456 .collect(Collectors.toList());457 }458 @Override459 public void setEnv(List<String> env) {460 this.env = env.stream()461 .map(it -> it.split("="))462 .collect(Collectors.toMap(463 it -> it[0],464 it -> it[1]465 ));466 }467 /**468 * {@inheritDoc}469 */470 @Override471 public void addEnv(String key, String value) {472 env.put(key, value);473 }474 /**475 * {@inheritDoc}476 */477 @Override478 public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) {479 final MountableFile mountableFile = MountableFile.forHostPath(hostPath);480 binds.add(new Bind(mountableFile.getResolvedPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext));481 }482 /**483 * {@inheritDoc}484 */485 @Override486 public SELF withFileSystemBind(String hostPath, String containerPath, BindMode mode) {487 addFileSystemBind(hostPath, containerPath, mode);488 return self();489 }490 /**491 * {@inheritDoc}492 */493 @Override494 public SELF withVolumesFrom(Container container, BindMode mode) {495 addVolumesFrom(container, mode);496 return self();497 }498 private void addVolumesFrom(Container container, BindMode mode) {499 volumesFroms.add(new VolumesFrom(container.getContainerName(), mode.accessMode));500 }501 /**502 * @deprecated Links are deprecated (see <a href="https://github.com/testcontainers/testcontainers-java/issues/465">#465</a>). Please use {@link Network} features instead.503 */504 @Deprecated505 @Override506 public void addLink(LinkableContainer otherContainer, String alias) {507 this.linkedContainers.put(alias, otherContainer);508 }509 @Override510 public void addExposedPort(Integer port) {511 exposedPorts.add(port);512 }513 @Override514 public void addExposedPorts(int... ports) {515 for (int port : ports) {516 exposedPorts.add(port);517 }518 }519 @Override520 protected void starting(Description description) {521 this.start();522 }523 @Override524 protected void finished(Description description) {525 this.stop();526 }527 /**528 * {@inheritDoc}529 */530 @Override531 public SELF withExposedPorts(Integer... ports) {532 this.setExposedPorts(newArrayList(ports));533 return self();534 }535 /**536 * Add a TCP container port that should be bound to a fixed port on the docker host.537 * <p>538 * Note that this method is protected scope to discourage use, as clashes or instability are more likely when539 * using fixed port mappings. If you need to use this method from a test, please use {@link FixedHostPortGenericContainer}540 * instead of GenericContainer.541 *542 * @param hostPort543 * @param containerPort544 */545 protected void addFixedExposedPort(int hostPort, int containerPort) {546 addFixedExposedPort(hostPort, containerPort, InternetProtocol.TCP);547 }548 /**549 * Add a container port that should be bound to a fixed port on the docker host.550 * <p>551 * Note that this method is protected scope to discourage use, as clashes or instability are more likely when552 * using fixed port mappings. If you need to use this method from a test, please use {@link FixedHostPortGenericContainer}553 * instead of GenericContainer.554 *555 * @param hostPort556 * @param containerPort557 * @param protocol558 */559 protected void addFixedExposedPort(int hostPort, int containerPort, InternetProtocol protocol) {560 portBindings.add(String.format("%d:%d/%s", hostPort, containerPort, protocol.toDockerNotation()));561 }562 /**563 * {@inheritDoc}564 */565 @Override566 public SELF withEnv(String key, String value) {567 this.addEnv(key, value);568 return self();569 }570 /**571 * {@inheritDoc}572 */573 @Override574 public SELF withEnv(Map<String, String> env) {575 env.forEach(this::addEnv);576 return self();577 }578 /**579 * {@inheritDoc}580 */581 @Override582 public SELF withCommand(String cmd) {583 this.setCommand(cmd);584 return self();585 }586 /**587 * {@inheritDoc}588 */589 @Override590 public SELF withCommand(String... commandParts) {591 this.setCommand(commandParts);592 return self();593 }594 /**595 * {@inheritDoc}596 */597 @Override598 public SELF withExtraHost(String hostname, String ipAddress) {599 this.extraHosts.add(String.format("%s:%s", hostname, ipAddress));600 return self();601 }602 @Override603 public SELF withNetworkMode(String networkMode) {604 this.networkMode = networkMode;605 return self();606 }607 @Override608 public SELF withNetwork(Network network) {609 this.network = network;610 return self();611 }612 @Override613 public SELF withNetworkAliases(String... aliases) {614 Collections.addAll(this.networkAliases, aliases);615 return self();616 }617 /**618 * {@inheritDoc}619 */620 @Override621 public SELF withClasspathResourceMapping(final String resourcePath, final String containerPath, final BindMode mode) {622 return withClasspathResourceMapping(resourcePath, containerPath, mode, SelinuxContext.NONE);623 }624 /**625 * {@inheritDoc}626 */627 @Override628 public SELF withClasspathResourceMapping(final String resourcePath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) {629 final MountableFile mountableFile = MountableFile.forClasspathResource(resourcePath);630 this.addFileSystemBind(mountableFile.getResolvedPath(), containerPath, mode, selinuxContext);631 return self();632 }633 /**634 * {@inheritDoc}635 */636 @Override637 public SELF withStartupTimeout(Duration startupTimeout) {638 getWaitStrategy().withStartupTimeout(startupTimeout);639 return self();640 }641 @Override642 public SELF withPrivilegedMode(boolean mode) {643 this.privilegedMode = mode;644 return self();645 }646 /**647 * {@inheritDoc}648 */649 @Override650 public SELF withMinimumRunningDuration(Duration minimumRunningDuration) {651 this.startupCheckStrategy = new MinimumDurationRunningStartupCheckStrategy(minimumRunningDuration);652 return self();653 }654 /**655 * {@inheritDoc}656 */657 @Override658 public SELF withStartupCheckStrategy(StartupCheckStrategy strategy) {659 this.startupCheckStrategy = strategy;660 return self();661 }662 /**663 * {@inheritDoc}664 */665 @Override666 public SELF withWorkingDirectory(String workDir) {667 this.setWorkingDirectory(workDir);668 return self();669 }670 /**671 * Get the IP address that this container may be reached on (may not be the local machine).672 *673 * @return an IP address674 * @deprecated please use getContainerIpAddress() instead675 */676 @Deprecated677 public String getIpAddress() {678 return getContainerIpAddress();679 }680 /**681 * {@inheritDoc}682 */683 @Override684 public void setDockerImageName(@NonNull String dockerImageName) {685 this.image = new RemoteDockerImage(dockerImageName);686 // Mimic old behavior where we resolve image once it's set687 getDockerImageName();688 }689 /**690 * {@inheritDoc}691 */692 @Override693 @NonNull694 public String getDockerImageName() {695 try {696 return image.get();697 } catch (Exception e) {698 throw new ContainerFetchException("Can't get Docker image: " + image, e);699 }700 }701 /**702 * {@inheritDoc}703 */704 @Override705 public String getTestHostIpAddress() {706 if (DockerMachineClient.instance().isInstalled()) {707 try {708 Optional<String> defaultMachine = DockerMachineClient.instance().getDefaultMachine();709 if (!defaultMachine.isPresent()) {710 throw new IllegalStateException("Could not find a default docker-machine instance");711 }712 String sshConnectionString = runShellCommand("docker-machine", "ssh", defaultMachine.get(), "echo $SSH_CONNECTION").trim();713 if (Strings.isNullOrEmpty(sshConnectionString)) {714 throw new IllegalStateException("Could not obtain SSH_CONNECTION environment variable for docker machine " + defaultMachine.get());715 }716 String[] sshConnectionParts = sshConnectionString.split("\\s");717 if (sshConnectionParts.length != 4) {718 throw new IllegalStateException("Unexpected pattern for SSH_CONNECTION for docker machine - expected 'IP PORT IP PORT' pattern but found '" + sshConnectionString + "'");719 }720 return sshConnectionParts[0];721 } catch (Exception e) {722 throw new RuntimeException(e);723 }724 } else {725 throw new UnsupportedOperationException("getTestHostIpAddress() is only implemented for docker-machine right now");726 }727 }728 /**729 * {@inheritDoc}730 */731 @Override732 public SELF withLogConsumer(Consumer<OutputFrame> consumer) {733 this.logConsumers.add(consumer);734 return self();735 }736 /**737 * {@inheritDoc}738 */739 @Override740 public synchronized Info fetchDockerDaemonInfo() throws IOException {741 if (this.dockerDaemonInfo == null) {742 this.dockerDaemonInfo = this.dockerClient.infoCmd().exec();743 }744 return this.dockerDaemonInfo;745 }746 /**747 * {@inheritDoc}748 */749 @Override750 public ExecResult execInContainer(String... command)751 throws UnsupportedOperationException, IOException, InterruptedException {752 return execInContainer(UTF8, command);753 }754 /**755 * {@inheritDoc}756 */757 @Override758 public void copyFileToContainer(MountableFile mountableLocalFile, String containerPath) {759 if (!isRunning()) {760 throw new IllegalStateException("copyFileToContainer can only be used while the Container is running");761 }762 this.dockerClient763 .copyArchiveToContainerCmd(this.containerId)764 .withHostResource(mountableLocalFile.getResolvedPath())765 .withRemotePath(containerPath)766 .exec();767 }768 /**769 * {@inheritDoc}770 */771 @Override772 public void copyFileFromContainer(String containerPath, String destinationPath) throws IOException {773 if (!isRunning()) {774 throw new IllegalStateException("copyFileToContainer can only be used while the Container is running");775 }776 try (final TarArchiveInputStream tarInputStream = new TarArchiveInputStream(this.dockerClient777 .copyArchiveFromContainerCmd(this.containerId, containerPath)778 .exec())) {779 tarInputStream.getNextTarEntry();780 IOUtils.copy(tarInputStream, new FileOutputStream(destinationPath));781 }782 }783 /**784 * {@inheritDoc}785 */786 @Override787 public ExecResult execInContainer(Charset outputCharset, String... command)788 throws UnsupportedOperationException, IOException, InterruptedException {789 return ExecInContainerPattern.execInContainer(getContainerInfo(), outputCharset, command);790 }791 /**792 * Allow container startup to be attempted more than once if an error occurs. To be if containers are793 * 'flaky' but this flakiness is not something that should affect test outcomes.794 *795 * @param attempts number of attempts796 */797 public SELF withStartupAttempts(int attempts) {798 this.startupAttempts = attempts;799 return self();800 }801 @Override802 public void close() {803 stop();804 }805 /**806 * Allow low level modifications of {@link CreateContainerCmd} after it was pre-configured in {@link #tryStart(Profiler)}.807 * Invocation happens eagerly on a moment when container is created.808 * Warning: this does expose the underlying docker-java API so might change outside of our control.809 *810 * @param modifier {@link Consumer} of {@link CreateContainerCmd}.811 * @return this812 */813 public SELF withCreateContainerCmdModifier(Consumer<CreateContainerCmd> modifier) {814 createContainerCmdModifiers.add(modifier);815 return self();816 }817 /**818 * Convenience class with access to non-public members of GenericContainer.819 *820 * @deprecated use {@link org.testcontainers.containers.wait.strategy.AbstractWaitStrategy}...

Full Screen

Full Screen

Source:ProxyServerLauncher.java Github

copy

Full Screen

...42 }43 44 45 @Test46 void tryStart() {47 48 }49}...

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.output.OutputFrame;3import org.testcontainers.containers.output.ToStringConsumer;4import org.testcontainers.containers.output.WaitingConsumer;5import org.testcontainers.containers.wait.strategy.Wait;6import org.testcontainers.utility.DockerImageName;7public class TestContainer {8 public static void main(String[] args) throws Exception {9 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:3.13.5"))10 .withCommand("echo", "hello")11 .waitingFor(Wait.forLogMessage("hello", 1));12 try (WaitingConsumer consumer = new WaitingConsumer()) {13 container.followOutput(consumer);14 container.start();15 consumer.waitUntil(frame -> frame.getUtf8String().contains("hello"));16 }17 }18}19import org.testcontainers.containers.GenericContainer;20import org.testcontainers.containers.output.OutputFrame;21import org.testcontainers.containers.output.ToStringConsumer;22import org.testcontainers.containers.output.WaitingConsumer;23import org.testcontainers.utility.DockerImageName;24public class TestContainer {25 public static void main(String[] args) throws Exception {26 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:3.13.5"))27 .withCommand("echo", "hello")28 .waitingFor(Wait.forLogMessage("hello", 1));29 try (WaitingConsumer consumer = new WaitingConsumer()) {30 container.followOutput(consumer);31 container.start();32 consumer.waitUntil(frame -> frame.getUtf8String().contains("hello"));33 }34 }35}36import org.testcontainers.containers.GenericContainer;37import org.testcontainers.containers.output.OutputFrame;38import org.testcontainers.containers.output.ToStringConsumer;39import org.testcontainers.containers.output.WaitingConsumer;40import org.testcontainers.utility.DockerImageName;41public class TestContainer {42 public static void main(String[] args) throws Exception {43 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:3.13.5"))44 .withCommand("echo", "hello")45 .waitingFor(Wait.forLogMessage("hello", 1));46 try (WaitingConsumer consumer = new Waiting

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.startupcheck.IsRunningStartupCheckStrategy;3import org.testcontainers.utility.DockerImageName;4public class Test1 {5 public static void main(String[] args) {6 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:latest"))7 .withStartupCheckStrategy(new IsRunningStartupCheckStrategy())8 .withCommand("sleep", "1000");9 if (container.tryStart()) {10 System.out.println("Container started successfully");11 }12 }13}14import org.testcontainers.containers.GenericContainer;15import org.testcontainers.containers.startupcheck.IsRunningStartupCheckStrategy;16import org.testcontainers.utility.DockerImageName;17public class Test2 {18 public static void main(String[] args) {19 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:latest"))20 .withStartupCheckStrategy(new IsRunningStartupCheckStrategy())21 .withCommand("sleep", "1000");22 if (container.tryStart()) {23 System.out.println("Container started successfully");24 }25 container.stop();26 }27}28import org.testcontainers.containers.GenericContainer;29import org.testcontainers.containers.startupcheck.IsRunningStartupCheckStrategy;30import org.testcontainers.utility.DockerImageName;31public class Test3 {32 public static void main(String[] args) {33 GenericContainer container = new GenericContainer(DockerImageName.parse

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2public class TestContainer {3 public static void main(String[] args) {4 GenericContainer container = new GenericContainer("alpine:3.8");5 container.withCommand("sleep", "1000");6 container.start();7 System.out.println("Container started");8 }9}10import org.testcontainers.containers.GenericContainer;11public class TestContainer {12 public static void main(String[] args) {13 GenericContainer container = new GenericContainer("alpine:3.8");14 container.withCommand("sleep", "1000");15 boolean started = container.tryStart();16 if (started) {17 System.out.println("Container started");18 } else {19 System.out.println("Container already started");20 }21 }22}23import org.testcontainers.containers.GenericContainer;24public class TestContainer {25 public static void main(String[] args) {26 GenericContainer container = new GenericContainer("alpine:3.8");27 container.withCommand("sleep", "1000");28 boolean started = container.tryStart();29 if (started) {30 System.out.println("Container started");31 } else {32 System.out.println("Container already started");33 }34 container.stop();35 }36}

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2public class TestContainer {3 public static void main(String[] args) {4 GenericContainer container = new GenericContainer("alpine:3.7");5 container.start();6 System.out.println("Container started");7 container.stop();8 System.out.println("Container stopped");9 }10}11import org.testcontainers.containers.GenericContainer;12public class TestContainer {13 public static void main(String[] args) {14 GenericContainer container = new GenericContainer("alpine:3.7");15 container.start();16 System.out.println("Container started");17 container.stop();18 System.out.println("Container stopped");19 }20}21import org.testcontainers.containers.GenericContainer;22public class TestContainer {23 public static void main(String[] args) {24 GenericContainer container = new GenericContainer("alpine:3.7");25 container.start();26 System.out.println("Container started");27 container.stop();28 System.out.println("Container stopped");29 }30}31import org.testcontainers.containers.GenericContainer;32public class TestContainer {33 public static void main(String[] args) {34 GenericContainer container = new GenericContainer("alpine:3.7");35 container.start();36 System.out.println("Container started");37 container.stop();38 System.out.println("Container stopped");39 }40}41import org.testcontainers.containers.GenericContainer;42public class TestContainer {43 public static void main(String[] args) {44 GenericContainer container = new GenericContainer("alpine:3.7");45 container.start();46 System.out.println("Container started");47 container.stop();48 System.out.println("Container stopped");49 }50}51import org.testcontainers.containers.GenericContainer;52public class TestContainer {53 public static void main(String[] args) {54 GenericContainer container = new GenericContainer("alpine:3.7");55 container.start();56 System.out.println("Container started");57 container.stop();58 System.out.println("Container stopped");59 }60}

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import com.github.dockerjava.api.DockerClient;3import com.github.dockerjava.api.command.CreateContainerCmd;4import com.github.dockerjava.api.exception.DockerException;5import com.github.dockerjava.api.model.Container;6import com.github.dockerjava.api.model.ExposedPort;7import com.github.dockerjava.api.model.Ports;8import com.github.dockerjava.core.command.PullImageResultCallback;9import org.slf4j.Logger;10import org.slf4j.LoggerFactory;11import org.testcontainers.DockerClientFactory;12import org.testcontainers.containers.output.OutputFrame;13import org.testcontainers.containers.output.ToStringConsumer;14import org.testcontainers.containers.wait.strategy.WaitStrategy;15import org.testcontainers.containers.wait.strategy.WaitStrategyTarget;16import org.testcontainers.utility.Base58;17import org.testcontainers.utility.DockerImageName;18import org.testcontainers.utility.TestcontainersConfiguration;19import org.testcontainers.utility.TestcontainersConfiguration.InstanceConfiguration;20import org.testcontainers.utility.TestcontainersConfiguration.StrategyConfiguration;21import org.testcontainers.utility.TestcontainersConfiguration.StrategyConfiguration.Strategy;22import java.io.IOException;23import java.time.Duration;24import java.util.*;25import java.util.concurrent.*;26import java.util.concurrent.atomic.AtomicBoolean;27import java.util.function.Consumer;28import java.util.function.Function;29import java.util.stream.Collectors;30import static java.util.concurrent.TimeUnit.SECONDS;31import static org.testcontainers.DockerClientFactory.DEFAULT_DOCKER_CLIENT_STRATEGY;32import static org.testcontainers.DockerClientFactory.TESTCONTAINERS_SESSION_ID;33import static org.testcontainers.DockerClientFactory.TESTCONTAINERS_SESSION_OVERRIDE_ENABLED;34import static org.testcontainers.containers.ContainerState.STARTED;35import static org.testcontainers.containers.ContainerState.STOPPED;36import static org.testcontainers.containers.ContainerState.UNDEFINED;37import static org.testcontainers.utility.DockerImageName.parse;38Container<SELF> implements WaitStrategyTarget {39 private static final Logger log = LoggerFactory.getLogger(GenericContainer.class);40 private static final String DOCKER_IMAGE_NAME = "dockerImageName";41 private static final String LINK_LOCALHOST = "linkLocalhost";42 private static final String NETWORK_MODE = "networkMode";43 private static final String NETWORKING_MODE = "networkingMode";44 private static final String NETWORK_ALIASES = "networkAliases";45 private static final String NETWORKS = "networks";

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import org.testcontainers.containers.GenericContainer;3public class TryStart {4 public static void main(String[] args) throws IOException, InterruptedException {5 GenericContainer container = new GenericContainer("alpine:3.5");6 container.withCommand("sleep 1000");7 boolean started = container.tryStart();8 System.out.println("Container started: " + started);9 container.stop();10 }11}

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2public class 1 {3 public static void main(String[] args) {4 try (GenericContainer container = new GenericContainer("alpine:3.7")) {5 container.withCommand("sleep", "100000");6 container.tryStart();7 container.tryStop();8 }9 }10}112. tryStart() method with timeout12import org.testcontainers.containers.GenericContainer;13public class 2 {14 public static void main(String[] args) {15 try (GenericContainer container = new GenericContainer("alpine:3.7")) {16 container.withCommand("sleep", "100000");17 container.tryStart(1000);18 container.tryStop();19 }20 }21}223. tryStart() method with timeout and timeunit23import org.testcontainers.containers.GenericContainer;24public class 3 {25 public static void main(String[] args) {26 try (GenericContainer container = new GenericContainer("alpine:3.7")) {27 container.withCommand("sleep", "100000");28 container.tryStart(1, TimeUnit.MILLISECONDS);29 container.tryStop();30 }31 }32}

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.containers;2import org.testcontainers.containers.output.OutputFrame;3import org.testcontainers.containers.output.WaitingConsumer;4import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy;5import org.testcontainers.utility.TestcontainersConfiguration;6import java.util.concurrent.TimeUnit;7public class CustomCommand {8public static void main(String[] args) throws Exception {9 String command = "echo 'Hello World'";10 String containerName = "test";11 String image = "alpine:3.10.2";12 String expectedOutput = "Hello World";13 try (GenericContainer container = new GenericContainer(image).withCommand(command)) {14 container.setWaitStrategy(new OneShotStartupCheckStrategy());15 WaitingConsumer waitingConsumer = new WaitingConsumer();16 container.followOutput(waitingConsumer);17 container.start();18 OutputFrame outputFrame = waitingConsumer.waitUntil(frame -> frame.getUtf8String().contains(expectedOutput), 10, TimeUnit.SECONDS);19 if (outputFrame == null) {20 throw new IllegalStateException("Expected output not found");21 }22 }23}24}25package org.testcontainers.containers;26import java.util.Arrays;27import java.util.List;28public class CustomCommand2 {29 public static void main(String[] args) {30 String command = "echo 'Hello World'";31 String containerName = "test";32 String image = "alpine:3.10.2";33 String expectedOutput = "Hello World";34 try (GenericContainer container = new GenericContainer(image).withCommand(command)) {35 container.start();36 List<String> logs = container.getLogs();37 System.out.println(Arrays.toString(logs.toArray()));38 }39 }40}41package org.testcontainers.containers;42import com.github.dockerjava.api.command.CreateContainerCmd;43import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy;44import java.util.Arrays;45import java.util.List;46public class CustomCommand3 {47 public static void main(String48}

Full Screen

Full Screen

tryStart

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer;2public class 1 {3 public static void main(String[] args) {4 try (GenericContainer container = new GenericContainer("alpine:3.7")) {5 container.withCommand("sleep", "100000");6 container.tryStart();7 container.tryStop();8 }9 }10}112. tryStart() method with timeout12import org.testcontainers.containers.GenericContainer;13public class 2 {14 public static void main(String[] args) {15 try (GenericContainer container = new GenericContainer("alpine:3.7")) {16 container.withCommand("sleep", "100000");17 container.tryStart(1000);18 container.tryStop();19 }20 }21}223. tryStart() method with timeout and timeunit23import org.testcontainers.containers.GenericContainer;24public class 3 {25 public static void main(String[] args) {26 try (GenericContainer container = new GenericContainer("alpine:3.7")) {27 container.withCommand("sleep", "100000");28 container.tryStart(1, TimeUnit.MILLISECONDS);29 container.tryStop();30 }31 }32}

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