Best Testcontainers-java code snippet using org.testcontainers.utility.ResourceReaper.performCleanup
Source:ResourceReaper.java
...152 /**153 * Perform a cleanup.154 *155 */156 public synchronized void performCleanup() {157 registeredContainers.forEach(this::stopContainer);158 registeredNetworks.forEach(this::removeNetwork);159 }160 /**161 * Register a filter to be cleaned up.162 *163 * @param filter the filter164 */165 public void registerFilterForCleanup(List<Map.Entry<String, String>> filter) {166 synchronized (DEATH_NOTE) {167 DEATH_NOTE.add(filter);168 DEATH_NOTE.notifyAll();169 }170 }171 /**172 * Register a container to be cleaned up, either on explicit call to stopAndRemoveContainer, or at JVM shutdown.173 *174 * @param containerId the ID of the container175 * @param imageName the image name of the container (used for logging)176 */177 public void registerContainerForCleanup(String containerId, String imageName) {178 setHook();179 registeredContainers.put(containerId, imageName);180 }181 /**182 * Stop a potentially running container and remove it, including associated volumes.183 *184 * @param containerId the ID of the container185 */186 public void stopAndRemoveContainer(String containerId) {187 stopContainer(containerId, registeredContainers.get(containerId));188 registeredContainers.remove(containerId);189 }190 /**191 * Stop a potentially running container and remove it, including associated volumes.192 *193 * @param containerId the ID of the container194 * @param imageName the image name of the container (used for logging)195 */196 public void stopAndRemoveContainer(String containerId, String imageName) {197 stopContainer(containerId, imageName);198 registeredContainers.remove(containerId);199 }200 private void stopContainer(String containerId, String imageName) {201 boolean running;202 try {203 InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();204 running = containerInfo.getState().getRunning();205 } catch (NotFoundException e) {206 LOGGER.trace("Was going to stop container but it apparently no longer exists: {}");207 return;208 } catch (DockerException e) {209 LOGGER.trace("Error encountered when checking container for shutdown (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());210 return;211 }212 if (running) {213 try {214 LOGGER.trace("Stopping container: {}", containerId);215 dockerClient.killContainerCmd(containerId).exec();216 LOGGER.trace("Stopped container: {}", imageName);217 } catch (DockerException e) {218 LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());219 }220 }221 try {222 dockerClient.inspectContainerCmd(containerId).exec();223 } catch (NotFoundException e) {224 LOGGER.trace("Was going to remove container but it apparently no longer exists: {}");225 return;226 }227 try {228 LOGGER.trace("Removing container: {}", containerId);229 try {230 dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();231 LOGGER.debug("Removed container and associated volume(s): {}", imageName);232 } catch (InternalServerErrorException e) {233 LOGGER.trace("Exception when removing container with associated volume(s): {} (due to {})", imageName, e.getMessage());234 }235 } catch (DockerException e) {236 LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());237 }238 }239 /**240 * Register a network to be cleaned up at JVM shutdown.241 *242 * @param id the ID of the network243 */244 public void registerNetworkIdForCleanup(String id) {245 setHook();246 registeredNetworks.add(id);247 }248 /**249 * @param networkName the name of the network250 * @deprecated see {@link ResourceReaper#registerNetworkIdForCleanup(String)}251 */252 @Deprecated253 public void registerNetworkForCleanup(String networkName) {254 try {255 // Try to find the network by name, so that we can register its ID for later deletion256 dockerClient.listNetworksCmd()257 .withNameFilter(networkName)258 .exec()259 .forEach(network -> registerNetworkIdForCleanup(network.getId()));260 } catch (Exception e) {261 LOGGER.trace("Error encountered when looking up network (name: {})", networkName);262 }263 }264 /**265 * Removes a network by ID.266 * @param id267 */268 public void removeNetworkById(String id) {269 removeNetwork(id);270 }271 /**272 * Removes a network by ID.273 * @param identifier274 * @deprecated see {@link ResourceReaper#removeNetworkById(String)}275 */276 @Deprecated277 public void removeNetworks(String identifier) {278 removeNetworkById(identifier);279 }280 private void removeNetwork(String id) {281 try {282 List<Network> networks;283 try {284 // Try to find the network if it still exists285 // Listing by ID first prevents docker-java logging an error if we just go blindly into removeNetworkCmd286 networks = dockerClient.listNetworksCmd().withIdFilter(id).exec();287 } catch (Exception e) {288 LOGGER.trace("Error encountered when looking up network for removal (name: {}) - it may not have been removed", id);289 return;290 }291 // at this point networks should contain either 0 or 1 entries, depending on whether the network exists292 // using a for loop we essentially treat the network like an optional, only applying the removal if it exists293 for (Network network : networks) {294 try {295 dockerClient.removeNetworkCmd(network.getId()).exec();296 registeredNetworks.remove(network.getId());297 LOGGER.debug("Removed network: {}", id);298 } catch (Exception e) {299 LOGGER.trace("Error encountered removing network (name: {}) - it may not have been removed", network.getName());300 }301 }302 } finally {303 registeredNetworks.remove(id);304 }305 }306 public void unregisterNetwork(String identifier) {307 registeredNetworks.remove(identifier);308 }309 public void unregisterContainer(String identifier) {310 registeredContainers.remove(identifier);311 }312 private void setHook() {313 if (hookIsSet.compareAndSet(false, true)) {314 // If the JVM stops without containers being stopped, try and stop the container.315 Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, this::performCleanup));316 }317 }318}...
performCleanup
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer2import org.testcontainers.utility.ResourceReaper3def performCleanup() {4 ResourceReaper.instance.performCleanup()5 GenericContainer.performCleanup()6}7performCleanup()8import com.github.dockerjava.api.DockerClient9import com.github.dockerjava.api.command.InspectContainerResponse10import com.github.dockerjava.api.command.InspectImageResponse11import com.github.dockerjava.api.model.ExposedPort12import com.github.dockerjava.api.model.Ports13import com.github.dockerjava.core.DockerClientBuilder14import com.github.dockerjava.core.DefaultDockerClientConfig15def config = DefaultDockerClientConfig.createDefaultConfigBuilder().build()16def dockerClient = DockerClientBuilder.getInstance(config).build()17def cleanupNetworks() {18 def networks = dockerClient.listNetworksCmd().exec()19 networks.each { network ->20 if (network.getName().startsWith("testcontainers-")) {21 dockerClient.removeNetworkCmd(network.getId()).exec()22 }23 }24}25def cleanupContainers() {26 def containers = dockerClient.listContainersCmd().exec()27 containers.each { container ->28 def inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec()29 if (inspectContainerResponse.getName().startsWith("/testcontainers-")) {30 dockerClient.removeContainerCmd(container.getId()).exec()31 }32 }33}34def cleanupImages() {35 def images = dockerClient.listImagesCmd().exec()36 images.each { image ->37 def inspectImageResponse = dockerClient.inspectImageCmd(image.getId()).exec()38 if (inspectImageResponse.getRepoTags().find { it.startsWith("testcontainers/") }) {39 dockerClient.removeImageCmd(image.getId()).exec()40 }41 }42}43cleanupNetworks()44cleanupContainers()45cleanupImages()46import com.github.dockerjava.api.DockerClient
performCleanup
Using AI Code Generation
1import org.testcontainers.utility.ResourceReaper2def cleanupDockerResources() {3 ResourceReaper.performCleanup()4}5cleanupDockerResources()6test {7}8tasks.test {9 finalizedBy(shutdownHook)10}11shutdownHook {12 doLast {13 cleanupDockerResources()14 }15}16test {17}18tasks.test {19 finalizedBy(stopTestContainers)20}21task stopTestContainers {22 doLast {23 }24}25test {26}27tasks.test {28 finalizedBy(shutdownHook)29}30shutdownHook {31 doLast {32 cleanupDockerResources()33 }34}
performCleanup
Using AI Code Generation
1import org.testcontainers.utility.ResourceReaper2def cleanupDockerResources() {3 ResourceReaper.performCleanup()4}5cleanupDockerResources()6test {7}8tasks.test {9 finalizedBy(shutdownHook)10}11shutdownHook {12 doLast {13 cleanupDockerResources()14 }15}16test {17}18tasks.test {19 finalizedBy(stopTestContainers)20}21task stopTestContainers {22 doLast {23 }24}25test {26}27tasks.test {28 finalizedBy(shutdownHook)29}30shutdownHook {31 doLast {32 cleanupDockerResources()33 }34}
performCleanup
Using AI Code Generation
1duf cleanup = { ResourceReaper.performCleanup() }2def cleanup = { ResourceReaper.performCleanup() }3def cleanup = { ResourceReaper.performCleanup() }4def cleanup er{ Resour(eReaper.perf)rmCleaup() }5def cleanup = { ResourceReaper.performCleanup() }6def cleanup = { ResourceReaper.performCleanup() }7def cleanup = { ResourceReaper.performCleanup() }8def cleanup = { ResourceReaper.performCleanup() }9def cleanup = { ResourceReaper.performCleanup() }10def cleanup = { ResourceReaper.performCleanup() }
performCleanup
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.output.Slf4jLogConsumer;3import org.testcontainers.containers.wait.strategy.Wait;4import org.testcontainers.utility.ResourceReaper;5import java.io.File;6import java.io.IOException;7import java.nio.file.Files;8import java.nio.file.Path;9import java.nio.file.Paths;10import java.util.Arrays;11import java.util.List;12import java.util.concurrent.TimeUnit;13import java.util.stream.Collectors;14import org.slf4j.Logger;15import org.slf4j.LoggerFactory;16public class TestcontainersDemo {17 private static final Logger log = LoggerFactory.getLogger(TestcontainersDemo.class);18 public static void main(String[] args) throws Exception {19 Path volumePath = Paths.get(System.getProperty("java.io.tmpdir"), "testcontainers-demo");20 Files.createDirectories(volumePath);21 Path filePath = Paths.get(volumePath.toString(), "test.txt");22 Files.write(filePath, "Hello World!".getBytes());23 GenericContainer container = new GenericContainer("busybox:1.31.1")24 .withCommand("sh", "-c", "while true; do date > /data/test.txt; sleep 1; done")25 .withExposedPorts(80)26 .withFileSystemBind(volumePath.toString(), "/data")27 .waitingFor(Wait.forLogMessage(".*", 1));28 container.start();29 int port = container.getMappedPort(80);30 String ip = container.getContainerIpAddress();31 String containerId = container.getContainerId();32 String containerName = container.getContainerName();33 List<String> containerLabels = container.getLabels();34 String containerImage = container.getDockerImageName();35 String hostConfig = container.getHostConfig();
performCleanup
Using AI Code Generation
1def cleanup = { ResourceReaper.performCleanup() }2def cleanup = { ResourceReaper.performCleanup() }3def cleanup = { ResourceReaper.performCleanup() }4def cleanup = { ResourceReaper.performCleanup() }5def cleanup = { ResourceReaper.performCleanup() }6def cleanup = { ResourceReaper.performCleanup() }7def cleanup = { ResourceReaper.performCleanup() }8def cleanup = { ResourceReaper.performCleanup() }9def cleanup = { ResourceReaper.performCleanup() }10def cleanup = { ResourceReaper.performCleanup() }
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!!