How to use MockTestcontainersConfigurationRule method of org.testcontainers.containers.ReusabilityUnitTests class

Best Testcontainers-java code snippet using org.testcontainers.containers.ReusabilityUnitTests.MockTestcontainersConfigurationRule

Source:ReusabilityUnitTests.java Github

copy

Full Screen

...21import org.rnorth.visibleassertions.VisibleAssertions;22import org.testcontainers.DockerClientFactory;23import org.testcontainers.containers.startupcheck.StartupCheckStrategy;24import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy;25import org.testcontainers.utility.MockTestcontainersConfigurationRule;26import org.testcontainers.utility.MountableFile;27import org.testcontainers.utility.TestcontainersConfiguration;28import java.io.File;29import java.nio.file.Files;30import java.nio.file.Path;31import java.util.ArrayList;32import java.util.Collections;33import java.util.List;34import java.util.Map;35import java.util.UUID;36import java.util.concurrent.CompletableFuture;37import java.util.concurrent.atomic.AtomicReference;38import java.util.function.Consumer;39import java.util.stream.Collectors;40import java.util.stream.Stream;41import static org.assertj.core.api.Assertions.assertThat;42import static org.assertj.core.api.Assumptions.assumeThat;43import static org.mockito.ArgumentMatchers.any;44import static org.mockito.Mockito.when;45@RunWith(Enclosed.class)46public class ReusabilityUnitTests {47 static final CompletableFuture<String> IMAGE_FUTURE = CompletableFuture.completedFuture(48 TestcontainersConfiguration.getInstance().getTinyImage()49 );50 @RunWith(Parameterized.class)51 @RequiredArgsConstructor52 @FieldDefaults(makeFinal = true)53 public static class CanBeReusedTest {54 @Parameterized.Parameters(name = "{0}")55 public static Object[][] data() {56 return new Object[][] {57 { "generic", new GenericContainer(IMAGE_FUTURE), true },58 { "anonymous generic", new GenericContainer(IMAGE_FUTURE) {}, true },59 { "custom", new CustomContainer(), true },60 { "anonymous custom", new CustomContainer() {}, true },61 { "custom with containerIsCreated", new CustomContainerWithContainerIsCreated(), false },62 };63 }64 String name;65 GenericContainer container;66 boolean reusable;67 @Test68 public void shouldBeReusable() {69 if (reusable) {70 VisibleAssertions.assertTrue("Is reusable", container.canBeReused());71 } else {72 VisibleAssertions.assertFalse("Is not reusable", container.canBeReused());73 }74 }75 static class CustomContainer extends GenericContainer {76 CustomContainer() {77 super(IMAGE_FUTURE);78 }79 }80 static class CustomContainerWithContainerIsCreated extends GenericContainer {81 CustomContainerWithContainerIsCreated() {82 super(IMAGE_FUTURE);83 }84 @Override85 protected void containerIsCreated(String containerId) {86 super.containerIsCreated(containerId);87 }88 }89 }90 @RunWith(BlockJUnit4ClassRunner.class)91 @FieldDefaults(makeFinal = true)92 public static class HooksTest extends AbstractReusabilityTest {93 List<String> script = new ArrayList<>();94 GenericContainer<?> container = makeReusable(new GenericContainer(IMAGE_FUTURE) {95 @Override96 protected boolean canBeReused() {97 // Because we override "containerIsCreated"98 return true;99 }100 @Override101 protected void containerIsCreated(String containerId) {102 script.add("containerIsCreated");103 }104 @Override105 protected void containerIsStarting(InspectContainerResponse containerInfo, boolean reused) {106 script.add("containerIsStarting(reused=" + reused + ")");107 }108 @Override109 protected void containerIsStarted(InspectContainerResponse containerInfo, boolean reused) {110 script.add("containerIsStarted(reused=" + reused + ")");111 }112 });113 @Test114 public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() {115 Mockito.doReturn(false).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();116 String containerId = randomContainerId();117 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));118 when(client.listContainersCmd()).then(listContainersAnswer());119 when(client.startContainerCmd(containerId)).then(startContainerAnswer());120 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());121 container.start();122 assertThat(script).containsExactly(123 "containerIsCreated",124 "containerIsStarting(reused=false)",125 "containerIsStarted(reused=false)"126 );127 }128 @Test129 public void shouldCallHookIfReused() {130 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();131 String containerId = randomContainerId();132 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));133 String existingContainerId = randomContainerId();134 when(client.listContainersCmd()).then(listContainersAnswer(existingContainerId));135 when(client.inspectContainerCmd(existingContainerId)).then(inspectContainerAnswer());136 container.start();137 assertThat(script).containsExactly(138 "containerIsStarting(reused=true)",139 "containerIsStarted(reused=true)"140 );141 }142 @Test143 public void shouldNotCallHookIfNotReused() {144 String containerId = randomContainerId();145 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));146 when(client.listContainersCmd()).then(listContainersAnswer());147 when(client.startContainerCmd(containerId)).then(startContainerAnswer());148 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());149 container.start();150 assertThat(script).containsExactly(151 "containerIsCreated",152 "containerIsStarting(reused=false)",153 "containerIsStarted(reused=false)"154 );155 }156 }157 @RunWith(BlockJUnit4ClassRunner.class)158 @FieldDefaults(makeFinal = true)159 public static class HashTest extends AbstractReusabilityTest {160 protected GenericContainer<?> container = makeReusable(new GenericContainer(IMAGE_FUTURE) {161 @Override162 public void copyFileToContainer(MountableFile mountableFile, String containerPath) {163 // NOOP164 }165 });166 @Test167 public void shouldStartIfListReturnsEmpty() {168 String containerId = randomContainerId();169 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));170 when(client.listContainersCmd()).then(listContainersAnswer());171 when(client.startContainerCmd(containerId)).then(startContainerAnswer());172 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());173 container.start();174 Mockito.verify(client, Mockito.atLeastOnce()).startContainerCmd(containerId);175 }176 @Test177 public void shouldReuseIfListReturnsID() {178 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();179 String containerId = randomContainerId();180 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));181 String existingContainerId = randomContainerId();182 when(client.listContainersCmd()).then(listContainersAnswer(existingContainerId));183 when(client.inspectContainerCmd(existingContainerId)).then(inspectContainerAnswer());184 container.start();185 Mockito.verify(client, Mockito.never()).startContainerCmd(containerId);186 Mockito.verify(client, Mockito.never()).startContainerCmd(existingContainerId);187 }188 @Test189 public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() {190 Mockito.doReturn(false).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();191 AtomicReference<CreateContainerCmd> commandRef = new AtomicReference<>();192 String containerId = randomContainerId();193 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId, commandRef::set));194 when(client.startContainerCmd(containerId)).then(startContainerAnswer());195 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());196 container.start();197 assertThat(commandRef)198 .isNotNull()199 .satisfies(command -> {200 assertThat(command.get().getLabels())201 .containsKeys(DockerClientFactory.TESTCONTAINERS_SESSION_ID_LABEL);202 });203 }204 @Test205 public void shouldSetCopiedFilesHashLabel() {206 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();207 AtomicReference<CreateContainerCmd> commandRef = new AtomicReference<>();208 String containerId = randomContainerId();209 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId, commandRef::set));210 when(client.listContainersCmd()).then(listContainersAnswer());211 when(client.startContainerCmd(containerId)).then(startContainerAnswer());212 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());213 container.start();214 assertThat(commandRef).isNotNull();215 assertThat(commandRef.get().getLabels())216 .containsKeys(GenericContainer.COPIED_FILES_HASH_LABEL);217 }218 @Test219 public void shouldHashCopiedFiles() {220 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();221 AtomicReference<CreateContainerCmd> commandRef = new AtomicReference<>();222 String containerId = randomContainerId();223 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId, commandRef::set));224 when(client.listContainersCmd()).then(listContainersAnswer());225 when(client.startContainerCmd(containerId)).then(startContainerAnswer());226 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());227 container.start();228 assertThat(commandRef).isNotNull();229 Map<String, String> labels = commandRef.get().getLabels();230 assertThat(labels).containsKeys(GenericContainer.COPIED_FILES_HASH_LABEL);231 String oldHash = labels.get(GenericContainer.COPIED_FILES_HASH_LABEL);232 // Simulate stop233 container.containerId = null;234 container.withCopyFileToContainer(235 MountableFile.forClasspathResource("test_copy_to_container.txt"),236 "/foo/bar"237 );238 container.start();239 assertThat(commandRef.get().getLabels()).hasEntrySatisfying(GenericContainer.COPIED_FILES_HASH_LABEL, newHash -> {240 assertThat(newHash).as("new hash").isNotEqualTo(oldHash);241 });242 }243 }244 @RunWith(BlockJUnit4ClassRunner.class)245 @FieldDefaults(makeFinal = true)246 public static class CopyFilesHashTest {247 GenericContainer<?> container = new GenericContainer(IMAGE_FUTURE);248 @Test249 public void empty() {250 assertThat(container.hashCopiedFiles()).isNotNull();251 }252 @Test253 public void oneFile() {254 long emptyHash = container.hashCopiedFiles().getValue();255 container.withCopyFileToContainer(256 MountableFile.forClasspathResource("test_copy_to_container.txt"),257 "/foo/bar"258 );259 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(emptyHash);260 }261 @Test262 public void differentPath() {263 MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt");264 container.withCopyFileToContainer(mountableFile, "/foo/bar");265 long hash1 = container.hashCopiedFiles().getValue();266 container.getCopyToFileContainerPathMap().clear();267 container.withCopyFileToContainer(mountableFile, "/foo/baz");268 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);269 }270 @Test271 public void detectsChangesInFile() throws Exception {272 Path path = File.createTempFile("reusable_test", ".txt").toPath();273 MountableFile mountableFile = MountableFile.forHostPath(path);274 container.withCopyFileToContainer(mountableFile, "/foo/bar");275 long hash1 = container.hashCopiedFiles().getValue();276 Files.write(path, UUID.randomUUID().toString().getBytes());277 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);278 }279 @Test280 public void multipleFiles() {281 container.withCopyFileToContainer(282 MountableFile.forClasspathResource("test_copy_to_container.txt"),283 "/foo/bar"284 );285 long hash1 = container.hashCopiedFiles().getValue();286 container.withCopyFileToContainer(287 MountableFile.forClasspathResource("mappable-resource/test-resource.txt"),288 "/foo/baz"289 );290 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);291 }292 @Test293 public void folder() throws Exception {294 long emptyHash = container.hashCopiedFiles().getValue();295 Path tempDirectory = Files.createTempDirectory("reusable_test");296 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);297 container.withCopyFileToContainer(mountableFile, "/foo/bar/");298 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(emptyHash);299 }300 @Test301 public void changesInFolder() throws Exception {302 Path tempDirectory = Files.createTempDirectory("reusable_test");303 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);304 assertThat(new File(mountableFile.getResolvedPath())).isDirectory();305 container.withCopyFileToContainer(mountableFile, "/foo/bar/");306 long hash1 = container.hashCopiedFiles().getValue();307 Path fileInFolder = Files.createFile(308 // Create file in the sub-folder309 Files.createDirectory(tempDirectory.resolve("sub")).resolve("test.txt")310 );311 assertThat(fileInFolder).exists();312 Files.write(fileInFolder, UUID.randomUUID().toString().getBytes());313 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);314 }315 @Test316 public void folderAndFile() throws Exception {317 Path tempDirectory = Files.createTempDirectory("reusable_test");318 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);319 assertThat(new File(mountableFile.getResolvedPath())).isDirectory();320 container.withCopyFileToContainer(mountableFile, "/foo/bar/");321 long hash1 = container.hashCopiedFiles().getValue();322 container.withCopyFileToContainer(323 MountableFile.forClasspathResource("test_copy_to_container.txt"),324 "/foo/baz"325 );326 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);327 }328 @Test329 public void filePermissions() throws Exception {330 Path path = File.createTempFile("reusable_test", ".txt").toPath();331 path.toFile().setExecutable(false);332 MountableFile mountableFile = MountableFile.forHostPath(path);333 container.withCopyFileToContainer(mountableFile, "/foo/bar");334 long hash1 = container.hashCopiedFiles().getValue();335 assumeThat(path.toFile().canExecute()).isFalse();336 path.toFile().setExecutable(true);337 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);338 }339 @Test340 public void folderPermissions() throws Exception {341 Path tempDirectory = Files.createTempDirectory("reusable_test");342 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);343 assertThat(new File(mountableFile.getResolvedPath())).isDirectory();344 Path subDir = Files.createDirectory(tempDirectory.resolve("sub"));345 subDir.toFile().setWritable(false);346 assumeThat(subDir.toFile().canWrite()).isFalse();347 container.withCopyFileToContainer(mountableFile, "/foo/bar/");348 long hash1 = container.hashCopiedFiles().getValue();349 subDir.toFile().setWritable(true);350 assumeThat(subDir.toFile()).canWrite();351 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);352 }353 }354 @FieldDefaults(makeFinal = true)355 public static abstract class AbstractReusabilityTest {356 @Rule357 public MockTestcontainersConfigurationRule configurationMock = new MockTestcontainersConfigurationRule();358 protected DockerClient client = Mockito.mock(DockerClient.class);359 protected <T extends GenericContainer<?>> T makeReusable(T container) {360 container.dockerClient = client;361 container.withNetworkMode("none"); // to disable the port forwarding362 container.withStartupCheckStrategy(new StartupCheckStrategy() {363 @Override364 public boolean waitUntilStartupSuccessful(DockerClient dockerClient, String containerId) {365 // Skip DockerClient rate limiter366 return true;367 }368 @Override369 public StartupStatus checkStartupState(DockerClient dockerClient, String containerId) {370 return StartupStatus.SUCCESSFUL;371 }...

Full Screen

Full Screen

MockTestcontainersConfigurationRule

Using AI Code Generation

copy

Full Screen

1 public void testReusability() {2 MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();3 mockTestcontainersConfigurationRule.withReuse(true);4 mockTestcontainersConfigurationRule.withReuseMode(ReuseMode.REUSE_CONTAINER);5 ReusabilityUnitTests reusabilityUnitTests = new ReusabilityUnitTests();6 reusabilityUnitTests.before();7 reusabilityUnitTests.testReusability();8 reusabilityUnitTests.after();9 }10 public void testReusability() {11 MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();12 mockTestcontainersConfigurationRule.withReuse(true);13 mockTestcontainersConfigurationRule.withReuseMode(ReuseMode.REUSE_CONTAINER);14 ReusabilityUnitTests reusabilityUnitTests = new ReusabilityUnitTests();15 reusabilityUnitTests.before();16 reusabilityUnitTests.testReusability();17 reusabilityUnitTests.after();18 }19 public void testReusability() {20 MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();21 mockTestcontainersConfigurationRule.withReuse(true);22 mockTestcontainersConfigurationRule.withReuseMode(ReuseMode.REUSE_CONTAINER);23 ReusabilityUnitTests reusabilityUnitTests = new ReusabilityUnitTests();24 reusabilityUnitTests.before();25 reusabilityUnitTests.testReusability();26 reusabilityUnitTests.after();27 }28 public void testReusability() {29 MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();30 mockTestcontainersConfigurationRule.withReuse(true);31 mockTestcontainersConfigurationRule.withReuseMode(ReuseMode.REUSE_CONTAINER);32 ReusabilityUnitTests reusabilityUnitTests = new ReusabilityUnitTests();33 reusabilityUnitTests.before();34 reusabilityUnitTests.testReusability();35 reusabilityUnitTests.after();36 }

Full Screen

Full Screen

MockTestcontainersConfigurationRule

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import org.junit.rules.TestRule;3import org.testcontainers.containers.MockTestcontainersConfigurationRule;4import org.testcontainers.containers.ReusabilityUnitTests;5public class ReusabilityUnitTestsTest {6 public void testReusability() {7 TestRule mockRule = new MockTestcontainersConfigurationRule();8 ReusabilityUnitTests.testReusability(mockRule);9 }10}

Full Screen

Full Screen

MockTestcontainersConfigurationRule

Using AI Code Generation

copy

Full Screen

1MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();2public void testReusabilityOfContainer() {3 final GenericContainer container = new GenericContainer("alpine:3.6")4 .withCommand("sleep", "9999")5 .withExposedPorts(22);6 container.start();7 assertThat(container.isRunning(), is(true));8 container.stop();9 assertThat(container.isRunning(), is(false));10}11MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();12public void testReusabilityOfContainer() {13 final GenericContainer container = new GenericContainer("alpine:3.6")14 .withCommand("sleep", "9999")15 .withExposedPorts(22);16 container.start();17 assertThat(container.isRunning(), is(true));18 container.stop();19 assertThat(container.isRunning(), is(false));20}21MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();22public void testReusabilityOfContainer() {23 final GenericContainer container = new GenericContainer("alpine:3.6")24 .withCommand("sleep", "9999")25 .withExposedPorts(22);26 container.start();27 assertThat(container.isRunning(), is(true));28 container.stop();29 assertThat(container.isRunning(), is(false));30}31MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();32public void testReusabilityOfContainer() {33 final GenericContainer container = new GenericContainer("alpine:3.6")34 .withCommand("sleep", "9999")35 .withExposedPorts(22);36 container.start();37 assertThat(container.isRunning(), is(true));38 container.stop();39 assertThat(container.isRunning(), is(false));40}41MockTestcontainersConfigurationRule mockTestcontainersConfigurationRule = new MockTestcontainersConfigurationRule();42public void testReusabilityOfContainer() {43 final GenericContainer container = new GenericContainer("alpine:3.6")44 .withCommand("sleep", "9999")45 .withExposedPorts(22);46 container.start();47 assertThat(container.isRunning(), is(true));48 container.stop();49 assertThat(container.isRunning(), is(false));50}

Full Screen

Full Screen

MockTestcontainersConfigurationRule

Using AI Code Generation

copy

Full Screen

1public void testReusabilityWithMockedConfig() {2 MockTestcontainersConfigurationRule mockRule = new MockTestcontainersConfigurationRule();3 mockRule.withReuse(true);4 mockRule.apply(null, null).evaluate();5 try {6 GenericContainer container = new GenericContainer("alpine:3.6");7 container.start();8 String containerId = container.getContainerId();9 container.stop();10 container.start();11 assertEquals(containerId, container.getContainerId());12 } finally {13 mockRule.apply(null, null).evaluate();14 }15}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful