Best Testcontainers-java code snippet using org.testcontainers.containers.GenericContainer.withNetwork
Source:ServerIntegratedBenchmark.java
...75 runBenchmark(null);76 }77 @Test void elasticsearch() throws Exception {78 GenericContainer<?> elasticsearch = new GenericContainer<>("openzipkin/zipkin-elasticsearch7")79 .withNetwork(Network.SHARED)80 .withNetworkAliases("elasticsearch")81 .withLabel("name", "elasticsearch")82 .withLabel("storageType", "elasticsearch")83 .withExposedPorts(9200)84 .waitingFor(new HttpWaitStrategy().forPath("/_cluster/health"));85 containers.add(elasticsearch);86 runBenchmark(elasticsearch);87 }88 @Test void cassandra() throws Exception {89 runBenchmark(createCassandra("cassandra"));90 }91 @Test void cassandra3() throws Exception {92 runBenchmark(createCassandra("cassandra3"));93 }94 private GenericContainer<?> createCassandra(String storageType) {95 GenericContainer<?> cassandra = new GenericContainer<>("openzipkin/zipkin-cassandra")96 .withNetwork(Network.SHARED)97 .withNetworkAliases("cassandra")98 .withLabel("name", "cassandra")99 .withLabel("storageType", storageType)100 .withExposedPorts(9042)101 .waitingFor(Wait.forLogMessage(".*Starting listening for CQL clients.*", 1));102 containers.add(cassandra);103 return cassandra;104 }105 @Test void mysql() throws Exception {106 GenericContainer<?> mysql = new GenericContainer<>("openzipkin/zipkin-mysql")107 .withNetwork(Network.SHARED)108 .withNetworkAliases("mysql")109 .withLabel("name", "mysql")110 .withLabel("storageType", "mysql")111 .withExposedPorts(3306);112 containers.add(mysql);113 runBenchmark(mysql);114 }115 // Benchmark for zipkin-aws XRay UDP storage. As UDP does not actually need a server running to116 // send to, we can reuse our benchmark logic here to check it. Note, this benchmark always uses117 // a docker image and ignores RELEASED_ZIPKIN_SERVER.118 @Test void xrayUdp() throws Exception {119 GenericContainer<?> zipkin = new GenericContainer<>("openzipkin/zipkin-aws")120 .withNetwork(Network.SHARED)121 .withNetworkAliases("zipkin")122 .withEnv("STORAGE_TYPE", "xray")123 .withExposedPorts(9411);124 containers.add(zipkin);125 runBenchmark(null, zipkin);126 }127 void runBenchmark(@Nullable GenericContainer<?> storage) throws Exception {128 runBenchmark(storage, createZipkinContainer(storage));129 }130 void runBenchmark(@Nullable GenericContainer<?> storage, GenericContainer<?> zipkin)131 throws Exception {132 GenericContainer<?> backend = new GenericContainer<>("openzipkin/example-sleuth-webmvc")133 .withNetwork(Network.SHARED)134 .withNetworkAliases("backend")135 .withCommand("backend")136 .withExposedPorts(9000)137 .waitingFor(Wait.forHttp("/actuator/health"));138 containers.add(backend);139 GenericContainer<?> frontend = new GenericContainer<>("openzipkin/example-sleuth-webmvc")140 .withNetwork(Network.SHARED)141 .withNetworkAliases("frontend")142 .withCommand("frontend")143 .withExposedPorts(8081)144 .waitingFor(Wait.forHttp("/actuator/health"));145 containers.add(frontend);146 GenericContainer<?> prometheus = new GenericContainer<>("prom/prometheus")147 .withNetwork(Network.SHARED)148 .withNetworkAliases("prometheus")149 .withExposedPorts(9090)150 .withCopyFileToContainer(151 MountableFile.forClasspathResource("prometheus.yml"), "/etc/prometheus/prometheus.yml");152 containers.add(prometheus);153 GenericContainer<?> grafana = new GenericContainer<>("grafana/grafana")154 .withNetwork(Network.SHARED)155 .withNetworkAliases("grafana")156 .withExposedPorts(3000)157 .withEnv("GF_AUTH_ANONYMOUS_ENABLED", "true")158 .withEnv("GF_AUTH_ANONYMOUS_ORG_ROLE", "Admin");159 containers.add(grafana);160 GenericContainer<?> grafanaDashboards = new GenericContainer<>("appropriate/curl")161 .withNetwork(Network.SHARED)162 .withCommand("/create.sh")163 .withCopyFileToContainer(164 MountableFile.forClasspathResource("create-datasource-and-dashboard.sh"), "/create.sh");165 containers.add(grafanaDashboards);166 GenericContainer<?> wrk = new GenericContainer<>("skandyla/wrk")167 .withNetwork(Network.SHARED)168 .withCommand("-t4 -c128 -d100s http://frontend:8081 --latency");169 containers.add(wrk);170 grafanaDashboards.dependsOn(grafana);171 wrk.dependsOn(frontend, backend, prometheus, grafanaDashboards, zipkin);172 if (storage != null) {173 wrk.dependsOn(storage);174 }175 Startables.deepStart(Stream.of(wrk)).join();176 System.out.println("Benchmark started.");177 if (zipkin != null) {178 printContainerMapping(zipkin);179 }180 if (storage != null) {{181 printContainerMapping(storage);182 }}183 printContainerMapping(backend);184 printContainerMapping(frontend);185 printContainerMapping(prometheus);186 printContainerMapping(grafana);187 while (wrk.isRunning()) {188 Thread.sleep(1000);189 }190 // Wait for prometheus to do a final scrape.191 Thread.sleep(5000);192 System.out.println("Benchmark complete, wrk output:");193 System.out.println(wrk.getLogs().replace("\n\n", "\n"));194 WebClient prometheusClient = WebClient.of(195 "h1c://" + prometheus.getContainerIpAddress() + ":" + prometheus.getFirstMappedPort());196 System.out.println(String.format("Messages received: %s", prometheusValue(197 prometheusClient, "sum(zipkin_collector_messages_total)")));198 System.out.println(String.format("Spans received: %s", prometheusValue(199 prometheusClient, "sum(zipkin_collector_spans_total)")));200 System.out.println(String.format("Spans dropped: %s", prometheusValue(201 prometheusClient, "sum(zipkin_collector_spans_dropped_total)")));202 System.out.println("Memory quantiles:");203 printQuartiles(prometheusClient, "jvm_memory_used_bytes{area=\"heap\"}");204 printQuartiles(prometheusClient, "jvm_memory_used_bytes{area=\"nonheap\"}");205 System.out.println(String.format("Total GC time (s): %s",206 prometheusValue(prometheusClient, "sum(jvm_gc_pause_seconds_sum)")));207 System.out.println(String.format("Number of GCs: %s",208 prometheusValue(prometheusClient, "sum(jvm_gc_pause_seconds_count)")));209 System.out.println("POST Spans latency (s)");210 printHistogram(prometheusClient, "http_server_requests_seconds_bucket{"211 + "method=\"POST\",status=\"202\",uri=\"/api/v2/spans\"}");212 if (WAIT_AFTER_BENCHMARK) {213 System.out.println("Keeping containers running until explicit termination. "214 + "Feel free to poke around in grafana.");215 Thread.sleep(Long.MAX_VALUE);216 }217 }218 GenericContainer<?> createZipkinContainer(@Nullable GenericContainer<?> storage)219 throws Exception {220 Map<String, String> env = new HashMap<>();221 if (storage != null) {222 String name = storage.getLabels().get("name");223 String host = name;224 int port = storage.getExposedPorts().get(0);225 String address = host + ":" + port;226 env.put("STORAGE_TYPE", storage.getLabels().get("storageType"));227 switch (name) {228 case "elasticsearch":229 env.put("ES_HOSTS", "http://" + address);230 break;231 case "cassandra":232 case "cassandra3":233 env.put("CASSANDRA_CONTACT_POINTS", address);234 break;235 case "mysql":236 env.put("MYSQL_HOST", host);237 env.put("MYSQL_TCP_PORT", Integer.toString(port));238 env.put("MYSQL_USER", "zipkin");239 env.put("MYSQL_PASS", "zipkin");240 break;241 default:242 throw new IllegalArgumentException("Unknown storage " + name +243 ". Update startZipkin to map it to properties.");244 }245 }246 final GenericContainer<?> zipkin;247 if (RELEASED_ZIPKIN_VERSION == null) {248 zipkin = new GenericContainer<>("gcr.io/distroless/java:11-debug");249 List<String> classpath = new ArrayList<>();250 for (String item : System.getProperty("java.class.path").split(File.pathSeparator)) {251 Path path = Paths.get(item);252 final String containerPath;253 if (Files.isDirectory(path)) {254 Path root = path.getParent();255 while (root != null) {256 try (Stream<Path> f = Files.list(root)) {257 if (f.anyMatch(p -> p.getFileName().toString().equals("mvnw"))) {258 break;259 }260 }261 root = root.getParent();262 }263 containerPath = root.relativize(path).toString().replace('\\', '/');264 } else {265 containerPath = path.getFileName().toString();266 }267 // Test containers currently doesn't support copying in a path with subdirectories that268 // need to be created, so we mangle directory structure into a single directory with269 // hyphens.270 String classPathItem = "/classpath-" + containerPath.replace('/', '-');271 zipkin.withCopyFileToContainer(MountableFile.forHostPath(item), classPathItem);272 classpath.add(classPathItem);273 }274 zipkin.withCreateContainerCmdModifier(cmd -> cmd.withEntrypoint("java"));275 zipkin.setCommand("-cp", String.join(":", classpath), "zipkin.server.ZipkinServer");276 // Don't fail on classpath problem from missing lens, as we don't use it.277 env.put("ZIPKIN_UI_ENABLED", "false");278 } else {279 zipkin = new GenericContainer<>("openzipkin/zipkin:" + RELEASED_ZIPKIN_VERSION);280 }281 zipkin282 .withNetwork(Network.SHARED)283 .withNetworkAliases("zipkin")284 .withExposedPorts(9411)285 .withEnv(env)286 .waitingFor(new HttpWaitStrategy().forPath("/health"));287 containers.add(zipkin);288 return zipkin;289 }290 static void printContainerMapping(GenericContainer<?> container) {291 System.out.println(String.format(292 "Container %s ports exposed at %s",293 container.getDockerImageName(),294 container.getExposedPorts().stream()295 .map(port -> new AbstractMap.SimpleImmutableEntry<>(296 port,297 "http://" + container.getContainerIpAddress() + ":" + container.getMappedPort(port)))...
Source:Infrastructure.java
...29 private static final Logger LOGGER = LoggerFactory.getLogger(Infrastructure.class);30 private static final Network NETWORK = Network.newNetwork();31 private static final KafkaContainer KAFKA_CONTAINER =32 new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"))33 .withNetwork(NETWORK);34 private static final PostgreSQLContainer<?> POSTGRES_CONTAINER =35 new PostgreSQLContainer<>(DockerImageName.parse("debezium/example-postgres:" + DEBEZIUM_CONTAINER_VERSION).asCompatibleSubstituteFor("postgres"))36 .withNetwork(NETWORK)37 .withNetworkAliases("postgres");38 private static final MySQLContainer<?> MYSQL_CONTAINER =39 new MySQLContainer<>(DockerImageName.parse("debezium/example-mysql:" + DEBEZIUM_CONTAINER_VERSION).asCompatibleSubstituteFor("mysql"))40 .withNetwork(NETWORK)41 .withUsername("mysqluser")42 .withPassword("mysqlpw")43 .withEnv("MYSQL_ROOT_PASSWORD", "debezium")44 .withNetworkAliases("mysql");45 private static final MongoDBContainer MONGODB_CONTAINER =46 new MongoDbContainer(DockerImageName.parse("mongo:3.6"))47 .withNetwork(NETWORK)48 .withNetworkAliases("mongodb");49 private static final DebeziumContainer DEBEZIUM_CONTAINER =50 new DebeziumContainer(DockerImageName.parse("debezium/connect:" + DEBEZIUM_CONTAINER_VERSION))51 .withNetwork(NETWORK)52 .withKafka(KAFKA_CONTAINER)53 .withLogConsumer(new Slf4jLogConsumer(LOGGER))54 .dependsOn(KAFKA_CONTAINER);55 public static Network getNetwork() {56 return NETWORK;57 }58 public static void startContainers(DATABASE database) {59 final GenericContainer<?> dbContainer;60 switch (database) {61 case POSTGRES:62 dbContainer = POSTGRES_CONTAINER;63 break;64 case MYSQL:65 dbContainer = MYSQL_CONTAINER;...
Source:AbstractTestcontainers.java
...24 @DynamicPropertySource25 private static void dynamicProperties(DynamicPropertyRegistry registry) {26 Network network = Network.SHARED;27 // MySQL28 mySQLContainer.withNetwork(network)29 .withNetworkAliases("mysql")30 .withUrlParam("characterEncoding", "UTF-8")31 .withUrlParam("serverTimezone", "UTC")32 .start();33 // Zookeeper34 zookeeperContainer.withNetwork(network)35 .withNetworkAliases("zookeeper")36 .withEnv("ZOOKEEPER_CLIENT_PORT", "2181")37 .withExposedPorts(2181)38 .waitingFor(Wait.forListeningPort().withStartupTimeout(STARTUP_TIMEOUT))39 .start();40 // Kafka41 kafkaContainer.withNetwork(network)42 .withNetworkAliases("kafka")43 .withExternalZookeeper("zookeeper:2181")44 .withExposedPorts(9092, 9093)45 .start();46 // Schema Registry47 schemaRegistryContainer.withNetwork(network)48 .withNetworkAliases("schema-registry")49 .withEnv("SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS", "kafka:9092")50 .withEnv("SCHEMA_REGISTRY_HOST_NAME", "schema-registry")51 .withEnv("SCHEMA_REGISTRY_LISTENERS", "http://0.0.0.0:8081")52 .withExposedPorts(8081)53 .waitingFor(Wait.forListeningPort().withStartupTimeout(STARTUP_TIMEOUT))54 .start();55 // Cassandra56 cassandraContainer.withNetwork(network)57 .withNetworkAliases("cassandra")58 .start();59 // event-service60 eventServiceContainer.withNetwork(network)61 .withNetworkAliases("event-service")62 .withEnv("KAFKA_HOST", "kafka")63 .withEnv("KAFKA_PORT", "9092")64 .withEnv("SCHEMA_REGISTRY_HOST", "schema-registry")65 .withEnv("CASSANDRA_HOST", "cassandra")66 .withEnv("SPRING_ZIPKIN_ENABLED", "false")67 .withExposedPorts(EVENT_SERVICE_EXPOSED_PORT)68 .waitingFor(Wait.forHttp("/actuator/health")69 .forPort(EVENT_SERVICE_EXPOSED_PORT).forStatusCode(200).withStartupTimeout(STARTUP_TIMEOUT))70 .start();71 registry.add("spring.datasource.url", mySQLContainer::getJdbcUrl);72 registry.add("spring.datasource.username", mySQLContainer::getUsername);73 registry.add("spring.datasource.password", mySQLContainer::getPassword);74 registry.add("spring.jpa.properties.hibernate.dialect.storage_engine", () -> "innodb");75 String schemaRegistryEndpoint = String.format("http://localhost:%s", schemaRegistryContainer.getMappedPort(8081));...
withNetwork
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2public class 1 {3 public static void main(String[] args) {4 try (GenericContainer container = new GenericContainer("alpine:3.8")) {5 container.withNetwork(null);6 container.start();7 System.out.println(container.getContainerId());8 }9 }10}11import org.testcontainers.containers.GenericContainer;12public class 2 {13 public static void main(String[] args) {14 try (GenericContainer container = new GenericContainer("alpine:3.8")) {15 container.withNetwork(null);16 container.start();17 System.out.println(container.getContainerId());18 }19 }20}
withNetwork
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.Network;3public class TestDocker {4 public static void main(String[] args) {5 Network network = Network.newNetwork();6 GenericContainer container1 = new GenericContainer("busybox:latest").withNetwork(network).withNetworkAliases("container1").withCommand("sleep 300");7 container1.start();8 GenericContainer container2 = new GenericContainer("busybox:latest").withNetwork(network).withNetworkAliases("container2").withCommand("sleep 300");9 container2.start();10 String ipContainer1 = container1.getContainerInfo().getNetworkSettings().getNetworks().get(network.getId()).getIpAddress();11 String ipContainer2 = container2.getContainerInfo().getNetworkSettings().getNetworks().get(network.getId()).getIpAddress();12 System.out.println("IP container 1: " + ipContainer1);13 System.out.println("IP container 2: " + ipContainer2);14 }15}
withNetwork
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.Network;3public class TestContainerNetworkExample {4 public static void main(String[] args) {5 Network network = Network.newNetwork();6 GenericContainer container1 = new GenericContainer("redis:latest")7 .withNetwork(network)8 .withNetworkAliases("redis1")9 .withExposedPorts(6379);10 GenericContainer container2 = new GenericContainer("redis:latest")11 .withNetwork(network)12 .withNetworkAliases("redis2")13 .withExposedPorts(6379);14 container1.start();15 container2.start();16 }17}18import org.testcontainers.containers.GenericContainer;19import org.testcontainers.containers.Network;20public class TestContainerNetworkExample {21 public static void main(String[] args) {22 Network network = Network.newNetwork();23 GenericContainer container1 = new GenericContainer("redis:latest")24 .withNetwork(network)25 .withNetworkAliases("redis1")26 .withExposedPorts(6379);27 GenericContainer container2 = new GenericContainer("redis:latest")28 .withNetwork(network)29 .withNetworkAliases("redis2")30 .withExposedPorts(6379);31 container1.start();32 container2.start();33 }34}35import org.testcontainers.containers.GenericContainer;36import org.testcontainers.containers.Network;37public class TestContainerNetworkExample {38 public static void main(String[] args) {39 Network network = Network.newNetwork();40 GenericContainer container1 = new GenericContainer("redis:latest")41 .withNetwork(network)42 .withNetworkAliases("redis1")43 .withExposedPorts(6379);44 GenericContainer container2 = new GenericContainer("redis:latest")45 .withNetwork(network)46 .withNetworkAliases("redis2")47 .withExposedPorts(6379);48 container1.start();49 container2.start();50 }51}52import org.testcontainers.containers.GenericContainer;53import org.testcontainers.containers.Network;54public class TestContainerNetworkExample {55 public static void main(String[] args)
withNetwork
Using AI Code Generation
1public class TestContainer {2 public static void main(String[] args) {3 try (GenericContainer container = new GenericContainer("postgres:10.5")) {4 container.withNetwork(Network.SHARED)5 .withNetworkAliases("postgres")6 .withEnv("POSTGRES_PASSWORD", "password")7 .withExposedPorts(5432)8 .start();9 }10 }11}12public class TestContainer {13 public static void main(String[] args) {14 try (PostgreSQLContainer container = new PostgreSQLContainer()) {15 container.withNetwork(Network.SHARED)16 .withNetworkAliases("postgres")17 .withEnv("POSTGRES_PASSWORD", "password")18 .withExposedPorts(5432)19 .start();20 }21 }22}23public class TestContainer {24 public static void main(String[] args) {25 try (PostgreSQLContainer container = new PostgreSQLContainer()) {26 container.withNetwork(Network.SHARED)27 .withNetworkAliases("postgres")28 .withEnv("POSTGRES_PASSWORD", "password")29 .withExposedPorts(5432)30 .start();31 }32 }33}34public class TestContainer {35 public static void main(String[] args) {36 try (PostgreSQLContainer container = new PostgreSQLContainer()) {37 container.withNetwork(Network.SHARED)38 .withNetworkAliases("postgres")39 .withEnv("POSTGRES_PASSWORD", "password")40 .withExposedPorts(5432)41 .start();42 }43 }44}45public class TestContainer {46 public static void main(String[] args) {47 try (PostgreSQLContainer container = new PostgreSQLContainer()) {48 container.withNetwork(Network.SHARED)49 .withNetworkAliases("postgres")50 .withEnv("POSTGRES_PASSWORD", "password")51 .withExposedPorts(5432)52 .start();53 }54 }55}
withNetwork
Using AI Code Generation
1import org.junit.Test;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.Network;4public class OneJava {5 public void test() {6 Network network = Network.newNetwork();7 GenericContainer container1 = new GenericContainer("alpine")8 .withNetwork(network)9 .withNetworkAliases("container1")10 .withCommand("sleep", "100000");11 GenericContainer container2 = new GenericContainer("alpine")12 .withNetwork(network)13 .withNetworkAliases("container2")14 .withCommand("sleep", "100000");15 container1.start();16 container2.start();17 System.out.println("container1 IP: " + container1.getContainerIpAddress());18 System.out.println("container2 IP: " + container2.getContainerIpAddress());19 System.out.println("container1 port: " + container1.getFirstMappedPort());20 System.out.println("container2 port: " + container2.getFirstMappedPort());21 container1.stop();22 container2.stop();23 }24}25import org.junit.Test;26import org.testcontainers.containers.GenericContainer;27import org.testcontainers.containers.Network;28public class TwoJava {29 public void test() {30 Network network = Network.newNetwork();31 GenericContainer container1 = new GenericContainer("alpine")32 .withNetworkMode("bridge")33 .withNetworkAliases("container1")34 .withCommand("sleep", "100000");35 GenericContainer container2 = new GenericContainer("alpine")36 .withNetworkMode("bridge")37 .withNetworkAliases("container2")38 .withCommand("sleep", "100000");39 container1.start();40 container2.start();41 System.out.println("container1 IP: " + container1.getContainerIpAddress());42 System.out.println("container2 IP: " + container2.getContainerIpAddress());43 System.out.println("container1 port: " + container1.getFirstMappedPort());44 System.out.println("container2 port: " + container2.getFirstMappedPort());
withNetwork
Using AI Code Generation
1import java.util.Arrays;2import java.util.List;3import java.util.stream.Collectors;4import org.testcontainers.containers.GenericContainer;5import org.testcontainers.containers.Network;6public class DockerNetwork {7 public static void main(String[] args) {8 Network network = Network.newNetwork();9 GenericContainer container1 = new GenericContainer("alpine:3.4")10 .withNetwork(network)11 .withNetworkAliases("alias1")12 .withCommand(Arrays.asList("sh", "-c", "while true; do sleep 1; done"));13 container1.start();14 GenericContainer container2 = new GenericContainer("alpine:3.4")15 .withNetwork(network)16 .withNetworkAliases("alias2")17 .withCommand(Arrays.asList("sh", "-c", "while true; do sleep 1; done"));18 container2.start();19 GenericContainer container3 = new GenericContainer("alpine:3.4")20 .withNetwork(network)21 .withCommand(Arrays.asList("sh", "-c", "while true; do sleep 1; done"));22 container3.start();23 System.out.println(container3.getContainerIpAddress());24 String result = container3.execInContainer("sh", "-c", "echo hello").getStdout();25 System.out.println(result);26 container3.stop();27 container3.remove();28 }29}
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!!