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

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

Source:GenericContainer.java Github

copy

Full Screen

...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 }483 try {484 String imageName;485 try {486 imageName = getDockerImageName();487 } catch (Exception e) {488 imageName = "<unknown>";489 }490 containerIsStopping(containerInfo);491 ResourceReaper.instance().stopAndRemoveContainer(containerId, imageName);492 containerIsStopped(containerInfo);493 } finally {494 containerId = null;495 containerInfo = null;496 }497 }498 /**499 * Provide a logger that references the docker image name.500 *501 * @return a logger that references the docker image name502 */503 protected Logger logger() {504 return DockerLoggerFactory.getLogger(this.getDockerImageName());505 }506 /**507 * Creates a directory on the local filesystem which will be mounted as a volume for the container.508 *509 * @param temporary is the volume directory temporary? If true, the directory will be deleted on JVM shutdown.510 * @return path to the volume directory511 */512 @Deprecated513 protected Path createVolumeDirectory(boolean temporary) {514 Path directory = new File(".tmp-volume-" + UUID.randomUUID()).toPath();515 PathUtils.mkdirp(directory);516 if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> {517 PathUtils.recursiveDeleteDir(directory);518 }));519 return directory;520 }521 protected void configure() {522 }523 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})524 protected void containerIsCreated(String containerId) {525 }526 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})527 protected void containerIsStarting(InspectContainerResponse containerInfo) {528 }529 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})530 @UnstableAPI531 protected void containerIsStarting(InspectContainerResponse containerInfo, boolean reused) {532 containerIsStarting(containerInfo);533 }534 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})535 protected void containerIsStarted(InspectContainerResponse containerInfo) {536 }537 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})538 @UnstableAPI539 protected void containerIsStarted(InspectContainerResponse containerInfo, boolean reused) {540 containerIsStarted(containerInfo);541 }542 /**543 * A hook that is executed before the container is stopped with {@link #stop()}.544 * Warning! This hook won't be executed if the container is terminated during545 * the JVM's shutdown hook or by Ryuk.546 */547 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})548 protected void containerIsStopping(InspectContainerResponse containerInfo) {549 }550 /**551 * A hook that is executed after the container is stopped with {@link #stop()}.552 * Warning! This hook won't be executed if the container is terminated during553 * the JVM's shutdown hook or by Ryuk.554 */555 @SuppressWarnings({"EmptyMethod", "UnusedParameters"})556 protected void containerIsStopped(InspectContainerResponse containerInfo) {557 }558 /**559 * @return the port on which to check if the container is ready560 * @deprecated see {@link GenericContainer#getLivenessCheckPorts()} for replacement561 */562 @Deprecated563 protected Integer getLivenessCheckPort() {564 // legacy implementation for backwards compatibility565 Iterator<Integer> exposedPortsIterator = exposedPorts.iterator();566 if (exposedPortsIterator.hasNext()) {567 return getMappedPort(exposedPortsIterator.next());568 } else if (portBindings.size() > 0) {569 return Integer.valueOf(PortBinding.parse(portBindings.get(0)).getBinding().getHostPortSpec());570 } else {571 return null;572 }573 }574 /**575 * @return the ports on which to check if the container is ready576 * @deprecated use {@link #getLivenessCheckPortNumbers()} instead577 */578 @NotNull579 @NonNull580 @Deprecated581 protected Set<Integer> getLivenessCheckPorts() {582 final Set<Integer> result = WaitStrategyTarget.super.getLivenessCheckPortNumbers();583 // for backwards compatibility584 if (this.getLivenessCheckPort() != null) {585 result.add(this.getLivenessCheckPort());586 }587 return result;588 }589 @Override590 public Set<Integer> getLivenessCheckPortNumbers() {591 return this.getLivenessCheckPorts();592 }593 private void applyConfiguration(CreateContainerCmd createCommand) {594 HostConfig hostConfig = buildHostConfig();595 // PortBindings must contain:596 // * all exposed ports with a randomized host port (equivalent to -p CONTAINER_PORT)597 // * all exposed ports with a fixed host port (equivalent to -p HOST_PORT:CONTAINER_PORT)598 Map<ExposedPort, PortBinding> allPortBindings = new HashMap<>();599 // First collect all the randomized host ports from our 'exposedPorts' field600 for (final Integer tcpPort : exposedPorts) {601 ExposedPort exposedPort = ExposedPort.tcp(tcpPort);602 allPortBindings.put(exposedPort, new PortBinding(Ports.Binding.empty(), exposedPort));603 }604 // Next collect all the fixed host ports from our 'portBindings' field, overwriting any randomized ports so that605 // we don't create two bindings for the same container port.606 for (final String portBinding : portBindings) {607 PortBinding parsedBinding = PortBinding.parse(portBinding);608 allPortBindings.put(parsedBinding.getExposedPort(), parsedBinding);...

Full Screen

Full Screen

buildHostConfig

Using AI Code Generation

copy

Full Screen

1package com.testcontainers;2import java.util.HashMap;3import java.util.Map;4import org.junit.Test;5import org.testcontainers.containers.GenericContainer;6import org.testcontainers.containers.Network;7import org.testcontainers.containers.wait.strategy.Wait;8public class TestContainersTest {9 public void test() {10 Network network = Network.newNetwork();11 Map<String, String> envMap = new HashMap<>();12 envMap.put("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1");13 envMap.put("KAFKA_ZOOKEEPER_CONNECT", "zookeeper:2181");14 envMap.put("KAFKA_BROKER_ID", "1");15 envMap.put("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1");16 envMap.put("KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS", "0");17 envMap.put("KAFKA_AUTO_CREATE_TOPICS_ENABLE", "true");18 GenericContainer kafka = new GenericContainer<>("confluentinc/cp-kafka:5.0.0")19 .withNetwork(network)20 .withNetworkAliases("kafka")21 .withEnv(envMap)22 .withExposedPorts(9092)23 .waitingFor(Wait.forLogMessage(".*started.*", 1));24 kafka.start();25 kafka.stop();26 }27}

Full Screen

Full Screen

buildHostConfig

Using AI Code Generation

copy

Full Screen

1class Container extends GenericContainer {2 Container(String imageName) {3 super(imageName)4 }5 protected void configure() {6 withLogConsumer(new Slf4jLogConsumer(log))7 }8}9def container = new Container('alpine:latest')10container.withCommand('tail', '-f', '/dev/null')11container.withCreateContainerCmdModifier { it.withHostConfig(buildHostConfig().withAutoRemove(true)) }12container.start()13container.stop()14container.close()

Full Screen

Full Screen

buildHostConfig

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.GenericContainer2def container = new GenericContainer('nginx:latest')3container.withCreateContainerCmdModifier { cmd ->4 cmd.withHostConfig(container.buildHostConfig().withIpcMode("host"))5}6container.start()7container.stop()8 {9 "daemon off;"10 "State": {11 },

Full Screen

Full Screen

buildHostConfig

Using AI Code Generation

copy

Full Screen

1def hostConfig = buildHostConfig()2def container = new GenericContainer('alpine:3.6')3 .withCommand('sh', '-c', 'echo hello')4 .withCreateContainerCmdModifier { cmd -> cmd.withHostConfig(hostConfig) }5container.start()6def result = container.execInContainer('sh', '-c', 'echo world')7println result.getStdout()8container.stop()

Full Screen

Full Screen

buildHostConfig

Using AI Code Generation

copy

Full Screen

1HostConfig hostConfig = buildHostConfig();2startContainer(this, hostConfig);3startContainer(this, hostConfig);4startContainer(this);5startContainer(this);6startContainer(this);7startContainer(this, hostConfig);8startContainer(this);

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