Best Testcontainers-java code snippet using org.testcontainers.utility.ResourceReaper
Source:BaseTest.java
...5import org.springframework.boot.test.web.server.LocalServerPort;6import org.testcontainers.containers.Network;7import org.testcontainers.containers.ToxiproxyContainer;8import org.testcontainers.utility.DockerImageName;9import org.testcontainers.utility.ResourceReaper;10import ru.jpoint.r2dbcdemo.jdbc.ReactiveJdbcService;11import ru.jpoint.r2dbcdemo.r2dbc.R2dbcService;12@Slf4j13@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)14abstract class BaseTest {15 private static final String TOXIPROXY_NETWORK_ALIAS = "toxiproxy";16 private static final Network NETWORK = Network.newNetwork();17 protected static final R2dbcDemoPostgresqlContainer POSTGRESQL_CONTAINER;18 protected static final ToxiproxyContainer TOXIPROXY_CONTAINER;19 protected static final ToxiproxyContainer.ContainerProxy PROXY;20 @LocalServerPort21 protected int localServerPort;22 static {23 ResourceReaper.instance().registerNetworkIdForCleanup(NETWORK.getId());24 POSTGRESQL_CONTAINER = R2dbcDemoPostgresqlContainer.getInstance()25 .withExposedPorts(5432)26 .withNetwork(NETWORK);27 POSTGRESQL_CONTAINER.start();28 log.info("Postgresql container started. Address: {}, port: {}",29 POSTGRESQL_CONTAINER.getHost(),30 POSTGRESQL_CONTAINER.getFirstMappedPort());31 TOXIPROXY_CONTAINER = new ToxiproxyContainer(DockerImageName.parse("shopify/toxiproxy:2.1.0"))32 .withNetwork(NETWORK)33 .withNetworkAliases(TOXIPROXY_NETWORK_ALIAS);34 TOXIPROXY_CONTAINER.start();35 PROXY = TOXIPROXY_CONTAINER.getProxy(POSTGRESQL_CONTAINER, 5432);36 var r2dbcUrl = POSTGRESQL_CONTAINER.getR2dbcUrl(PROXY.getContainerIpAddress(), PROXY.getProxyPort());37 System.setProperty("DB_URL", r2dbcUrl);...
Source:FlyteSandboxNetwork.java
...22import java.util.concurrent.atomic.AtomicBoolean;23import org.junit.rules.ExternalResource;24import org.testcontainers.DockerClientFactory;25import org.testcontainers.containers.Network;26import org.testcontainers.utility.ResourceReaper;27// see https://github.com/testcontainers/testcontainers-java/issues/308128class FlyteSandboxNetwork extends ExternalResource implements Network {29 private static final String NAME = "flyte-sandbox";30 private final AtomicBoolean initialized = new AtomicBoolean();31 private String id;32 static final Network INSTANCE = new FlyteSandboxNetwork();33 private FlyteSandboxNetwork() {}34 @Override35 public String getId() {36 if (initialized.compareAndSet(false, true)) {37 id = create();38 }39 return id;40 }41 private String create() {42 List<com.github.dockerjava.api.model.Network> existing =43 DockerClientFactory.instance().client().listNetworksCmd().withNameFilter(NAME).exec();44 if (!existing.isEmpty()) {45 return existing.get(0).getId();46 }47 CreateNetworkCmd createNetworkCmd = DockerClientFactory.instance().client().createNetworkCmd();48 createNetworkCmd.withName(NAME);49 createNetworkCmd.withCheckDuplicate(true);50 Map<String, String> dockerLabels = createNetworkCmd.getLabels();51 Map<String, String> allLabels = new HashMap<>();52 if (dockerLabels != null) {53 allLabels.putAll(dockerLabels);54 }55 allLabels.putAll(DockerClientFactory.DEFAULT_LABELS);56 return createNetworkCmd.withLabels(allLabels).exec().getId();57 }58 @Override59 protected void after() {60 close();61 }62 @Override63 public void close() {64 if (initialized.getAndSet(false)) {65 ResourceReaper.instance().removeNetworkById(NAME);66 }67 }68}...
Source:TeardownGoalMojo.java
...3import org.apache.maven.plugin.MojoFailureException;4import org.apache.maven.plugins.annotations.LifecyclePhase;5import org.apache.maven.plugins.annotations.Mojo;6import org.testcontainers.containers.JdbcDatabaseContainer;7import org.testcontainers.utility.ResourceReaper;8import java.util.Optional;9@Mojo(name = "teardown", defaultPhase = LifecyclePhase.GENERATE_SOURCES)10public class TeardownGoalMojo extends AbstractTickMojo{11 @Override12 public void execute() throws MojoExecutionException, MojoFailureException {13 getLog().info("(TICK) Attempting to retrieve container!");14 Optional<JdbcDatabaseContainer<?>> optional = singleton.getContainer();15 if (optional.isPresent()) {16 getLog().info("(TICK) Retrieved optional, attempting teardown!");17 ResourceReaper.instance().stopAndRemoveContainer(optional.get().getContainerId());18 getLog().info("(TICK) Teardown successful!");19 } else {20 throw new MojoFailureException("No container found to teardown!");21 }22 }23}...
ResourceReaper
Using AI Code Generation
1import org.testcontainers.containers.PostgreSQLContainer;2import org.testcontainers.utility.ResourceReaper;3public class 1 {4 public static void main(String[] args) {5 PostgreSQLContainer container = new PostgreSQLContainer();6 container.start();7 String containerId = container.getContainerId();8 ResourceReaper.startInstance();9 ResourceReaper.instance().stopAndRemoveContainer(containerId);10 }11}12import com.github.dockerjava.api.DockerClient;13import com.github.dockerjava.api.command.InspectContainerResponse;14import com.github.dockerjava.api.model.Container;15import com.github.dockerjava.api.model.ContainerState;16import org.testcontainers.containers.PostgreSQLContainer;17import org.testcontainers.dockerclient.DockerClientFactory;18import java.util.List;19public class 2 {20 public static void main(String[] args) {21 PostgreSQLContainer container = new PostgreSQLContainer();22 container.start();23 String containerId = container.getContainerId();24 DockerClient dockerClient = DockerClientFactory.instance().client();25 List<Container> containers = dockerClient.listContainersCmd().exec();26 for (Container c : containers) {27 if (c.getId().equals(containerId)) {28 dockerClient.removeContainerCmd(containerId).exec();29 }30 }31 }32}33import com.github.dockerjava.api.DockerClient;34import com.github.dockerjava.api.command.InspectContainerResponse;35import com.github.dockerjava.api.model.Container;36import com.github.dockerjava.api.model.ContainerState;37import org.testcontainers.containers.PostgreSQLContainer;38import org.testcontainers.dockerclient.DockerClientFactory;39import java.util.List;40public class 3 {41 public static void main(String[] args) {42 PostgreSQLContainer container = new PostgreSQLContainer();43 container.start();44 String containerId = container.getContainerId();45 DockerClient dockerClient = DockerClientFactory.instance().client();46 List<Container> containers = dockerClient.listContainersCmd().exec();47 for (Container c : containers) {48 if (c.getId().equals(containerId)) {49 InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(containerId).exec();50 ContainerState containerState = containerResponse.getState();51 if (containerState.getRunning()) {52 dockerClient.killContainerCmd(containerId).exec();
ResourceReaper
Using AI Code Generation
1package org.testcontainers.utility;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.PostgreSQLContainer;4import org.testcontainers.containers.wait.strategy.Wait;5import org.testcontainers.utility.ResourceReaper;6import java.io.IOException;7import java.util.concurrent.TimeUnit;8public class Test {9 public static void main(String[] args) throws IOException {10 PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:9.6.8")11 .withDatabaseName("test")12 .withUsername("test")13 .withPassword("test")14 .withExposedPorts(5432)15 .waitingFor(Wait.forLogMessage(".*database system is ready to accept connections.*\\s", 1));16 postgres.start();17 ResourceReaper.instance().stopAndRemoveContainer(postgres.getContainerId());18 }19}20package org.testcontainers.utility;21import org.testcontainers.containers.GenericContainer;22import org.testcontainers.containers.PostgreSQLContainer;23import org.testcontainers.containers.wait.strategy.Wait;24import org.testcontainers.utility.ResourceReaper;25import java.io.IOException;26import java.util.concurrent.TimeUnit;27public class Test {28 public static void main(String[] args) throws IOException {29 PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:9.6.8")30 .withDatabaseName("test")31 .withUsername("test")32 .withPassword("test")33 .withExposedPorts(5432)34 .waitingFor(Wait.forLogMessage(".*database system is ready to accept connections.*\\s", 1));35 postgres.start();36 postgres.stop();37 }38}
ResourceReaper
Using AI Code Generation
1package org.testcontainers.utility;2import java.io.IOException;3import java.nio.file.Files;4import java.nio.file.Path;5import java.nio.file.Paths;6import java.util.List;7import java.util.stream.Collectors;8import org.testcontainers.DockerClientFactory;9import org.testcontainers.containers.GenericContainer;10import org.testcontainers.containers.startupcheck.StartupCheckStrategy;11import org.testcontainers.images.builder.ImageFromDockerfile;12public class ResourceReaperTest {13 public static void main(String[] args) throws IOException, InterruptedException {14 final String imageName = "testcontainers/ryuk:0.2.3";15 final Path dockerfilePath = Paths.get("Dockerfile.ryuk");16 final String dockerfileContent = new String(Files.readAllBytes(dockerfilePath));17 final ImageFromDockerfile image = new ImageFromDockerfile(imageName, false)18 .withDockerfileFromBuilder(builder -> builder.from("openjdk:8-jre-alpine").withDockerfile(dockerfileContent));19 final GenericContainer<?> ryukContainer = new GenericContainer<>(image)20 .withStartupCheckStrategy(new StartupCheckStrategy() {21 public StartupStatus checkStartupState(DockerClientFactory clientFactory, String containerId) {22 return StartupStatus.SUCCESSFUL;23 }24 })25 .withExposedPorts(8080)26 .withCommand("--port", "8080");27 ryukContainer.start();28 final ResourceReaper resourceReaper = new ResourceReaper();29 resourceReaper.start();30 final List<String> containerIds = DockerClientFactory.instance().client().listContainersCmd().exec().stream()31 .map(container -> container.getId())32 .collect(Collectors.toList());33 resourceReaper.registerResourceReaper(containerIds);34 Thread.sleep(10000);35 ryukContainer.stop();36 resourceReaper.stop();37 }38}
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!!