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

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

Source:GenericContainer.java Github

copy

Full Screen

...310 containerId = createCommand.exec().getId();311 // TODO use single "copy" invocation (and calculate an hash of the resulting tar archive)312 copyToFileContainerPathMap.forEach(this::copyFileToContainer);313 }314 connectToPortForwardingNetwork(createCommand.getNetworkMode());315 if (!reused) {316 containerIsCreated(containerId);317 logger().info("Starting container with ID: {}", containerId);318 dockerClient.startContainerCmd(containerId).exec();319 }320 logger().info("Container {} is starting: {}", dockerImageName, containerId);321 // For all registered output consumers, start following as close to container startup as possible322 this.logConsumers.forEach(this::followOutput);323 // Wait until inspect container returns the mapped ports324 containerInfo = await()325 .atMost(5, TimeUnit.SECONDS)326 .pollInterval(DynamicPollInterval.ofMillis(50))327 .pollInSameThread()328 .until(329 () -> dockerClient.inspectContainerCmd(containerId).exec(),330 inspectContainerResponse -> {331 Set<Integer> exposedAndMappedPorts = inspectContainerResponse332 .getNetworkSettings()333 .getPorts()334 .getBindings()335 .entrySet()336 .stream()337 .filter(it -> Objects.nonNull(it.getValue())) // filter out exposed but not yet mapped338 .map(Entry::getKey)339 .map(ExposedPort::getPort)340 .collect(Collectors.toSet());341 return exposedAndMappedPorts.containsAll(exposedPorts);342 }343 );344 // Tell subclasses that we're starting345 containerIsStarting(containerInfo, reused);346 // Wait until the container has reached the desired running state347 if (!this.startupCheckStrategy.waitUntilStartupSuccessful(dockerClient, containerId)) {348 // Bail out, don't wait for the port to start listening.349 // (Exception thrown here will be caught below and wrapped)350 throw new IllegalStateException("Container did not start correctly.");351 }352 // Wait until the process within the container has become ready for use (e.g. listening on network, log message emitted, etc).353 try {354 waitUntilContainerStarted();355 } catch (Exception e) {356 logger().debug("Wait strategy threw an exception", e);357 InspectContainerResponse inspectContainerResponse = null;358 try {359 inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec();360 } catch (NotFoundException notFoundException) {361 logger().debug("Container {} not found", containerId, notFoundException);362 }363 if (inspectContainerResponse == null) {364 throw new IllegalStateException("Container is removed");365 }366 InspectContainerResponse.ContainerState state = inspectContainerResponse.getState();367 if (Boolean.TRUE.equals(state.getDead())) {368 throw new IllegalStateException("Container is dead");369 }370 if (Boolean.TRUE.equals(state.getOOMKilled())) {371 throw new IllegalStateException("Container crashed with out-of-memory (OOMKilled)");372 }373 String error = state.getError();374 if (!StringUtils.isBlank(error)) {375 throw new IllegalStateException("Container crashed: " + error);376 }377 if (!Boolean.TRUE.equals(state.getRunning())) {378 throw new IllegalStateException("Container exited with code " + state.getExitCode());379 }380 throw e;381 }382 logger().info("Container {} started in {}", dockerImageName, Duration.between(startedAt, Instant.now()));383 containerIsStarted(containerInfo, reused);384 } catch (Exception e) {385 if (e instanceof UndeclaredThrowableException && e.getCause() instanceof Exception) {386 e = (Exception) e.getCause();387 }388 if (e instanceof InvocationTargetException && e.getCause() instanceof Exception) {389 e = (Exception) e.getCause();390 }391 logger().error("Could not start container", e);392 if (containerId != null) {393 // Log output if startup failed, either due to a container failure or exception (including timeout)394 final String containerLogs = getLogs();395 if (containerLogs.length() > 0) {396 logger().error("Log output from the failed container:\n{}", getLogs());397 } else {398 logger().error("There are no stdout/stderr logs available for the failed container");399 }400 }401 throw new ContainerLaunchException("Could not create/start container", e);402 }403 }404 @VisibleForTesting405 Checksum hashCopiedFiles() {406 Checksum checksum = new Adler32();407 copyToFileContainerPathMap.entrySet().stream().sorted(Entry.comparingByValue()).forEach(entry -> {408 byte[] pathBytes = entry.getValue().getBytes();409 // Add path to the hash410 checksum.update(pathBytes, 0, pathBytes.length);411 File file = new File(entry.getKey().getResolvedPath());412 checksumFile(file, checksum);413 });414 return checksum;415 }416 @VisibleForTesting417 @SneakyThrows(IOException.class)418 void checksumFile(File file, Checksum checksum) {419 Path path = file.toPath();420 checksum.update(MountableFile.getUnixFileMode(path));421 if (file.isDirectory()) {422 try (Stream<Path> stream = Files.walk(path)) {423 stream.filter(it -> it != path).forEach(it -> {424 checksumFile(it.toFile(), checksum);425 });426 }427 } else {428 FileUtils.checksum(file, checksum);429 }430 }431 @UnstableAPI432 @SneakyThrows(JsonProcessingException.class)433 final String hash(CreateContainerCmd createCommand) {434 DefaultDockerClientConfig dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder().build();435 byte[] commandJson = dockerClientConfig.getObjectMapper()436 .copy()437 .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)438 .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)439 .writeValueAsBytes(createCommand);440 // TODO add Testcontainers' version to the hash441 return Hashing.sha1().hashBytes(commandJson).toString();442 }443 @VisibleForTesting444 Optional<String> findContainerForReuse(String hash) {445 // TODO locking446 return dockerClient.listContainersCmd()447 .withLabelFilter(ImmutableMap.of(HASH_LABEL, hash))448 .withLimit(1)449 .withStatusFilter(Arrays.asList("running"))450 .exec()451 .stream()452 .findAny()453 .map(it -> it.getId());454 }455 /**456 * Set any custom settings for the create command such as shared memory size.457 */458 private HostConfig buildHostConfig() {459 HostConfig config = new HostConfig();460 if (shmSize != null) {461 config.withShmSize(shmSize);462 }463 if (tmpFsMapping != null) {464 config.withTmpFs(tmpFsMapping);465 }466 return config;467 }468 private void connectToPortForwardingNetwork(String networkMode) {469 PortForwardingContainer.INSTANCE.getNetwork().map(ContainerNetwork::getNetworkID).ifPresent(networkId -> {470 if (!Arrays.asList(networkId, "none", "host").contains(networkMode)) {471 dockerClient.connectToNetworkCmd().withContainerId(containerId).withNetworkId(networkId).exec();472 }473 });474 }475 /**476 * Stops the container.477 */478 @Override479 public void stop() {480 if (containerId == null) {481 return;482 }...

