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

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

Source:ReusabilityUnitTests.java Github

copy

Full Screen

...95 @RunWith(BlockJUnit4ClassRunner.class)96 @FieldDefaults(makeFinal = true)97 public static class HooksTest extends AbstractReusabilityTest {98 List<String> script = new ArrayList<>();99 GenericContainer<?> container = makeReusable(new GenericContainer(TINY_IMAGE) {100 @Override101 protected boolean canBeReused() {102 // Because we override "containerIsCreated"103 return true;104 }105 @Override106 protected void containerIsCreated(String containerId) {107 script.add("containerIsCreated");108 }109 @Override110 protected void containerIsStarting(InspectContainerResponse containerInfo, boolean reused) {111 script.add("containerIsStarting(reused=" + reused + ")");112 }113 @Override114 protected void containerIsStarted(InspectContainerResponse containerInfo, boolean reused) {115 script.add("containerIsStarted(reused=" + reused + ")");116 }117 });118 @Test119 public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() {120 Mockito.doReturn(false).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();121 String containerId = randomContainerId();122 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));123 when(client.listContainersCmd()).then(listContainersAnswer());124 when(client.startContainerCmd(containerId)).then(startContainerAnswer());125 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());126 container.start();127 assertThat(script).containsExactly(128 "containerIsCreated",129 "containerIsStarting(reused=false)",130 "containerIsStarted(reused=false)"131 );132 }133 @Test134 public void shouldCallHookIfReused() {135 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();136 String containerId = randomContainerId();137 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));138 String existingContainerId = randomContainerId();139 when(client.listContainersCmd()).then(listContainersAnswer(existingContainerId));140 when(client.inspectContainerCmd(existingContainerId)).then(inspectContainerAnswer());141 container.start();142 assertThat(script).containsExactly(143 "containerIsStarting(reused=true)",144 "containerIsStarted(reused=true)"145 );146 }147 @Test148 public void shouldNotCallHookIfNotReused() {149 String containerId = randomContainerId();150 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));151 when(client.listContainersCmd()).then(listContainersAnswer());152 when(client.startContainerCmd(containerId)).then(startContainerAnswer());153 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());154 container.start();155 assertThat(script).containsExactly(156 "containerIsCreated",157 "containerIsStarting(reused=false)",158 "containerIsStarted(reused=false)"159 );160 }161 }162 @RunWith(BlockJUnit4ClassRunner.class)163 @FieldDefaults(makeFinal = true)164 public static class HashTest extends AbstractReusabilityTest {165 protected GenericContainer<?> container = makeReusable(new GenericContainer(TINY_IMAGE) {166 @Override167 public void copyFileToContainer(MountableFile mountableFile, String containerPath) {168 // NOOP169 }170 });171 @Test172 public void shouldStartIfListReturnsEmpty() {173 String containerId = randomContainerId();174 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));175 when(client.listContainersCmd()).then(listContainersAnswer());176 when(client.startContainerCmd(containerId)).then(startContainerAnswer());177 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());178 container.start();179 Mockito.verify(client, Mockito.atLeastOnce()).startContainerCmd(containerId);180 }181 @Test182 public void shouldReuseIfListReturnsID() {183 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();184 String containerId = randomContainerId();185 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId));186 String existingContainerId = randomContainerId();187 when(client.listContainersCmd()).then(listContainersAnswer(existingContainerId));188 when(client.inspectContainerCmd(existingContainerId)).then(inspectContainerAnswer());189 container.start();190 Mockito.verify(client, Mockito.never()).startContainerCmd(containerId);191 Mockito.verify(client, Mockito.never()).startContainerCmd(existingContainerId);192 }193 @Test194 public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() {195 Mockito.doReturn(false).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();196 AtomicReference<CreateContainerCmd> commandRef = new AtomicReference<>();197 String containerId = randomContainerId();198 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId, commandRef::set));199 when(client.startContainerCmd(containerId)).then(startContainerAnswer());200 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());201 container.start();202 assertThat(commandRef)203 .isNotNull()204 .satisfies(command -> {205 assertThat(command.get().getLabels())206 .containsKeys(DockerClientFactory.TESTCONTAINERS_SESSION_ID_LABEL);207 });208 }209 @Test210 public void shouldSetCopiedFilesHashLabel() {211 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();212 AtomicReference<CreateContainerCmd> commandRef = new AtomicReference<>();213 String containerId = randomContainerId();214 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId, commandRef::set));215 when(client.listContainersCmd()).then(listContainersAnswer());216 when(client.startContainerCmd(containerId)).then(startContainerAnswer());217 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());218 container.start();219 assertThat(commandRef).isNotNull();220 assertThat(commandRef.get().getLabels())221 .containsKeys(GenericContainer.COPIED_FILES_HASH_LABEL);222 }223 @Test224 public void shouldHashCopiedFiles() {225 Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse();226 AtomicReference<CreateContainerCmd> commandRef = new AtomicReference<>();227 String containerId = randomContainerId();228 when(client.createContainerCmd(any())).then(createContainerAnswer(containerId, commandRef::set));229 when(client.listContainersCmd()).then(listContainersAnswer());230 when(client.startContainerCmd(containerId)).then(startContainerAnswer());231 when(client.inspectContainerCmd(containerId)).then(inspectContainerAnswer());232 container.start();233 assertThat(commandRef).isNotNull();234 Map<String, String> labels = commandRef.get().getLabels();235 assertThat(labels).containsKeys(GenericContainer.COPIED_FILES_HASH_LABEL);236 String oldHash = labels.get(GenericContainer.COPIED_FILES_HASH_LABEL);237 // Simulate stop238 container.containerId = null;239 container.withCopyFileToContainer(240 MountableFile.forClasspathResource("test_copy_to_container.txt"),241 "/foo/bar"242 );243 container.start();244 assertThat(commandRef.get().getLabels()).hasEntrySatisfying(GenericContainer.COPIED_FILES_HASH_LABEL, newHash -> {245 assertThat(newHash).as("new hash").isNotEqualTo(oldHash);246 });247 }248 }249 @RunWith(BlockJUnit4ClassRunner.class)250 @FieldDefaults(makeFinal = true)251 public static class CopyFilesHashTest {252 GenericContainer<?> container = new GenericContainer<>(TINY_IMAGE);253 @Test254 public void empty() {255 assertThat(container.hashCopiedFiles()).isNotNull();256 }257 @Test258 public void oneFile() {259 long emptyHash = container.hashCopiedFiles().getValue();260 container.withCopyFileToContainer(261 MountableFile.forClasspathResource("test_copy_to_container.txt"),262 "/foo/bar"263 );264 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(emptyHash);265 }266 @Test267 public void differentPath() {268 MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt");269 container.withCopyFileToContainer(mountableFile, "/foo/bar");270 long hash1 = container.hashCopiedFiles().getValue();271 container.getCopyToFileContainerPathMap().clear();272 container.withCopyFileToContainer(mountableFile, "/foo/baz");273 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);274 }275 @Test276 public void detectsChangesInFile() throws Exception {277 Path path = File.createTempFile("reusable_test", ".txt").toPath();278 MountableFile mountableFile = MountableFile.forHostPath(path);279 container.withCopyFileToContainer(mountableFile, "/foo/bar");280 long hash1 = container.hashCopiedFiles().getValue();281 Files.write(path, UUID.randomUUID().toString().getBytes());282 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);283 }284 @Test285 public void multipleFiles() {286 container.withCopyFileToContainer(287 MountableFile.forClasspathResource("test_copy_to_container.txt"),288 "/foo/bar"289 );290 long hash1 = container.hashCopiedFiles().getValue();291 container.withCopyFileToContainer(292 MountableFile.forClasspathResource("mappable-resource/test-resource.txt"),293 "/foo/baz"294 );295 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);296 }297 @Test298 public void folder() throws Exception {299 long emptyHash = container.hashCopiedFiles().getValue();300 Path tempDirectory = Files.createTempDirectory("reusable_test");301 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);302 container.withCopyFileToContainer(mountableFile, "/foo/bar/");303 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(emptyHash);304 }305 @Test306 public void changesInFolder() throws Exception {307 Path tempDirectory = Files.createTempDirectory("reusable_test");308 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);309 assertThat(new File(mountableFile.getResolvedPath())).isDirectory();310 container.withCopyFileToContainer(mountableFile, "/foo/bar/");311 long hash1 = container.hashCopiedFiles().getValue();312 Path fileInFolder = Files.createFile(313 // Create file in the sub-folder314 Files.createDirectory(tempDirectory.resolve("sub")).resolve("test.txt")315 );316 assertThat(fileInFolder).exists();317 Files.write(fileInFolder, UUID.randomUUID().toString().getBytes());318 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);319 }320 @Test321 public void folderAndFile() throws Exception {322 Path tempDirectory = Files.createTempDirectory("reusable_test");323 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);324 assertThat(new File(mountableFile.getResolvedPath())).isDirectory();325 container.withCopyFileToContainer(mountableFile, "/foo/bar/");326 long hash1 = container.hashCopiedFiles().getValue();327 container.withCopyFileToContainer(328 MountableFile.forClasspathResource("test_copy_to_container.txt"),329 "/foo/baz"330 );331 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);332 }333 @Test334 public void filePermissions() throws Exception {335 Path path = File.createTempFile("reusable_test", ".txt").toPath();336 path.toFile().setExecutable(false);337 MountableFile mountableFile = MountableFile.forHostPath(path);338 container.withCopyFileToContainer(mountableFile, "/foo/bar");339 long hash1 = container.hashCopiedFiles().getValue();340 assumeThat(path.toFile().canExecute()).isFalse();341 path.toFile().setExecutable(true);342 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);343 }344 @Test345 public void folderPermissions() throws Exception {346 Path tempDirectory = Files.createTempDirectory("reusable_test");347 MountableFile mountableFile = MountableFile.forHostPath(tempDirectory);348 assertThat(new File(mountableFile.getResolvedPath())).isDirectory();349 Path subDir = Files.createDirectory(tempDirectory.resolve("sub"));350 subDir.toFile().setWritable(false);351 assumeThat(subDir.toFile().canWrite()).isFalse();352 container.withCopyFileToContainer(mountableFile, "/foo/bar/");353 long hash1 = container.hashCopiedFiles().getValue();354 subDir.toFile().setWritable(true);355 assumeThat(subDir.toFile()).canWrite();356 assertThat(container.hashCopiedFiles().getValue()).isNotEqualTo(hash1);357 }358 }359 @FieldDefaults(makeFinal = true)360 public static abstract class AbstractReusabilityTest {361 @Rule362 public MockTestcontainersConfigurationRule configurationMock = new MockTestcontainersConfigurationRule();363 protected DockerClient client = Mockito.mock(DockerClient.class);364 protected <T extends GenericContainer<?>> T makeReusable(T container) {365 container.dockerClient = client;366 container.withNetworkMode("none"); // to disable the port forwarding367 container.withStartupCheckStrategy(new StartupCheckStrategy() {368 @Override369 public boolean waitUntilStartupSuccessful(DockerClient dockerClient, String containerId) {370 // Skip DockerClient rate limiter371 return true;372 }373 @Override374 public StartupStatus checkStartupState(DockerClient dockerClient, String containerId) {375 return StartupStatus.SUCCESSFUL;376 }377 });378 container.waitingFor(new AbstractWaitStrategy() {...

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