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

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

Source:ReusabilityUnitTests.java Github

copy

Full Screen

...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() {379 @Override380 protected void waitUntilReady() {381 }382 });383 container.withReuse(true);384 return container;385 }386 protected String randomContainerId() {387 return UUID.randomUUID().toString();388 }389 protected Answer<ListContainersCmd> listContainersAnswer(String... ids) {390 return invocation -> {391 ListContainersCmd.Exec exec = command -> {392 return new ObjectMapper().convertValue(393 Stream.of(ids)394 .map(id -> Collections.singletonMap("Id", id))395 .collect(Collectors.toList()),396 new TypeReference<List<Container>>() {}397 );398 };399 return new ListContainersCmdImpl(exec);400 };401 }402 protected Answer<CreateContainerCmd> createContainerAnswer(String containerId) {403 return createContainerAnswer(containerId, command -> {});404 }405 protected Answer<CreateContainerCmd> createContainerAnswer(String containerId, Consumer<CreateContainerCmd> cmdConsumer) {406 return invocation -> {407 CreateContainerCmd.Exec exec = command -> {408 cmdConsumer.accept(command);409 CreateContainerResponse response = new CreateContainerResponse();410 response.setId(containerId);411 return response;412 };413 return new CreateContainerCmdImpl(exec, null, "image:latest");414 };415 }416 protected Answer<StartContainerCmd> startContainerAnswer() {417 return invocation -> {418 StartContainerCmd.Exec exec = command -> {419 return null;...

Full Screen

Full Screen

createContainerAnswer

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.ReusabilityUnitTests2import org.testcontainers.containers.GenericContainer3import org.testcontainers.containers.output.Slf4jLogConsumer4import org.slf4j.LoggerFactory5def log = LoggerFactory.getLogger("org.testcontainers.containers.ReusabilityUnitTests")6def container = ReusabilityUnitTests.createContainerAnswer()7container.withLogConsumer(new Slf4jLogConsumer(log))8container.start()9container.stop()10container.start()11container.stop()12container.start()13container.stop()14container.start()15container.stop()16def container = ReusabilityUnitTests.createContainerAnswer()17container.withLogConsumer(new Slf4jLogConsumer(log))18container.start()19container.stop()20container.start()21container.stop()22container.start()23container.stop()24container.start()25container.stop()26def container = ReusabilityUnitTests.createContainerAnswer()27container.withLogConsumer(new Slf4jLogConsumer(log))28container.start()29container.stop()30container.start()31container.stop()32container.start()33container.stop()34container.start()35container.stop()36def container = ReusabilityUnitTests.createContainerAnswer()

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