Best Testcontainers-java code snippet using org.testcontainers.lifecycle.Startables
Source:TestcontainersExtension.java
...43 @Override44 public void beforeContainer(ContainerLifecycleContext context) {45 Class<?> testClass = context.optionalContainerClass()46 .orElseThrow(() -> new IllegalStateException("TestcontainersExtension is only supported for classes."));47 Store<ClosableStartables> store = getOrCreateContainerClosingStore(IDENTIFIER, Lifespan.RUN);48 List<TestLifecycleAware> lifecycleAwareContainers = startContainersAndFindLifeCycleAwareOnes(store, findSharedContainers(testClass));49 Store.getOrCreate(SHARED_LIFECYCLE_AWARE_TEST_CONTAINERS, Lifespan.RUN, () -> lifecycleAwareContainers);50 signalBeforeTestToContainers(lifecycleAwareContainers, testDescriptionFrom(context));51 }52 @Override53 public void afterContainer(ContainerLifecycleContext context) {54 Store<List<TestLifecycleAware>> containers = Store55 .getOrCreate(SHARED_LIFECYCLE_AWARE_TEST_CONTAINERS, Lifespan.RUN, ArrayList::new);56 signalAfterTestToContainersFor(containers.get(), testDescriptionFrom(context));57 }58 @Override59 public int proximity() {60 // must be run before the @BeforeContainer annotation and after @AfterContainer annotation61 return -11;62 }63 @Override64 public PropertyExecutionResult aroundProperty(PropertyLifecycleContext context, PropertyExecutor property) {65 Object testInstance = context.testInstance();66 Store<ClosableStartables> store = getOrCreateContainerClosingStore(property.hashCode(), Lifespan.PROPERTY);67 List<TestLifecycleAware> lifecycleAwareContainers = startContainersAndFindLifeCycleAwareOnes(store, findRestartContainers(testInstance));68 TestDescription testDescription = testDescriptionFrom(context);69 signalBeforeTestToContainers(lifecycleAwareContainers, testDescription);70 PropertyExecutionResult executionResult = property.execute();71 signalAfterTestToContainersFor(lifecycleAwareContainers, testDescription, executionResult);72 return executionResult;73 }74 @Override75 public int aroundPropertyProximity() {76 return -11; // Run before BeforeProperty and after AfterProperty77 }78 @Override79 public TryExecutionResult aroundTry(TryLifecycleContext context, TryExecutor aTry, List<Object> parameters) {80 Object testInstance = context.testInstance();81 Store<ClosableStartables> store = getOrCreateContainerClosingStore(aTry.hashCode(), Lifespan.TRY);82 List<TestLifecycleAware> lifecycleAwareContainers = startContainersAndFindLifeCycleAwareOnes(store, findRestartContainersPerTry(testInstance));83 TestDescription testDescription = testDescriptionFrom(context);84 signalBeforeTestToContainers(lifecycleAwareContainers, testDescription);85 TryExecutionResult executionResult = aTry.execute(parameters);86 signalAfterTestToContainersFor(lifecycleAwareContainers, testDescription, executionResult);87 return executionResult;88 }89 @Override90 public int aroundTryProximity() {91 return -11; // Run before BeforeTry and after AfterTry92 }93 private Store<ClosableStartables> getOrCreateContainerClosingStore(Object identifier, Lifespan lifespan) {94 return Store.getOrCreate(identifier, lifespan, ClosableStartables::empty);95 }96 private List<TestLifecycleAware> startContainersAndFindLifeCycleAwareOnes(Store<ClosableStartables> store, Stream<Startable> containers) {97 return containers98 .peek(startable -> store.update(closableStartables -> {99 startable.start();100 closableStartables.add(startable);101 return closableStartables;102 }))103 .filter(this::isTestLifecycleAware)104 .map(startable -> (TestLifecycleAware) startable)105 .collect(toList());106 }107 private void signalBeforeTestToContainers(List<TestLifecycleAware> lifecycleAwareContainers, TestDescription testDescription) {108 lifecycleAwareContainers.forEach(container -> container.beforeTest(testDescription));109 }110 private void signalAfterTestToContainersFor(List<TestLifecycleAware> containers, TestDescription testDescription) {111 containers.forEach(container -> container.afterTest(testDescription, Optional.empty()));112 }113 private void signalAfterTestToContainersFor(114 List<TestLifecycleAware> containers,115 TestDescription testDescription,116 PropertyExecutionResult executionResult117 ) {118 containers.forEach(container -> {119 if (executionResult.status() == PropertyExecutionResult.Status.ABORTED) {120 container.afterTest(testDescription, Optional.of(new TestAbortedException()));121 } else {122 container.afterTest(testDescription, executionResult.throwable());123 }124 });125 }126 private void signalAfterTestToContainersFor(127 List<TestLifecycleAware> containers,128 TestDescription testDescription,129 TryExecutionResult executionResult130 ) {131 containers.forEach(container -> container.afterTest(testDescription, executionResult.throwable()));132 }133 private TestDescription testDescriptionFrom(LifecycleContext context) {134 return new TestcontainersTestDescription(135 context.label(),136 FilesystemFriendlyNameGenerator.filesystemFriendlyNameOf(context)137 );138 }139 private boolean isTestLifecycleAware(Startable startable) {140 return startable instanceof TestLifecycleAware;141 }142 @Override143 public SkipResult shouldBeSkipped(LifecycleContext context) {144 return findTestcontainers(context)145 .map(this::evaluateSkipResult)146 .orElseThrow(() -> new JqwikException("@Testcontainers not found"));147 }148 private Optional<Testcontainers> findTestcontainers(LifecycleContext context) {149 // Find closest TestContainers annotation150 Optional<Testcontainers> first = context.findAnnotationsInContainer(Testcontainers.class).stream().findFirst();151 if (first.isPresent())152 return first;153 else154 return context.findAnnotation(Testcontainers.class);155 }156 private SkipResult evaluateSkipResult(Testcontainers testcontainers) {157 if (testcontainers.disabledWithoutDocker()) {158 if (isDockerAvailable()) {159 return SkipResult.doNotSkip();160 }161 return SkipResult.skip("disabledWithoutDocker is true and Docker is not available");162 }163 return SkipResult.doNotSkip();164 }165 boolean isDockerAvailable() {166 try {167 DockerClientFactory.instance().client();168 return true;169 } catch (Throwable ex) {170 return false;171 }172 }173 private Stream<Startable> findSharedContainers(Class<?> testClass) {174 final Predicate<Field> isSharedContainer = ReflectionUtils::isStatic;175 return findContainers(null, isSharedContainer, testClass);176 }177 private Stream<Startable> findRestartContainers(Object testInstance) {178 final Predicate<Field> isRestartContainer = ReflectionUtils::isNotStatic;179 return findContainers(testInstance, isRestartContainer.and(restartPerTry().negate()), testInstance.getClass());180 }181 private Stream<Startable> findRestartContainersPerTry(Object testInstance) {182 final Predicate<Field> isRestartContainer = ReflectionUtils::isNotStatic;183 return findContainers(testInstance, isRestartContainer.and(restartPerTry()), testInstance.getClass());184 }185 private Stream<Startable> findContainers(Object testInstance, Predicate<Field> containerCondition, Class<?> testClass) {186 return ReflectionUtils.findFields(187 testClass,188 isContainer().and(containerCondition),189 ReflectionUtils.HierarchyTraversalMode.TOP_DOWN190 )191 .stream()192 .map(f -> getContainerInstance(testInstance, f));193 }194 private static class ClosableStartables implements Store.CloseOnReset {195 private final List<Startable> startables;196 private ClosableStartables(List<Startable> startables) {197 this.startables = startables;198 }199 private static ClosableStartables empty(){200 return of(new ArrayList<>());201 }202 private static ClosableStartables of(List<Startable> startables){203 return new ClosableStartables(startables);204 }205 public void add(Startable startable){206 startables.add(startable);207 }208 @Override209 public void close() {210 startables.forEach(Startable::close);211 }212 }213}...
Source:IntegrationTest.java
...4import org.springframework.core.env.ConfigurableEnvironment;5import org.springframework.core.env.MapPropertySource;6import org.springframework.test.context.ContextConfiguration;7import org.testcontainers.containers.GenericContainer;8import org.testcontainers.lifecycle.Startables;9import java.util.Map;10import java.util.stream.Stream;11@ContextConfiguration(12 initializers = IntegrationTest.Initializer.class)13public abstract class IntegrationTest {14 static class Initializer implements15 ApplicationContextInitializer<ConfigurableApplicationContext> {16 static GenericContainer<?> redis = new GenericContainer("redis")17 .withExposedPorts(6379);18 private static void startContainers() {19 Startables.deepStart(Stream.of(redis)).join();20 }21 private static Map<String, String> createConnectionConfiguration() {22 return Map.of(23 "dh.redis.host", redis.getHost(),24 "dh.redis.port", redis.getMappedPort(6379).toString()25 );26 }27 @Override28 public void initialize(29 ConfigurableApplicationContext applicationContext) {30 startContainers();31 ConfigurableEnvironment environment =32 applicationContext.getEnvironment();33 MapPropertySource testcontainers = new MapPropertySource(...
Source:TimetableApplicationTests.java
2import org.springframework.boot.test.context.SpringBootTest;3import org.testcontainers.containers.PostgreSQLContainer;4import org.testcontainers.junit.jupiter.Container;5import org.testcontainers.junit.jupiter.Testcontainers;6import org.testcontainers.lifecycle.Startables;7import java.util.stream.Stream;8@Testcontainers9@SpringBootTest10public class TimetableApplicationTests {11 @Container12 public static PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>("postgres:11.1");13 static {14 Startables.deepStart(Stream.of(postgresContainer)).join();15 System.setProperty("spring.datasource.url", postgresContainer.getJdbcUrl());16 System.setProperty("spring.datasource.username", postgresContainer.getUsername());17 System.setProperty("spring.datasource.password", postgresContainer.getPassword());18 }19}...
Startables
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.output.Slf4jLogConsumer;3import org.testcontainers.lifecycle.Startables;4import org.testcontainers.utility.DockerImageName;5import org.slf4j.Logger;6import org.slf4j.LoggerFactory;7import java.util.ArrayList;8import java.util.List;9public class StartablesExample {10 private static final Logger LOGGER = LoggerFactory.getLogger(StartablesExample.class);11 public static void main(String[] args) {12 GenericContainer redis = new GenericContainer(DockerImageName.parse("redis:5.0.9"))13 .withExposedPorts(6379)14 .withLogConsumer(new Slf4jLogConsumer(LOGGER));15 GenericContainer mongo = new GenericContainer(DockerImageName.parse("mongo:4.4.4"))16 .withExposedPorts(27017)17 .withLogConsumer(new Slf4jLogConsumer(LOGGER));18 List<GenericContainer> containers = new ArrayList<>();19 containers.add(redis);20 containers.add(mongo);21 try {22 Startables.deepStart(containers).get();23 } catch (Exception e) {24 throw new RuntimeException(e);25 }26 }27}282021-04-15 14:00:20.312 [main] INFO o.t.utility.RegistryAuthLocator - Credential helper/store (docker-credential-desktop) does not have credentials for index.docker.io
Startables
Using AI Code Generation
1import org.testcontainers.containers.PostgreSQLContainer;2import org.testcontainers.lifecycle.Startables;3import org.testcontainers.utility.DockerImageName;4import java.util.concurrent.CompletableFuture;5public class StartablesTest {6 public static void main(String[] args) {7 PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer(DockerImageName.parse("postgres:13.2"));8 PostgreSQLContainer postgreSQLContainer2 = new PostgreSQLContainer(DockerImageName.parse("postgres:13.2"));9 PostgreSQLContainer postgreSQLContainer3 = new PostgreSQLContainer(DockerImageName.parse("postgres:13.2"));10 CompletableFuture.allOf(11 Startables.deepStart(postgreSQLContainer).toCompletableFuture(),12 Startables.deepStart(postgreSQLContainer2).toCompletableFuture(),13 Startables.deepStart(postgreSQLContainer3).toCompletableFuture()14 ).join();15 System.out.println("All containers started");16 Startables.deepStop(postgreSQLContainer);17 Startables.deepStop(postgreSQLContainer2);18 Startables.deepStop(postgreSQLContainer3);19 }20}
Startables
Using AI Code Generation
1package com.mycompany.app;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.JdbcDatabaseContainer;4import org.testcontainers.containers.MySQLContainer;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.testcontainers.lifecycle.Startables;7import java.util.ArrayList;8import java.util.List;9public class App {10 public static void main(String[] args) {11 List<JdbcDatabaseContainer> containers = new ArrayList<>();12 containers.add(new MySQLContainer("mysql:5.7.22"));13 containers.add(new GenericContainer("postgres:9.6.8").withExposedPorts(5432));14 Startables.deepStart(containers).join();15 containers.forEach(container -> {16 System.out.println(container.getContainerIpAddress());17 System.out.println(container.getMappedPort(3306));18 });19 Startables.deepStop(containers).join();20 }21}
Startables
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.lifecycle.Startables;3import java.util.concurrent.CompletableFuture;4public class StartablesTest {5 public static void main(String[] args) {6 GenericContainer container1 = new GenericContainer("alpine:3.12.3");7 GenericContainer container2 = new GenericContainer("alpine:3.12.3");8 Startables.deepStart(CompletableFuture.allOf(container1.startAsync(), container2.startAsync())).join();9 }10}
Startables
Using AI Code Generation
1package org.testcontainers.lifecycle;2import java.util.ArrayList;3import java.util.List;4import org.testcontainers.containers.GenericContainer;5import org.testcontainers.containers.JdbcDatabaseContainer;6import org.testcontainers.containers.PostgreSQLContainer;7public class Startables {8 public static void deepStart(List<? extends Startable> startables) {9 List<Throwable> exceptions = new ArrayList<>();10 startables.forEach(startable -> {11 try {12 startable.start();13 } catch (Throwable t) {14 exceptions.add(t);15 }16 });17 if (!exceptions.isEmpty()) {18 throw new ContainerLaunchException("Could not start container", exceptions);19 }20 }21}22package org.testcontainers.lifecycle;23import java.util.ArrayList;24import java.util.List;25import org.testcontainers.containers.GenericContainer;26import org.testcontainers.containers.JdbcDatabaseContainer;27import org.testcontainers.containers.PostgreSQLContainer;28public class Startables {29 public static void deepStart(List<? extends Startable> startables) {30 List<Throwable> exceptions = new ArrayList<>();31 startables.forEach(startable -> {32 try {33 startable.start();34 } catch (Throwable t) {35 exceptions.add(t);36 }37 });38 if (!exceptions.isEmpty()) {39 throw new ContainerLaunchException("Could not start container", exceptions);40 }41 }42}
Startables
Using AI Code Generation
1import org.testcontainers.lifecycle.Startables;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.containers.wait.strategy.Wait;4import org.testcontainers.utility.DockerImageName;5public class App {6 public static void main(String[] args) throws Exception {7 GenericContainer<?> container1 = new GenericContainer<>(DockerImageName.parse("busybox:latest"))8 .withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")9 .waitingFor(Wait.forLogMessage(".*hello.*\\n", 1));10 GenericContainer<?> container2 = new GenericContainer<>(DockerImageName.parse("busybox:latest"))11 .withCommand("sh", "-c", "while true; do echo world; sleep 1; done")12 .waitingFor(Wait.forLogMessage(".*world.*\\n", 1));13 Startables.deepStart(Arrays.asList(container1, container2)).join();14 System.out.println("Containers started");15 Thread.sleep(30000);16 Startables.deepStop(Arrays.asList(container1, container2)).join();17 }18}19import org.testcontainers.lifecycle.Startables;20import org.testcontainers.containers.GenericContainer;21import org.testcontainers.containers.wait.strategy.Wait;22import org.testcontainers.utility.DockerImageName;23public class App {24 public static void main(String[] args) throws Exception {25 GenericContainer<?> container1 = new GenericContainer<>(DockerImageName.parse("busybox:latest"))26 .withCommand("sh", "-c", "while true; do echo hello; sleep 1; done")27 .waitingFor(Wait.forLogMessage(".*hello.*\\n", 1));28 GenericContainer<?> container2 = new GenericContainer<>(DockerImageName.parse("busybox:latest"))29 .withCommand("sh", "-c", "while true; do echo world; sleep 1; done")30 .waitingFor(Wait.forLogMessage(".*world.*\\n", 1));31 Startables.deepStart(Arrays.asList(container1, container2)).join();32 System.out.println("Containers started");33 Thread.sleep(30000);34 Startables.deepStop(Arrays.asList(container1, container2)).join();35 }36}
Startables
Using AI Code Generation
1package com.testcontainers;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.lifecycle.Startables;4import java.util.concurrent.CompletableFuture;5public class StartablesTest {6 public static void main(String[] args) throws Exception {7 GenericContainer container1 = new GenericContainer("alpine:3.8").withCommand("top");8 GenericContainer container2 = new GenericContainer("alpine:3.8").withCommand("top");9 GenericContainer container3 = new GenericContainer("alpine:3.8").withCommand("top");10 GenericContainer container4 = new GenericContainer("alpine:3.8").withCommand("top");11 GenericContainer container5 = new GenericContainer("alpine:3.8").withCommand("top");12 GenericContainer container6 = new GenericContainer("alpine:3.8").withCommand("top");13 container1.start();14 container2.start();15 container3.start();16 container4.start();17 container5.start();18 container6.start();19 CompletableFuture.allOf(20 Startables.deepStart(container1).toCompletableFuture(),21 Startables.deepStart(container2).toCompletableFuture(),22 Startables.deepStart(container3).toCompletableFuture(),23 Startables.deepStart(container4).toCompletableFuture(),24 Startables.deepStart(container5).toCompletableFuture(),25 Startables.deepStart(container6).toCompletableFuture()26 ).join();27 }28}29package com.testcontainers;30import org.testcontainers.containers.GenericContainer;31import org.testcontainers.lifecycle.Startables;32import java.util.concurrent.CompletableFuture;33public class StartablesTest {34 public static void main(String[] args) throws Exception {35 GenericContainer container1 = new GenericContainer("alpine:3.8").withCommand("top");36 GenericContainer container2 = new GenericContainer("alpine:3.8").withCommand("top");37 GenericContainer container3 = new GenericContainer("alpine:3.8").withCommand("top");38 GenericContainer container4 = new GenericContainer("alpine:3.8").withCommand("top");39 GenericContainer container5 = new GenericContainer("alpine:3.8").withCommand("top");40 GenericContainer container6 = new GenericContainer("alpine:3.8").withCommand("top");
Startables
Using AI Code Generation
1package org.testcontainers.lifecycle;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.utility.DockerImageName;4public class StartablesTest {5 public static void main(String[] args) {6 try (GenericContainer mysql = new GenericContainer(DockerImageName.parse("mysql:5.7.22"))7 .withExposedPorts(3306)8 .withEnv("MYSQL_ROOT_PASSWORD", "test")9 .withEnv("MYSQL_DATABASE", "test")) {10 Startables.deepStart(mysql).get();11 System.out.println("MySQL started");12 }13 }14}
Startables
Using AI Code Generation
1package org.testcontainers.lifecycle;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.lifecycle.Startables;4import java.util.concurrent.ExecutionException;5public class StartablesTest {6 public static void main(String[] args) throws ExecutionException, InterruptedException {7 GenericContainer container1 = new GenericContainer("alpine:3.12.0");8 GenericContainer container2 = new GenericContainer("alpine:3.12.0");9 GenericContainer container3 = new GenericContainer("alpine:3.12.0");10 Startables.deepStart(container1).get();11 Startables.deepStart(container2).get();12 Startables.deepStart(container3).get();13 System.out.println("Containers started");14 Startables.deepStop(container1).get();15 Startables.deepStop(container2).get();
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!!