### Extending PostgresContainer for Template Database Initialization (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md This Java code defines `PostgresWithTemplates`, extending `PostgresContainer` to support template databases. The constructor initializes the container with a specific Postgres image and copies a `schema.sql` file to the container's initialization directory. The `containerIsStarted` method is overridden to ensure initial setup scripts are run after the container starts, preparing the base database for templating. ```Java public static final String ACTUAL_DATABASE_NAME = "realtest"; public PostgresWithTemplates() { super("postgres:16-alpine"); this.withCopyFileToContainer(MountableFile.forClasspathResource("schema.sql"), "/docker-entrypoint-initdb.d/"); } @Override protected void containerIsStarted(InspectContainerResponse containerInfo) { this.runInitScriptIfRequired(); } ``` -------------------------------- ### Running Supabase PostgreSQL Docker Container Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This command starts a Supabase PostgreSQL Docker container, exposing it with a specified password. It's used to observe the container's startup logs and identify the 'ready' state for Testcontainers module development. ```bash docker run -e POSTGRES_PASSWORD=p@$$w0rd supabase/postgres:15.1.1.55 ``` -------------------------------- ### Starting Ollama Container and Verifying Version (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This snippet demonstrates how to initialize and start an Ollama container using Testcontainers. It then verifies the container's API by fetching its version and asserting it matches the expected value, ensuring the container is up and running correctly. The `try-with-resources` ensures the container is automatically closed. ```Java try ( OllamaContainer ollama = new OllamaContainer("ollama/ollama:0.1.26") ) { ollama.start(); String version = given().baseUri(ollama.getEndpoint()).get("/api/version").jsonPath().get("version"); assertThat(version).isEqualTo("0.1.26"); } ``` -------------------------------- ### Basic SupabaseContainer Test with Default Password Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This JUnit test demonstrates how to start and interact with the `SupabaseContainer`. It verifies that a connection can be established using the default credentials and a simple SQL query `SELECT 1` executes successfully, confirming the container's readiness and connectivity. ```java import org.testcontainers.utility.DockerImageName; @Test void test() throws SQLException { try (SupabaseContainer supabase = new SupabaseContainer(DockerImageName.parse("supabase/postgres:15.1.1.55"))) { supabase.start(); Connection connection = DriverManager.getConnection(supabase.getJdbcUrl(), supabase.getUsername(), supabase.getPassword()); PreparedStatement preparedStatement = connection.prepareStatement("SELECT 1"); preparedStatement.execute(); ResultSet resultSet = preparedStatement.getResultSet(); resultSet.next(); assertThat(resultSet.getInt(1)).isEqualTo(1); } } ``` -------------------------------- ### Instantiating Ollama Container from Cached Image (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This code demonstrates how to instantiate an Ollama container from a previously committed and cached Docker image. It uses `DockerImageName.parse().asCompatibleSubstituteFor()` to ensure the custom image is used as a substitute for the original Ollama image. After starting the container, it verifies that the pre-pulled model is available by querying the API, leveraging the cached image for faster test setup. ```Java try ( OllamaContainer ollama = new OllamaContainer( DockerImageName.parse(newImageName) .asCompatibleSubstituteFor("ollama/ollama") ) ) { ollama.start(); String modelName = given() .baseUri(ollama.getEndpoint()) .get("/api/tags") .jsonPath() .getString("models[0].name"); assertThat(modelName).contains("all-minilm"); } ``` -------------------------------- ### Retrieving Docker Runtime Information (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This snippet shows how to access Docker client information, specifically retrieving runtime details. It uses `dockerClient.infoCmd().exec()` to get general Docker daemon information and then extracts the `runtimes` map, which can be used to determine available GPU support or other runtime configurations for container creation. ```Java Info info = (Info)this.dockerClient.infoCmd().exec(); Map runtimes = info.getRuntimes(); ``` -------------------------------- ### Checking Docker Version Source: https://github.com/testcontainers/java-module-workshop/blob/main/README.md This command checks the installed Docker client and server versions, along with other details like API version, Go version, and OS/Arch. It's used to verify a working Docker environment is present and configured correctly for Testcontainers. ```shell $ docker version Client: Version: 24.0.6-rd API version: 1.43 Go version: go1.20.7 Git commit: da4c87c Built: Wed Sep 6 16:40:13 2023 OS/Arch: darwin/arm64 Context: desktop-linux Server: Docker Desktop 4.24.2 (124339) Engine: Version: 24.0.6 API version: 1.43 (minimum version 1.12) Go version: go1.20.7 Git commit: 1a79695 Built: Mon Sep 4 12:31:36 2023 OS/Arch: linux/arm64 Experimental: false ... ``` -------------------------------- ### Pulling Ollama Model into Container (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This code snippet shows how to start an Ollama container and then execute a command inside it to pull a specific LLM model ("all-minilm"). After pulling, it verifies that the model is available by querying the Ollama API's tags endpoint and asserting its presence. This is necessary for running inference. ```Java try (OllamaContainer ollama = new OllamaContainer("ollama/ollama:0.1.26")) { ollama.start(); ollama.execInContainer("ollama", "pull", "all-minilm"); String modelName = given() .baseUri(ollama.getEndpoint()) .get("/api/tags") .jsonPath() .getString("models[0].name"); assertThat(modelName).contains("all-minilm"); } ``` -------------------------------- ### Configuring Spring Boot Test with Testcontainers Postgres (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md This Java snippet sets up a Spring Boot test class to use the custom `PostgresWithTemplates` container. It initializes and starts the container statically, then uses `@DynamicPropertySource` to dynamically configure the Spring `DataSource` properties (username, password, JDBC URL) based on the running Testcontainers instance. This ensures the `JdbcTemplate` is correctly wired to the containerized database. ```Java static PostgresWithTemplates pg = new PostgresWithTemplates(); static { pg.start(); } @Autowired JdbcTemplate jdbcTemplate; @DynamicPropertySource public static void setup(DynamicPropertyRegistry reg) { reg.add("spring.datasource.username", pg::getUsername); reg.add("spring.datasource.password", pg::getPassword); reg.add("spring.datasource.url", pg::getJdbcUrl); } ``` -------------------------------- ### Adding Connection Access Methods to SupabaseContainer Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md These methods provide convenient access to the Supabase container's connection details. `getJdbcUrl()` constructs the JDBC URL, `getUsername()` returns the default PostgreSQL username, and `getPassword()` returns the default password, simplifying database connection setup in tests. ```java public String getJdbcUrl() { return "jdbc:postgresql://" + getHost() + ":" + getMappedPort(5432) + "/postgres"; } public String getUsername() { return "postgres"; } public String getPassword() { return "password"; } ``` -------------------------------- ### Copying Sharding Script to MongoDB Container in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet overrides the `containerIsStarting` lifecycle method to copy the `sharding.sh` script from the classpath into the container. This operation is performed only if sharding is enabled, ensuring the script is available before the container fully starts. ```Java @Override protected void containerIsStarting(InspectContainerResponse containerInfo) { if (this.shardingEnabled) { copyFileToContainer(MountableFile.forClasspathResource("/sharding.sh", 0777), STARTER_SCRIPT); } } ``` -------------------------------- ### SupabaseContainer Test with Custom Password Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This JUnit test demonstrates using the `withPassword()` method to set a custom password for the Supabase container. It verifies that the container starts, a connection is established with the custom password, and the `getPassword()` method correctly reflects the set value, ensuring password customization works as expected. ```java @Test void test2() throws SQLException { try (SupabaseContainer supabase = new SupabaseContainer(DockerImageName.parse("supabase/postgres:15.1.1.55")) .withPassword("testpassword")) { supabase.start(); Connection connection = DriverManager.getConnection(supabase.getJdbcUrl(), supabase.getUsername(), supabase.getPassword()); PreparedStatement preparedStatement = connection.prepareStatement("SELECT 1"); preparedStatement.execute(); ResultSet resultSet = preparedStatement.getResultSet(); resultSet.next(); assertThat(resultSet.getInt(1)).isEqualTo(1); assertThat(supabase.getJdbcUrl()).endsWith("/test"); assertThat(supabase.getUsername()).isEqualTo("postgres"); assertThat(supabase.getPassword()).isEqualTo("testpassword"); } } ``` -------------------------------- ### Conditional Ollama Image Creation and Model Pull (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This snippet shows how to conditionally create and commit a new Docker image for Ollama with a pre-pulled model. It first checks if a specific image (`tc-ollama-allminilm`) already exists. If not, it starts a fresh Ollama container, pulls the "all-minilm" model, verifies its presence, and then commits the container's state to the new image, preventing redundant model downloads on subsequent runs. ```Java String newImageName = "tc-ollama-allminilm"; DockerClient client = DockerClientFactory.lazyClient(); List images = client.listImagesCmd().withImageNameFilter(newImageName).exec(); if (images.isEmpty()) { // use the code from above to create an Ollama container, pull the model, and com try (OllamaContainer ollama = new OllamaContainer("ollama/ollama:0.1.26")) { ollama.start(); ollama.execInContainer("ollama", "pull", "all-minilm"); // pull the model String modelName = given() .baseUri(ollama.getEndpoint()) .get("/api/tags") .jsonPath() .getString("models[0].name"); assertThat(modelName).contains("all-minilm"); ollama.commitToImage(newImageName); // commit the image } } ``` -------------------------------- ### Conditionally Initializing Replica Set in Testcontainers MongoDB in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet modifies the `containerIsStarted` lifecycle method to conditionally initialize the MongoDB replica set. The `initReplicaSet` method is only called if sharding is not enabled, preventing conflicts when a custom sharding setup is used. ```Java @Override protected void containerIsStarted(InspectContainerResponse containerInfo, boolean reused) { if (!this.shardingEnabled) { try { initReplicaSet(reused); } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } } } ``` -------------------------------- ### Setting Up a Helloworld Application Container in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md This snippet initializes a `GenericContainer` for a simple 'helloworld' application, which serves as the target for the Cloudflare tunnel. It configures network aliases, exposes necessary ports (8080, 8081), and sets up an `HttpWaitStrategy` to ensure the application is ready before the tunnel connects. ```Java GenericContainer helloworld = new GenericContainer<>(DockerImageName.parse("testcontainers/helloworld:1.1.0")) .withNetworkAliases("helloworld") .withExposedPorts(8080, 8081) .waitingFor(new HttpWaitStrategy()); helloworld.start(); ``` -------------------------------- ### Configuring SupabaseContainer Constructor Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This constructor for `SupabaseContainer` configures the container with essential properties: it asserts compatibility with the `supabase/postgres` image, exposes port 5432, sets a default `POSTGRES_PASSWORD` environment variable, and defines a wait strategy based on log messages to determine the container's ready state. ```java import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.utility.DockerImageName; public SupabaseContainer(DockerImageName dockerImageName) { super(dockerImageName); dockerImageName.assertCompatibleWith(DockerImageName.parse("supabase/postgres")); withExposedPorts(5432); withEnv("POSTGRES_PASSWORD", "password"); waitingFor(Wait.forLogMessage(".*database system is ready to accept connections.*\\s", 2)); } ``` -------------------------------- ### Configuring MongoDBContainerDef for Sharding Entrypoint in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet enhances the `withSharding()` method within `MongoDBContainerDef` to configure the container's startup behavior for sharding. It sets a custom command to wait for and execute the `STARTER_SCRIPT`, defines a wait strategy for 'mongos ready' logs, and sets the entrypoint to 'sh'. ```Java void withSharding() { setCommand("-c", "while [ ! -f " + STARTER_SCRIPT + " ]; do sleep 0.1; done; " + STARTER_SCRIPT); setWaitStrategy(Wait.forLogMessage("(?i).*mongos ready.*", 1)); setEntrypoint("sh"); } ``` -------------------------------- ### Creating a Database Snapshot Method in Testcontainers (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md This `snapshot` method in `PostgresWithTemplates` executes a `psql` command within the container to mark the 'test' database as a template. It then calls `reset()` to create a fresh database from this template and sets the container's exposed database name. This method allows programmatic creation of a database snapshot for later restoration. ```Java public void snapshot() { try { ExecResult execResult = this.execInContainer("psql", "-U", "test", "-c", "ALTER DATABASE test WITH is_template = TRUE"); } catch (Exception e) { throw new RuntimeException(e); } reset(); this.withDatabaseName(ACTUAL_DATABASE_NAME); } ``` -------------------------------- ### Cloning Testcontainers Java Module Workshop Repository Source: https://github.com/testcontainers/java-module-workshop/blob/main/README.md This command clones the `java-module-workshop` repository from GitHub to the local machine. Executing this command downloads all necessary project files, allowing participants to begin the workshop. ```shell git clone https://github.com/testcontainers/java-module-workshop.git ``` -------------------------------- ### Declaring and Creating Postgres Template Databases (SQL) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md This SQL snippet demonstrates how to mark an existing PostgreSQL database as a template and then create a new database from that template. The `ALTER DATABASE` command sets the `is_template` property to `TRUE`, making the 'test' database available as a template. The `CREATE DATABASE` command then uses this template to create 'test1', inheriting its schema and data. ```SQL ALTER DATABASE test WITH is_template = TRUE; CREATE DATABASE test1 TEMPLATE test; ``` -------------------------------- ### Defining Starter Script Path Constant for MongoDBContainer in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet defines a constant `STARTER_SCRIPT` specifying the absolute path within the container where the custom sharding startup script will be copied. This ensures a consistent and known location for the script. ```Java private static final String STARTER_SCRIPT = "/testcontainers_start.sh"; ``` -------------------------------- ### Resetting Database State Using Postgres Templates (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md The `reset` method facilitates resetting the database to its initial template state. It first drops the currently exposed database (`ACTUAL_DATABASE_NAME`) using a `psql` command with `FORCE` to terminate active connections. Subsequently, it creates a new database instance from the 'test' template, effectively restoring the database to its snapshot state. ```Java public void reset() { try { ExecResult execResult = this.execInContainer("psql", "-U", "test", "-c", "DROP DATABASE " + ACTUAL_DATABASE_NAME + " with (FORCE)"); } catch (Exception e) { throw new RuntimeException(e); } try { ExecResult execResult1 = this.execInContainer("psql", "-U", "test", "-c", "CREATE DATABASE " + ACTUAL_DATABASE_NAME + " TEMPLATE test"); } catch (Exception e) { throw new RuntimeException(e); } } ``` -------------------------------- ### Creating a Network for Container Communication (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-3/README.md This snippet initializes a new network instance using Testcontainers' `Network.newNetwork()` method. This network will be used to connect multiple containers, allowing them to communicate with each other within the same isolated environment. ```Java Network network = Network.newNetwork(); ``` -------------------------------- ### Producing, Consuming, and Asserting Kafka Messages with kcat (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-3/README.md This snippet demonstrates producing a message to Kafka using `kcat` within the container, then consuming a message from the same topic. Finally, it asserts that the consumed message matches the expected content, verifying successful end-to-end communication. ```Java kcat.execInContainer("kcat", "-b", "kafka:19092", "-t", "msgs", "-P", "-l", "/data/msgs.txt"); String stdout = kcat .execInContainer("kcat", "-b", "kafka:19092", "-C", "-t", "msgs", "-c", "1") .getStdout(); assertThat(stdout).contains("Message produced by kcat"); ``` -------------------------------- ### Defining kcat GenericContainer for Message Operations (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-3/README.md This snippet defines a `GenericContainer` for the `kcat` utility. It modifies the container's entrypoint, copies a message file into it, attaches it to the shared network, and sets a command to keep the container running for interactive use. ```Java @Container GenericContainer kcat = new GenericContainer<>("confluentinc/cp-kcat:7.4.1") .withCreateContainerCmdModifier(cmd -> { cmd.withEntrypoint("sh"); }) .withCopyToContainer(Transferable.of("Message produced by kcat"), "/data/msgs.txt") .withNetwork(network) .withCommand("-c", "tail -f /dev/null"); ``` -------------------------------- ### Verifying Database State and Truncation in Testcontainers Test (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md This JUnit test method verifies the initial state of the database and demonstrates data manipulation. It queries the current database name, asserts that the `products` table initially contains data, then truncates the table, and finally asserts that the table is empty after truncation. This test highlights how to interact with the containerized database and check its state. ```Java @Test void contextLoads() { String s = jdbcTemplate.queryForObject("SELECT current_database();", String.class); assertThat(s).isNotEqualTo("test"); var count = jdbcTemplate.queryForObject("SELECT count(*) from products;", Integer.class); assertThat(count).isPositive(); jdbcTemplate.execute("TRUNCATE TABLE products;"); var afterTruncate = jdbcTemplate.queryForObject("SELECT count(*) from products;", Integer.class); assertThat(afterTruncate).isZero(); } ``` -------------------------------- ### Implementing Log Message Waiting Strategy in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md This line configures a waiting strategy for the `CloudflaredContainer` to ensure it's ready before use. It waits for a log message matching the regex `.*Registered tunnel connection.*` to appear at least once, indicating that the Cloudflare tunnel has been successfully established. ```Java waitingFor(Wait.forLogMessage(".*Registered tunnel connection.*", 1)); ``` -------------------------------- ### Resetting Database State Between JUnit Tests (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-5/README.md This `@BeforeEach` method ensures the database is reset to its initial template state before each test execution. It calls the `pg.reset()` method to drop and recreate the database. Additionally, it handles connection pool management by soft-evicting connections from a HikariDataSource, preventing `FATAL: terminating connection` errors that can occur after a database reset. ```Java @BeforeEach public void reset() { pg.reset(); // Resetting the database terminates the connections, so we need to soft-evict those in the connection pool as well. // Otherwise, tests would fail with postgres error 'FATAL: terminating connection due to administrator command'. DataSource dataSource = jdbcTemplate.getDataSource(); if (dataSource instanceof HikariDataSource hikariDataSource) { hikariDataSource.getHikariPoolMXBean().softEvictConnections(); } } ``` -------------------------------- ### Extending GenericContainer for SupabaseContainer Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This snippet defines the initial structure of the `SupabaseContainer` class, extending `GenericContainer` from Testcontainers. This forms the base for creating a custom Testcontainers module for Supabase PostgreSQL. ```java import org.testcontainers.containers.GenericContainer; public class SupabaseContainer extends GenericContainer { } ``` -------------------------------- ### Defining CloudflaredContainer Class in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md This snippet defines the basic `CloudflaredContainer` class, extending `GenericContainer`. It serves as the foundation for creating a Testcontainers module for Cloudflare Quick Tunnel, allowing it to work with compatible Docker images like 'cloudflare/cloudflared'. ```Java public class CloudflaredContainer extends GenericContainer {} ``` -------------------------------- ### Defining KafkaContainer with Network and Listener (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-3/README.md This snippet defines a `KafkaContainer` instance, specifying its Docker image. It configures an additional listener for Kafka clients to connect to and attaches the container to the previously created network, enabling communication with other containers on that network. ```Java @Container KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.6.1")) .withListener(() -> "kafka:19092") .withNetwork(network); ``` -------------------------------- ### Configuring Host Port Access for CloudflaredContainer in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md These lines are added to the `CloudflaredContainer` constructor to enable access to the host machine's ports. `withAccessToHost(true)` grants the container network access to the host, and `Testcontainers.exposeHostPorts(port)` exposes the specified host port to the container, crucial for tunneling local applications. ```Java withAccessToHost(true); Testcontainers.exposeHostPorts(port); ``` -------------------------------- ### Adding Custom Password Configuration to SupabaseContainer Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This snippet introduces a private `password` field and a `withPassword` fluent setter method to the `SupabaseContainer` class. This allows users to customize the PostgreSQL password for the container, enhancing flexibility and security. ```java private String password = "p@$$word"; public SupabaseContainer withPassword(String password) { this.password = password; return this; } ``` -------------------------------- ### Instantiating MongoDBContainer with Sharding in Java Test Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet demonstrates how to instantiate a `MongoDBContainer` in a test class, specifying the MongoDB image version and enabling sharding using the `withSharding()` fluent method. This prepares the container for sharded operations in integration tests. ```Java MongoDBContainer myMongo = new MongoDBContainer("mongo:7.0.9") .withSharding(); ``` -------------------------------- ### Verifying MongoDB Sharding Status via Shell Commands Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet provides shell commands to connect to a running MongoDB container, switch to the 'admin' database, and execute `db.adminCommand({ listShards: 1 })` to verify if sharding is enabled and configured correctly within the MongoDB instance. ```Shell mongosh use admin db.adminCommand({ listShards: 1 }) ``` -------------------------------- ### Adding withSharding Configuration Method to MongoDBContainer in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet introduces a fluent `withSharding()` method to the `MongoDBContainer` class. Calling this method enables the sharding flag and delegates to a `MongoDBContainerDef` to apply sharding-specific configurations, allowing for a more configurable container. ```Java public MongoDBContainer withSharding() { this.shardingEnabled = true; getContainerDef().withSharding(); return this; } ``` -------------------------------- ### Committing Container Changes to New Docker Image (Java) Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This method demonstrates how to commit the current state of a running Testcontainers container to a new Docker image. It checks if the target image already exists and, if not, uses the Docker Client API to commit the container's changes, including any pulled models, to a new image with specified repository and tag. This optimizes subsequent test runs by reusing the pre-configured image. ```Java public void commitToImage(String imageName) { DockerImageName dockerImageName = DockerImageName.parse(this.getDockerImageName()); if (!dockerImageName.equals(DockerImageName.parse(imageName))) { DockerClient dockerClient = DockerClientFactory.instance().client(); List images = (List)dockerClient.listImagesCmd().withReferenceFilter(imageName).exec(); if (images.isEmpty()) { DockerImageName imageModel = DockerImageName.parse(imageName); dockerClient.commitCmd(this.getContainerId()).withRepository(imageModel.getUnversionedPart()).withLabels(Collections.singletonMap("org.testcontainers.sessionId", "")).withTag(imageModel.getVersionPart()).exec(); } } } ``` -------------------------------- ### Testing Java GC Selection with Testcontainers Resource Limits Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This parameterized JUnit test uses Testcontainers to verify the Garbage Collector (GC) chosen by a Java process under specific CPU and memory constraints. It configures a `GenericContainer` with a `HostConfig` to limit memory and CPU count, then runs a Java command to print GC flags, asserting that the container logs match the expected GC pattern. It requires JUnit 5 and Testcontainers dependencies. ```Java @CsvSource({ ".*SerialGC.*true.*, 1791", ".*G1GC.*true.*, 1792"} ) @ParameterizedTest void doSomethingWithCreate(String gcRegex, long memoryLimitInMB) throws IOException { try (var container = new GenericContainer<>("eclipse-temurin:17-jdk") .withCreateContainerCmdModifier(createContainerCmd -> { var hostConfig = new HostConfig(); hostConfig.withMemory(memoryLimitInMB * 1024L * 1024L); hostConfig.withCpuCount(1L); createContainerCmd.withHostConfig(hostConfig); } ) .withCommand("java -XX:+PrintFlagsFinal -version && sleep infinity") .withStartupCheckStrategy(new IndefiniteWaitOneShotStartupCheckStrategy()) ) { container.start(); var logs = container.getLogs(); Assertions.assertThat(logs).containsPattern(gcRegex); } } ``` -------------------------------- ### Configuring GPU Access for Testcontainers in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-6/README.md This Java snippet demonstrates how to conditionally enable GPU access for a Testcontainers container. It uses `withCreateContainerCmdModifier` to add a `DeviceRequest` to the container's host configuration, specifying "gpu" capabilities and requesting all available GPUs (`count -1`). This is typically used when the host system has NVIDIA runtimes. ```Java if (runtimes != null && runtimes.containsKey("nvidia")) { this.withCreateContainerCmdModifier((cmd) -> { cmd.getHostConfig().withDeviceRequests(Collections.singletonList((new DeviceRequest()).withCapabilities(Collections.singletonList(Collections.singletonList("gpu"))).withCount(-1))); }); } ``` -------------------------------- ### Registering Custom ConnectionDetailsFactory in Spring Boot Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-7/README.md This snippet shows the content to be added to `src/main/resources/META-INF/spring.factories`. This entry registers the `WireMockContainerConnectionDetailsFactory` with Spring Boot's auto-configuration system, making it discoverable for `@ServiceConnection`. ```Properties org.springframework.boot.autoconfigure.service.connection.ConnectionDetailsFactory=org.testcontainers.workshop.WireMockContainerConnectionDetailsFactory ``` -------------------------------- ### Testing Cloudflare Tunnel Public URL with Awaitility and RestAssured in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md This test snippet asserts that the retrieved public URL contains 'cloudflare' and then uses Awaitility to repeatedly attempt to access the URL via RestAssured. It disables DNS caching and ignores exceptions, allowing for retries until the 'Hello world' content is found, confirming the tunnel's functionality. ```Java assertThat(url).as("Public url contains 'cloudflare'").contains("cloudflare"); System.setProperty("networkaddress.cache.ttl", "0"); Awaitility.await().pollDelay(10, TimeUnit.SECONDS).atMost(30, TimeUnit.SECONDS).ignoreExceptions().untilAsserted(()-> { String body = RestAssured.given().baseUri(url) .get() .body() .print(); assertThat(body.trim()).as("the index page contains the title 'Hello world'").contains("Hello world"); }); ``` -------------------------------- ### Retrieving Public Tunnel URL from CloudflaredContainer Logs in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md This method parses the container logs to extract the public URL generated by Cloudflare Quick Tunnel. It searches for the 'Your quick Tunnel has been created' line and then extracts the URL from the subsequent line, providing a programmatic way to access the exposed application. ```Java public String getPublicUrl() { if (null != publicUrl) { return publicUrl; } String logs = getLogs(); String[] split = logs.split(String.format("\\n")); boolean found = false; for (int i = 0; i < split.length; i++) { String currentLine = split[i]; if (currentLine.contains("Your quick Tunnel has been created")) { found = true; continue; } if (found) { return publicUrl = currentLine.substring(currentLine.indexOf("http"), currentLine.indexOf(".com") + 4); } } throw new IllegalStateException("Didn't find public url in logs. Has container started?"); } ``` -------------------------------- ### Updating SupabaseContainer getPassword Method Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-1/README.md This method updates the `getPassword()` implementation to return the dynamically set `password` field, rather than a hardcoded value. This ensures that the custom password configured via `withPassword()` is used when establishing database connections. ```java public String getPassword() { return this.password; } ``` -------------------------------- ### Setting MongoDB Replica Set Command in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet shows how to set the default command for a MongoDB container to initialize a replica set named 'docker-rs'. This is a common practice for running MongoDB in a clustered environment for integration tests. ```Java setCommand("--replSet", "docker-rs"); ``` -------------------------------- ### Overriding Cloudflared Container Command for Tunnel in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-8/README.md This snippet overrides the default command for the `CloudflaredContainer` to configure the Cloudflare tunnel. It sets up the `cloudflared` command with `tunnel --url` pointing to the application running on the host machine at the specified port, using `host.testcontainers.internal` for host resolution. ```Java withCommand("tunnel", "--url", String.format("http://host.testcontainers.internal:%d", port)); ``` -------------------------------- ### Creating Custom WireMock Connection Details Factory in Spring Boot Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-7/README.md This Java class extends `ContainerConnectionDetailsFactory` to provide custom connection details for `WireMockContainer`. It defines how Spring Boot can extract the base URL and a hardcoded token from a running WireMock container, enabling `@ServiceConnection` support. ```Java import org.springframework.boot.testcontainers.service.connection.ContainerConnectionDetailsFactory; import org.springframework.boot.testcontainers.service.connection.ContainerConnectionSource; import org.wiremock.integrations.testcontainers.WireMockContainer; class WireMockContainerConnectionDetailsFactory extends ContainerConnectionDetailsFactory { WireMockContainerConnectionDetailsFactory() { } protected GHConnectionDetails getContainerConnectionDetails(ContainerConnectionSource source) { return new WireMockContainerConnectionDetails(source); } private static final class WireMockContainerConnectionDetails extends ContainerConnectionDetails implements GHConnectionDetails { private WireMockContainerConnectionDetails(ContainerConnectionSource source) { super(source); } @Override public String url() { return getContainer().getBaseUrl(); } @Override public String token() { return "test-token"; } } } ``` -------------------------------- ### Adding ServiceConnection Annotation to WireMock Container in Spring Boot Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-7/README.md This Java snippet demonstrates how to apply the `@ServiceConnection` annotation to a `WireMockContainer` instance. This annotation instructs Spring Boot to automatically configure connection properties using the custom `ConnectionDetailsFactory`. ```Java @ServiceConnection static WireMockContainer wireMock = new WireMockContainer("wiremock/wiremock:3.2.0-alpine") ``` -------------------------------- ### Removing DynamicPropertySource for WireMock in Spring Boot Tests Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-7/README.md This snippet shows the `DynamicPropertySource` configuration that needs to be removed when transitioning to Spring Boot's `ServiceConnection` mechanism. It previously manually registered `github.url` and `github.token` properties for the WireMock container. ```Java @DynamicPropertySource static void properties(DynamicPropertyRegistry registry) { registry.add("github.url", wireMock::getBaseUrl); registry.add("github.token", () -> "test"); } ``` -------------------------------- ### Adding Sharding Enabled Field to MongoDBContainer in Java Source: https://github.com/testcontainers/java-module-workshop/blob/main/module-2/README.md This snippet adds a private boolean field `shardingEnabled` to the `MongoDBContainer` class. This field acts as a flag to control whether sharding-specific logic should be applied during the container's lifecycle. ```Java private boolean shardingEnabled; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.