Full Screen

Full Screen

connectToPortForwardingNetwork

Using AI Code Generation

copy

Full Screen

1val container = new GenericContainer("busybox:1.28")2container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")3container.withExposedPorts(8080)4container.start()5val port = container.getMappedPort(8080)6val host = container.getContainerIpAddress()7println(url)8container.stop()9val network = Network.newNetwork()10val container = new GenericContainer("busybox:1.28")11container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")12container.withExposedPorts(8080)13container.withNetwork(network)14container.withNetworkAliases("myalias")15container.start()16val port = container.getMappedPort(8080)17val host = container.getContainerIpAddress()18println(url)19container.stop()20network.close()21val container = new MySQLContainer()22container.start()23val port = container.getMappedPort(3306)24val host = container.getContainerIpAddress()25println(url)26container.stop()27val container = new GenericContainer("busybox:1.28")28container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")29container.withExposedPorts(8080)30container.waitingFor(Wait.forListeningPort())31container.start()32val port = container.getMappedPort(8080)33val host = container.getContainerIpAddress()34println(url)35container.stop()36val container = new GenericContainer("busybox:1.28")37container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")38container.withExposedPorts(8080)39container.waitingFor(new AbstractWaitStrategy() {40 override def waitUntilReady(): Unit = {41 }42})

Full Screen

Full Screen

connectToPortForwardingNetwork

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer2import org.testcontainers.containers.wait.strategy.Wait3import org.testcontainers.utility.DockerImageName4import org.testcontainers.utility.MountableFile5val container = GenericContainer(DockerImageName.parse("alpine:3.12"))6container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")7container.waitingFor(Wait.forLogMessage(".*hello.*", 1))8container.start()9container.connectToPortForwardingNetwork(80)10container.getMappedPort(80)11container.stop()12val container = GenericContainer(DockerImageName.parse("alpine:3.12"))13container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")14container.waitingFor(Wait.forLogMessage(".*hello.*", 1))15container.start()16container.connectToPortForwardingNetwork(80)17container.getMappedPort(80)18container.stop()19val container = GenericContainer(DockerImageName.parse("alpine:3.12"))20container.withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")21container.waitingFor(Wait.forLogMessage(".*hello.*", 1))22container.start()23container.connectToPortForwardingNetwork(80)24container.getMappedPort(80)25container.stop()26val container = GenericContainer(DockerImageName.parse("alpine:3.12"))

Full Screen

Full Screen

connectToPortForwardingNetwork

Using AI Code Generation

copy

Full Screen

1dependencies {2}3repositories {4 maven {5 }6}7java.lang.NoSuchMethodError: org.testcontainers.containers.GenericContainer.connectToPortForwardingNetwork()Lorg/testcontainers/containers/GenericContainer;8import org.junit.jupiter.api.Test;9import org.junit.jupiter.api.extension.ExtendWith;10import org.springframework.boot.test.context.SpringBootTest;11import org.springframework.test.context.junit.jupiter.SpringExtension;12import org.testcontainers.containers.GenericContainer;13@ExtendWith(SpringExtension.class)14public class TestcontainersTests {15 public void test() {16 GenericContainer<?> container = new GenericContainer<>("alpine:latest");17 container.withCommand("sleep", "100000");18 container.start();19 }20}21java.lang.NoSuchMethodError: org.testcontainers.containers.GenericContainer.withCommand([Ljava/lang/String;)Lorg/testcontainers/containers/GenericContainer;22dependencies {23}24repositories {25 maven {26 }27}

Full Screen

Full Screen

connectToPortForwardingNetwork

Using AI Code Generation

copy

Full Screen

1def container = new GenericContainer("alpine:latest")2container.withCommand("tail", "-f", "/dev/null")3container.start()4container.connectToPortForwardingNetwork()5def container = new GenericContainer("alpine:latest")6container.withCommand("tail", "-f", "/dev/null")7container.withNetwork(Network.newNetwork())8container.start()9container.connectToPortForwardingNetwork()10def container = new GenericContainer("alpine:latest")11container.withCommand("tail", "-f", "/dev/null")12def container = new GenericContainer("alpine:latest")13container.withCommand("tail", "-f", "/dev/null")14container.withNetwork(Network.newNetwork())15container.start()16container.connectToPortForwardingNetwork()17def container = new GenericContainer("alpine:latest")18container.withCommand("tail", "-f", "/dev/null")19container.withNetwork(Network.newNetwork())20container.start()21container.connectToPortForwardingNetwork()

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