diff --git a/core/build.gradle b/core/build.gradle index ac868c2f928..b4eeae7b0c5 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -30,6 +30,7 @@ shadowJar { } task jarFileTest(type: Test) { + useJUnitPlatform() testClassesDirs = sourceSets.jarFileTest.output.classesDirs classpath = sourceSets.jarFileTest.runtimeClasspath @@ -105,6 +106,9 @@ dependencies { shaded 'org.zeroturnaround:zt-exec:1.12' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.11.0' + + testImplementation 'org.junit.jupiter:junit-jupiter:5.13.4' testImplementation('com.google.cloud.tools:jib-core:0.27.3') { exclude group: 'com.google.guava', module: 'guava' } @@ -124,8 +128,9 @@ dependencies { jarFileTestCompileOnly "org.projectlombok:lombok:${lombok.version}" jarFileTestAnnotationProcessor "org.projectlombok:lombok:${lombok.version}" - jarFileTestImplementation 'junit:junit:4.13.2' - jarFileTestImplementation 'org.assertj:assertj-core:3.27.6' + jarFileTestRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.11.0' + jarFileTestImplementation 'org.junit.jupiter:junit-jupiter:5.13.4' + jarFileTestImplementation 'org.assertj:assertj-core:3.27.4' jarFileTestImplementation 'org.ow2.asm:asm-debug-all:5.2' } @@ -135,3 +140,14 @@ tasks.generatePomFileForMavenJavaPublication.finalizedBy( ] } ) + +compileTestJava { + javaCompiler = javaToolchains.compilerFor { + languageVersion = JavaLanguageVersion.of(17) + } + options.release.set(17) +} + +test { + useJUnitPlatform() +} diff --git a/core/src/jarFileTest/java/org/testcontainers/JarFileShadingTest.java b/core/src/jarFileTest/java/org/testcontainers/JarFileShadingTest.java index 6b9ebc32efc..8b6f380f6eb 100644 --- a/core/src/jarFileTest/java/org/testcontainers/JarFileShadingTest.java +++ b/core/src/jarFileTest/java/org/testcontainers/JarFileShadingTest.java @@ -1,7 +1,7 @@ package org.testcontainers; import org.assertj.core.api.ListAssert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Files; @@ -9,17 +9,17 @@ import static org.assertj.core.api.Assertions.assertThat; -public class JarFileShadingTest extends AbstractJarFileTest { +class JarFileShadingTest extends AbstractJarFileTest { @Test - public void testPackages() throws Exception { + void testPackages() throws Exception { assertThatFileList(root).containsOnly("org", "META-INF"); assertThatFileList(root.resolve("org")).containsOnly("testcontainers"); } @Test - public void testMetaInf() throws Exception { + void testMetaInf() throws Exception { assertThatFileList(root.resolve("META-INF")) .containsOnly( "MANIFEST.MF", @@ -33,7 +33,7 @@ public void testMetaInf() throws Exception { } @Test - public void testMetaInfServices() throws Exception { + void testMetaInfServices() throws Exception { assertThatFileList(root.resolve("META-INF").resolve("services")) .allMatch(it -> it.startsWith("org.testcontainers.")); } diff --git a/core/src/jarFileTest/java/org/testcontainers/PublicBinaryAPITest.java b/core/src/jarFileTest/java/org/testcontainers/PublicBinaryAPITest.java index 77156e77636..6f8a1c46941 100644 --- a/core/src/jarFileTest/java/org/testcontainers/PublicBinaryAPITest.java +++ b/core/src/jarFileTest/java/org/testcontainers/PublicBinaryAPITest.java @@ -2,12 +2,12 @@ import lombok.RequiredArgsConstructor; import org.assertj.core.api.Assertions; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; @@ -30,15 +30,15 @@ /** * This test checks that we don't expose any shaded class in our public API. - * We use {@link Parameterized} runner here to create a test per public class in Testcontainers' JAR file. */ -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("data") @RequiredArgsConstructor public class PublicBinaryAPITest extends AbstractJarFileTest { - private static String SHADED_PACKAGE = "org.testcontainers.shaded."; + private static final String SHADED_PACKAGE = "org.testcontainers.shaded."; - private static String SHADED_PACKAGE_PATH = SHADED_PACKAGE.replaceAll("\\.", "/"); + private static final String SHADED_PACKAGE_PATH = SHADED_PACKAGE.replaceAll("\\.", "/"); static { Assertions.registerFormatterForType(ClassNode.class, it -> it.name); @@ -46,7 +46,6 @@ public class PublicBinaryAPITest extends AbstractJarFileTest { Assertions.registerFormatterForType(MethodNode.class, it -> it.name + it.desc); } - @Parameters(name = "{0}") public static List data() throws Exception { List result = new ArrayList<>(); @@ -85,11 +84,13 @@ public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IO return result; } - private final String fileName; + @Parameter(0) + private String fileName; - private final ClassNode classNode; + @Parameter(1) + private ClassNode classNode; - @Before + @BeforeEach public void setUp() { switch (classNode.name) { // Necessary evil @@ -97,29 +98,29 @@ public void setUp() { case "org/testcontainers/dockerclient/DockerClientProviderStrategy": case "org/testcontainers/dockerclient/WindowsClientProviderStrategy": case "org/testcontainers/utility/DynamicPollInterval": - Assume.assumeTrue(false); + Assumptions.assumeTrue(false); } } @Test - public void testSuperClass() { + void testSuperClass() { assertThat(classNode.superName).doesNotStartWith(SHADED_PACKAGE_PATH); } @Test - public void testInterfaces() { + void testInterfaces() { assertThat(classNode.interfaces).allSatisfy(it -> assertThat(it).doesNotStartWith(SHADED_PACKAGE_PATH)); } @Test - public void testMethodReturnTypes() { + void testMethodReturnTypes() { assertThat(classNode.methods) .filteredOn(it -> (it.access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) != 0) .allSatisfy(it -> assertThat(Type.getReturnType(it.desc).getClassName()).doesNotStartWith(SHADED_PACKAGE)); } @Test - public void testMethodArguments() { + void testMethodArguments() { assertThat(classNode.methods) .filteredOn(it -> (it.access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) != 0) .allSatisfy(method -> { @@ -130,7 +131,7 @@ public void testMethodArguments() { } @Test - public void testFields() { + void testFields() { assertThat(classNode.fields) .filteredOn(it -> (it.access & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) != 0) .allSatisfy(it -> assertThat(Type.getType(it.desc).getClassName()).doesNotStartWith(SHADED_PACKAGE)); diff --git a/core/src/test/java/alt/testcontainers/images/OutOfPackageImagePullPolicyTest.java b/core/src/test/java/alt/testcontainers/images/OutOfPackageImagePullPolicyTest.java index 6b7f7044994..5b13d172386 100644 --- a/core/src/test/java/alt/testcontainers/images/OutOfPackageImagePullPolicyTest.java +++ b/core/src/test/java/alt/testcontainers/images/OutOfPackageImagePullPolicyTest.java @@ -1,6 +1,6 @@ package alt.testcontainers.images; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; @@ -8,10 +8,10 @@ import org.testcontainers.images.ImageData; import org.testcontainers.utility.DockerImageName; -public class OutOfPackageImagePullPolicyTest { +class OutOfPackageImagePullPolicyTest { @Test - public void shouldSupportCustomPoliciesOutOfTestcontainersPackage() { + void shouldSupportCustomPoliciesOutOfTestcontainersPackage() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withImagePullPolicy( diff --git a/core/src/test/java/org/testcontainers/DaemonTest.java b/core/src/test/java/org/testcontainers/DaemonTest.java index dd35112f781..01f4a1c5475 100644 --- a/core/src/test/java/org/testcontainers/DaemonTest.java +++ b/core/src/test/java/org/testcontainers/DaemonTest.java @@ -1,6 +1,6 @@ package org.testcontainers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import java.io.File; @@ -14,7 +14,7 @@ /** * This test forks a new JVM, otherwise it's not possible to reliably diff the threads */ -public class DaemonTest { +class DaemonTest { public static void main(String[] args) { Thread mainThread = Thread.currentThread(); @@ -46,7 +46,7 @@ public static void main(String[] args) { } @Test - public void testThatAllThreadsAreDaemons() throws Exception { + void testThatAllThreadsAreDaemons() throws Exception { ProcessBuilder processBuilder = new ProcessBuilder( new File(System.getProperty("java.home")).toPath().resolve("bin").resolve("java").toString(), "-ea", diff --git a/core/src/test/java/org/testcontainers/DockerClientFactoryTest.java b/core/src/test/java/org/testcontainers/DockerClientFactoryTest.java index 794bbbc37c9..56c68d4fd5d 100644 --- a/core/src/test/java/org/testcontainers/DockerClientFactoryTest.java +++ b/core/src/test/java/org/testcontainers/DockerClientFactoryTest.java @@ -1,10 +1,10 @@ package org.testcontainers; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.testcontainers.dockerclient.LogToStringContainerCallback; import org.testcontainers.utility.DockerImageName; -import org.testcontainers.utility.MockTestcontainersConfigurationRule; +import org.testcontainers.utility.MockTestcontainersConfigurationExtension; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -12,13 +12,11 @@ /** * Test for {@link DockerClientFactory}. */ -public class DockerClientFactoryTest { - - @Rule - public MockTestcontainersConfigurationRule configurationMock = new MockTestcontainersConfigurationRule(); +@ExtendWith(MockTestcontainersConfigurationExtension.class) +class DockerClientFactoryTest { @Test - public void runCommandInsideDockerShouldNotFailIfImageDoesNotExistsLocally() { + void runCommandInsideDockerShouldNotFailIfImageDoesNotExistsLocally() { try (DockerRegistryContainer registryContainer = new DockerRegistryContainer()) { registryContainer.start(); DockerImageName imageName = registryContainer.createImage(); @@ -40,14 +38,14 @@ public void runCommandInsideDockerShouldNotFailIfImageDoesNotExistsLocally() { } @Test - public void dockerHostIpAddress() { + void dockerHostIpAddress() { DockerClientFactory instance = new DockerClientFactory(); instance.strategy = null; assertThat(instance.dockerHostIpAddress()).isNotNull(); } @Test - public void failedChecksFailFast() { + void failedChecksFailFast() { DockerClientFactory instance = DockerClientFactory.instance(); assertThat(instance.client()).isNotNull(); assertThat(instance.cachedClientFailure).isNull(); diff --git a/core/src/test/java/org/testcontainers/containers/ComposeContainerWithServicesTest.java b/core/src/test/java/org/testcontainers/containers/ComposeContainerWithServicesTest.java index 9a73c83981b..6d141ac08f1 100644 --- a/core/src/test/java/org/testcontainers/containers/ComposeContainerWithServicesTest.java +++ b/core/src/test/java/org/testcontainers/containers/ComposeContainerWithServicesTest.java @@ -1,6 +1,6 @@ package org.testcontainers.containers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.rnorth.ducttape.TimeoutException; import org.testcontainers.containers.wait.strategy.Wait; @@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -public class ComposeContainerWithServicesTest { +class ComposeContainerWithServicesTest { public static final File SIMPLE_COMPOSE_FILE = new File( "src/test/resources/compose-scaling-multiple-containers.yml" @@ -28,7 +28,7 @@ public class ComposeContainerWithServicesTest { ); @Test - public void testDesiredSubsetOfServicesAreStarted() { + void testDesiredSubsetOfServicesAreStarted() { try (ComposeContainer compose = new ComposeContainer(SIMPLE_COMPOSE_FILE).withServices("redis")) { compose.start(); @@ -37,7 +37,7 @@ public void testDesiredSubsetOfServicesAreStarted() { } @Test - public void testDesiredSubsetOfScaledServicesAreStarted() { + void testDesiredSubsetOfScaledServicesAreStarted() { try (ComposeContainer compose = new ComposeContainer(SIMPLE_COMPOSE_FILE).withScaledService("redis", 2)) { compose.start(); @@ -46,7 +46,7 @@ public void testDesiredSubsetOfScaledServicesAreStarted() { } @Test - public void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() { + void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() { try ( ComposeContainer compose = new ComposeContainer(SIMPLE_COMPOSE_FILE) .withServices("redis") @@ -59,7 +59,7 @@ public void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() { } @Test - public void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() { + void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() { try ( ComposeContainer compose = new ComposeContainer(SIMPLE_COMPOSE_FILE) .withServices("other") @@ -72,7 +72,7 @@ public void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() { } @Test - public void testAllServicesAreStartedIfNotSpecified() { + void testAllServicesAreStartedIfNotSpecified() { try (ComposeContainer compose = new ComposeContainer(SIMPLE_COMPOSE_FILE)) { compose.start(); @@ -81,7 +81,7 @@ public void testAllServicesAreStartedIfNotSpecified() { } @Test - public void testScaleInComposeFileIsRespected() { + void testScaleInComposeFileIsRespected() { try (ComposeContainer compose = new ComposeContainer(COMPOSE_FILE_WITH_INLINE_SCALE)) { compose.start(); @@ -91,7 +91,7 @@ public void testScaleInComposeFileIsRespected() { } @Test - public void testStartupTimeoutSetsTheHighestTimeout() { + void testStartupTimeoutSetsTheHighestTimeout() { assertThat( catchThrowable(() -> { try ( @@ -113,7 +113,7 @@ public void testStartupTimeoutSetsTheHighestTimeout() { } @Test - public void testWaitingForHealthcheck() { + void testWaitingForHealthcheck() { try ( ComposeContainer compose = new ComposeContainer(COMPOSE_FILE_WITH_HEALTHCHECK) .waitingFor("redis", Wait.forHealthcheck().withStartupTimeout(Duration.ofMinutes(2))) @@ -125,7 +125,7 @@ public void testWaitingForHealthcheck() { } @Test - public void testWaitingForHealthcheckWithRestartDoesNotCrash() { + void testWaitingForHealthcheckWithRestartDoesNotCrash() { try ( ComposeContainer compose = new ComposeContainer(COMPOSE_FILE_WITH_HEALTHCHECK) .waitingFor("redis", Wait.forHealthcheck().withStartupTimeout(Duration.ofMinutes(1))) diff --git a/core/src/test/java/org/testcontainers/containers/ComposeOverridesTest.java b/core/src/test/java/org/testcontainers/containers/ComposeOverridesTest.java index 553ac21a8a0..1ed03ae9315 100644 --- a/core/src/test/java/org/testcontainers/containers/ComposeOverridesTest.java +++ b/core/src/test/java/org/testcontainers/containers/ComposeOverridesTest.java @@ -3,11 +3,8 @@ import com.google.common.util.concurrent.Uninterruptibles; import org.apache.commons.lang3.SystemUtils; import org.assertj.core.api.Assumptions; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.utility.CommandLine; @@ -18,8 +15,7 @@ import java.util.Arrays; import java.util.concurrent.TimeUnit; -@RunWith(Parameterized.class) -public class ComposeOverridesTest { +class ComposeOverridesTest { private static final String DOCKER_EXECUTABLE = SystemUtils.IS_OS_WINDOWS ? "docker.exe" : "docker"; @@ -37,19 +33,6 @@ public class ComposeOverridesTest { private static final String SERVICE_NAME = "alpine-1"; - private final boolean localMode; - - private final String expectedEnvVar; - - private final File[] composeFiles; - - public ComposeOverridesTest(boolean localMode, String expectedEnvVar, File... composeFiles) { - this.localMode = localMode; - this.expectedEnvVar = expectedEnvVar; - this.composeFiles = composeFiles; - } - - @Parameters(name = "{index}: local[{0}], composeFiles[{2}], expectedEnvVar[{1}]") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -61,18 +44,15 @@ public static Iterable data() { ); } - @Before - public void setUp() { + @ParameterizedTest(name = "{index}: local[{0}], composeFiles[{2}], expectedEnvVar[{1}]") + @MethodSource("data") + void test(boolean localMode, String expectedEnvVar, File... composeFiles) { if (localMode) { Assumptions .assumeThat(CommandLine.executableExists(DOCKER_EXECUTABLE)) .as("docker executable exists") .isTrue(); } - } - - @Test - public void test() { try ( ComposeContainer compose = new ComposeContainer(composeFiles) .withLocalCompose(localMode) diff --git a/core/src/test/java/org/testcontainers/containers/ComposeProfilesOptionTest.java b/core/src/test/java/org/testcontainers/containers/ComposeProfilesOptionTest.java index 8fc662a118e..8a176fdcddb 100644 --- a/core/src/test/java/org/testcontainers/containers/ComposeProfilesOptionTest.java +++ b/core/src/test/java/org/testcontainers/containers/ComposeProfilesOptionTest.java @@ -1,41 +1,31 @@ package org.testcontainers.containers; import org.assertj.core.api.Assumptions; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.utility.CommandLine; import java.io.File; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class ComposeProfilesOptionTest { +class ComposeProfilesOptionTest { - @Parameterized.Parameters(name = "{0}") public static Boolean[] local() { return new Boolean[] { Boolean.TRUE, Boolean.FALSE }; } - @Parameterized.Parameter - public boolean localMode; - public static final File COMPOSE_FILE = new File("src/test/resources/compose-profile-option/compose-test.yml"); - @Before - public void setUp() { - if (this.localMode) { + @ParameterizedTest + @MethodSource("local") + void testProfileOption(boolean localMode) { + if (localMode) { Assumptions .assumeThat(CommandLine.executableExists(ComposeContainer.COMPOSE_EXECUTABLE)) .as("docker executable exists") .isTrue(); } - } - - @Test - public void testProfileOption() { try ( // composeContainerWithLocalCompose { ComposeContainer compose = new ComposeContainer(COMPOSE_FILE) diff --git a/core/src/test/java/org/testcontainers/containers/ContainerStateTest.java b/core/src/test/java/org/testcontainers/containers/ContainerStateTest.java index d3cedc11464..7b37bc1926f 100644 --- a/core/src/test/java/org/testcontainers/containers/ContainerStateTest.java +++ b/core/src/test/java/org/testcontainers/containers/ContainerStateTest.java @@ -1,8 +1,7 @@ package org.testcontainers.containers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Collections; import java.util.List; @@ -12,10 +11,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(Parameterized.class) -public class ContainerStateTest { +class ContainerStateTest { - @Parameterized.Parameters(name = "{0} ({1} -> {2})") public static Object[][] params() { return new Object[][] { new Object[] { "regular mapping", "80:8080/tcp", Collections.singletonList(80) }, @@ -27,17 +24,9 @@ public static Object[][] params() { }; } - @Parameterized.Parameter(0) - public String name; - - @Parameterized.Parameter(1) - public String testSet; - - @Parameterized.Parameter(2) - public List expectedResult; - - @Test - public void test() { + @ParameterizedTest(name = "{0} ({1} -> {2})") + @MethodSource("params") + void test(String name, String testSet, List expectedResult) { ContainerState containerState = mock(ContainerState.class); doCallRealMethod().when(containerState).getBoundPortNumbers(); diff --git a/core/src/test/java/org/testcontainers/containers/DockerComposeContainerWithServicesTest.java b/core/src/test/java/org/testcontainers/containers/DockerComposeContainerWithServicesTest.java index f92c4727921..cc6c124fde0 100644 --- a/core/src/test/java/org/testcontainers/containers/DockerComposeContainerWithServicesTest.java +++ b/core/src/test/java/org/testcontainers/containers/DockerComposeContainerWithServicesTest.java @@ -1,6 +1,6 @@ package org.testcontainers.containers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.rnorth.ducttape.TimeoutException; import org.testcontainers.containers.wait.strategy.Wait; @@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -public class DockerComposeContainerWithServicesTest { +class DockerComposeContainerWithServicesTest { public static final File SIMPLE_COMPOSE_FILE = new File( "src/test/resources/compose-scaling-multiple-containers.yml" @@ -28,7 +28,7 @@ public class DockerComposeContainerWithServicesTest { ); @Test - public void testDesiredSubsetOfServicesAreStarted() { + void testDesiredSubsetOfServicesAreStarted() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE).withServices("redis") ) { @@ -39,7 +39,7 @@ public void testDesiredSubsetOfServicesAreStarted() { } @Test - public void testDesiredSubsetOfScaledServicesAreStarted() { + void testDesiredSubsetOfScaledServicesAreStarted() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE) .withScaledService("redis", 2) @@ -51,7 +51,7 @@ public void testDesiredSubsetOfScaledServicesAreStarted() { } @Test - public void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() { + void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE) .withServices("redis") @@ -64,7 +64,7 @@ public void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() { } @Test - public void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() { + void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE) .withServices("other") @@ -77,7 +77,7 @@ public void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() { } @Test - public void testAllServicesAreStartedIfNotSpecified() { + void testAllServicesAreStartedIfNotSpecified() { try (DockerComposeContainer compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE)) { compose.start(); @@ -86,7 +86,7 @@ public void testAllServicesAreStartedIfNotSpecified() { } @Test - public void testScaleInComposeFileIsRespected() { + void testScaleInComposeFileIsRespected() { try (DockerComposeContainer compose = new DockerComposeContainer<>(COMPOSE_FILE_WITH_INLINE_SCALE)) { compose.start(); @@ -96,7 +96,7 @@ public void testScaleInComposeFileIsRespected() { } @Test - public void testStartupTimeoutSetsTheHighestTimeout() { + void testStartupTimeoutSetsTheHighestTimeout() { assertThat( catchThrowable(() -> { try ( @@ -118,7 +118,7 @@ public void testStartupTimeoutSetsTheHighestTimeout() { } @Test - public void testWaitingForHealthcheck() { + void testWaitingForHealthcheck() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(COMPOSE_FILE_WITH_HEALTHCHECK) .waitingFor("redis", Wait.forHealthcheck().withStartupTimeout(Duration.ofMinutes(2))) @@ -130,7 +130,7 @@ public void testWaitingForHealthcheck() { } @Test - public void testWaitingForHealthcheckWithRestartDoesNotCrash() { + void testWaitingForHealthcheckWithRestartDoesNotCrash() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(COMPOSE_FILE_WITH_HEALTHCHECK) .waitingFor("redis", Wait.forHealthcheck().withStartupTimeout(Duration.ofMinutes(1))) diff --git a/core/src/test/java/org/testcontainers/containers/DockerComposeFilesTest.java b/core/src/test/java/org/testcontainers/containers/DockerComposeFilesTest.java index 9ae02a676c4..4704817c0e0 100644 --- a/core/src/test/java/org/testcontainers/containers/DockerComposeFilesTest.java +++ b/core/src/test/java/org/testcontainers/containers/DockerComposeFilesTest.java @@ -1,16 +1,16 @@ package org.testcontainers.containers; import com.google.common.collect.Lists; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import static org.assertj.core.api.Assertions.assertThat; -public class DockerComposeFilesTest { +class DockerComposeFilesTest { @Test - public void shouldGetDependencyImages() { + void shouldGetDependencyImages() { DockerComposeFiles dockerComposeFiles = new DockerComposeFiles( Lists.newArrayList(new File("src/test/resources/docker-compose-imagename-parsing-v2.yml")) ); @@ -19,7 +19,7 @@ public void shouldGetDependencyImages() { } @Test - public void shouldGetDependencyImagesWhenOverriding() { + void shouldGetDependencyImagesWhenOverriding() { DockerComposeFiles dockerComposeFiles = new DockerComposeFiles( Lists.newArrayList( new File("src/test/resources/docker-compose-imagename-overriding-a.yml"), diff --git a/core/src/test/java/org/testcontainers/containers/DockerComposeOverridesTest.java b/core/src/test/java/org/testcontainers/containers/DockerComposeOverridesTest.java index 036134e32d8..eb66fbabc38 100644 --- a/core/src/test/java/org/testcontainers/containers/DockerComposeOverridesTest.java +++ b/core/src/test/java/org/testcontainers/containers/DockerComposeOverridesTest.java @@ -2,11 +2,8 @@ import com.google.common.util.concurrent.Uninterruptibles; import org.assertj.core.api.Assumptions; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.utility.CommandLine; @@ -17,8 +14,7 @@ import java.util.Arrays; import java.util.concurrent.TimeUnit; -@RunWith(Parameterized.class) -public class DockerComposeOverridesTest { +class DockerComposeOverridesTest { private static final File BASE_COMPOSE_FILE = new File("src/test/resources/docker-compose-base.yml"); @@ -34,19 +30,6 @@ public class DockerComposeOverridesTest { private static final String SERVICE_NAME = "alpine_1"; - private final boolean localMode; - - private final String expectedEnvVar; - - private final File[] composeFiles; - - public DockerComposeOverridesTest(boolean localMode, String expectedEnvVar, File... composeFiles) { - this.localMode = localMode; - this.expectedEnvVar = expectedEnvVar; - this.composeFiles = composeFiles; - } - - @Parameters(name = "{index}: local[{0}], composeFiles[{2}], expectedEnvVar[{1}]") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -58,8 +41,9 @@ public static Iterable data() { ); } - @Before - public void setUp() { + @ParameterizedTest(name = "{index}: local[{0}], composeFiles[{2}], expectedEnvVar[{1}]") + @MethodSource("data") + void test(boolean localMode, String expectedEnvVar, File... composeFiles) { if (localMode) { Assumptions .assumeThat(CommandLine.executableExists(DockerComposeContainer.COMPOSE_EXECUTABLE)) @@ -69,10 +53,6 @@ public void setUp() { .assumeThat(CommandLine.runShellCommand("docker-compose", "--version")) .doesNotStartWith("Docker Compose version v2"); } - } - - @Test - public void test() { try ( DockerComposeContainer compose = new DockerComposeContainer(composeFiles) .withLocalCompose(localMode) diff --git a/core/src/test/java/org/testcontainers/containers/DockerComposeProfilesOptionTest.java b/core/src/test/java/org/testcontainers/containers/DockerComposeProfilesOptionTest.java index 72f80cc877e..20a52566201 100644 --- a/core/src/test/java/org/testcontainers/containers/DockerComposeProfilesOptionTest.java +++ b/core/src/test/java/org/testcontainers/containers/DockerComposeProfilesOptionTest.java @@ -1,31 +1,27 @@ package org.testcontainers.containers; import org.assertj.core.api.Assumptions; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.utility.CommandLine; import java.io.File; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class DockerComposeProfilesOptionTest { +class DockerComposeProfilesOptionTest { - @Parameterized.Parameters(name = "{0}") public static Boolean[] local() { return new Boolean[] { Boolean.TRUE, Boolean.FALSE }; } - @Parameterized.Parameter public boolean localMode; public static final File COMPOSE_FILE = new File("src/test/resources/compose-profile-option/compose-test.yml"); - @Before - public void setUp() { + @ParameterizedTest(name = "{0}") + @MethodSource("local") + void testProfileOption() { if (this.localMode) { Assumptions .assumeThat(CommandLine.executableExists(DockerComposeContainer.COMPOSE_EXECUTABLE)) @@ -35,10 +31,6 @@ public void setUp() { .assumeThat(CommandLine.runShellCommand("docker-compose", "--version")) .doesNotStartWith("Docker Compose version v2"); } - } - - @Test - public void testProfileOption() { try ( DockerComposeContainer compose = new DockerComposeContainer<>(COMPOSE_FILE) .withOptions("--profile=cache") diff --git a/core/src/test/java/org/testcontainers/containers/DockerMcpGatewayContainerTest.java b/core/src/test/java/org/testcontainers/containers/DockerMcpGatewayContainerTest.java index 28e4cf6fb6a..cecd9f4da6f 100644 --- a/core/src/test/java/org/testcontainers/containers/DockerMcpGatewayContainerTest.java +++ b/core/src/test/java/org/testcontainers/containers/DockerMcpGatewayContainerTest.java @@ -1,15 +1,15 @@ package org.testcontainers.containers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -public class DockerMcpGatewayContainerTest { +class DockerMcpGatewayContainerTest { @Test - public void serviceSuccessfullyStarts() { + void serviceSuccessfullyStarts() { try (DockerMcpGatewayContainer gateway = new DockerMcpGatewayContainer("docker/mcp-gateway:latest")) { gateway.start(); @@ -18,7 +18,7 @@ public void serviceSuccessfullyStarts() { } @Test - public void gatewayStartsWithServers() { + void gatewayStartsWithServers() { try ( // container { DockerMcpGatewayContainer gateway = new DockerMcpGatewayContainer("docker/mcp-gateway:latest") diff --git a/core/src/test/java/org/testcontainers/containers/DockerModelRunnerContainerTest.java b/core/src/test/java/org/testcontainers/containers/DockerModelRunnerContainerTest.java index c04c0159e51..b215a373cf5 100644 --- a/core/src/test/java/org/testcontainers/containers/DockerModelRunnerContainerTest.java +++ b/core/src/test/java/org/testcontainers/containers/DockerModelRunnerContainerTest.java @@ -2,15 +2,15 @@ import io.restassured.RestAssured; import io.restassured.response.Response; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; -public class DockerModelRunnerContainerTest { +class DockerModelRunnerContainerTest { @Test - public void checkStatus() { + void checkStatus() { assumeThat(System.getenv("CI")).isNull(); try ( @@ -26,7 +26,7 @@ public void checkStatus() { } @Test - public void pullsModelAndExposesInference() { + void pullsModelAndExposesInference() { assumeThat(System.getenv("CI")).isNull(); String modelName = "ai/smollm2:360M-Q4_K_M"; diff --git a/core/src/test/java/org/testcontainers/containers/ExposedHostTest.java b/core/src/test/java/org/testcontainers/containers/ExposedHostTest.java index 4ce316fcf80..39c986d1f8a 100644 --- a/core/src/test/java/org/testcontainers/containers/ExposedHostTest.java +++ b/core/src/test/java/org/testcontainers/containers/ExposedHostTest.java @@ -3,10 +3,10 @@ import com.google.common.collect.ImmutableMap; import com.sun.net.httpserver.HttpServer; import lombok.SneakyThrows; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.testcontainers.DockerClientFactory; @@ -23,11 +23,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; -public class ExposedHostTest { +class ExposedHostTest { private static HttpServer server; - @BeforeClass + @BeforeAll public static void setUpClass() throws Exception { server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext( @@ -44,18 +44,18 @@ public static void setUpClass() throws Exception { server.start(); } - @AfterClass + @AfterAll public static void tearDownClass() { server.stop(0); } - @After + @AfterEach public void tearDown() { PortForwardingContainer.INSTANCE.reset(); } @Test - public void testExposedHostAfterContainerIsStarted() { + void testExposedHostAfterContainerIsStarted() { try (GenericContainer container = new GenericContainer<>(tinyContainerDef()).withAccessToHost(true)) { container.start(); Testcontainers.exposeHostPorts(server.getAddress().getPort()); @@ -64,13 +64,13 @@ public void testExposedHostAfterContainerIsStarted() { } @Test - public void testExposedHost() { + void testExposedHost() { Testcontainers.exposeHostPorts(server.getAddress().getPort()); assertResponse(new GenericContainer<>(tinyContainerDef()), server.getAddress().getPort()); } @Test - public void testExposedHostWithNetwork() { + void testExposedHostWithNetwork() { Testcontainers.exposeHostPorts(server.getAddress().getPort()); try (Network network = Network.newNetwork()) { assertResponse( @@ -81,7 +81,7 @@ public void testExposedHostWithNetwork() { } @Test - public void testExposedHostPortOnFixedInternalPorts() { + void testExposedHostPortOnFixedInternalPorts() { Testcontainers.exposeHostPorts(ImmutableMap.of(server.getAddress().getPort(), 80)); Testcontainers.exposeHostPorts(ImmutableMap.of(server.getAddress().getPort(), 81)); @@ -90,7 +90,7 @@ public void testExposedHostPortOnFixedInternalPorts() { } @Test - public void testExposedHostWithReusableContainerAndFixedNetworkName() throws IOException, InterruptedException { + void testExposedHostWithReusableContainerAndFixedNetworkName() throws IOException, InterruptedException { assumeThat(TestcontainersConfiguration.getInstance().environmentSupportsReuse()).isTrue(); Network network = createReusableNetwork(UUID.randomUUID()); Testcontainers.exposeHostPorts(server.getAddress().getPort()); @@ -117,7 +117,7 @@ public void testExposedHostWithReusableContainerAndFixedNetworkName() throws IOE } @Test - public void testExposedHostOnFixedInternalPortsWithReusableContainerAndFixedNetworkName() + void testExposedHostOnFixedInternalPortsWithReusableContainerAndFixedNetworkName() throws IOException, InterruptedException { assumeThat(TestcontainersConfiguration.getInstance().environmentSupportsReuse()).isTrue(); Network network = createReusableNetwork(UUID.randomUUID()); diff --git a/core/src/test/java/org/testcontainers/containers/FailureDetectingExternalResourceTest.java b/core/src/test/java/org/testcontainers/containers/FailureDetectingExternalResourceTest.java index c743fcf6a43..b2abf02bce5 100644 --- a/core/src/test/java/org/testcontainers/containers/FailureDetectingExternalResourceTest.java +++ b/core/src/test/java/org/testcontainers/containers/FailureDetectingExternalResourceTest.java @@ -1,6 +1,6 @@ package org.testcontainers.containers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.runner.Description; import org.junit.runners.model.Statement; @@ -10,10 +10,10 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -public class FailureDetectingExternalResourceTest { +class FailureDetectingExternalResourceTest { @Test - public void finishedIsCalledForCleanupIfStartingThrows() throws Throwable { + void finishedIsCalledForCleanupIfStartingThrows() { FailureDetectingExternalResource res = spy(FailureDetectingExternalResource.class); Statement stmt = res.apply(mock(Statement.class), Description.EMPTY); doThrow(new RuntimeException()).when(res).starting(any()); diff --git a/core/src/test/java/org/testcontainers/containers/GenericContainerTest.java b/core/src/test/java/org/testcontainers/containers/GenericContainerTest.java index c1c4ff3818e..37aac1b0af9 100644 --- a/core/src/test/java/org/testcontainers/containers/GenericContainerTest.java +++ b/core/src/test/java/org/testcontainers/containers/GenericContainerTest.java @@ -17,7 +17,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.assertj.core.api.Assumptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.DockerClientFactory; import org.testcontainers.TestImages; @@ -46,10 +46,10 @@ import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assumptions.assumeThat; -public class GenericContainerTest { +class GenericContainerTest { @Test - public void shouldReportOOMAfterWait() { + void shouldReportOOMAfterWait() { Info info = DockerClientFactory.instance().client().infoCmd().exec(); // Poor man's rootless Docker detection :D Assumptions.assumeThat(info.getSecurityOptions()).doesNotContain("name=rootless"); @@ -75,7 +75,7 @@ public void shouldReportOOMAfterWait() { } @Test - public void shouldReportErrorAfterWait() { + void shouldReportErrorAfterWait() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withStartupCheckStrategy(new NoopStartupCheckStrategy()) @@ -90,7 +90,7 @@ public void shouldReportErrorAfterWait() { } @Test - public void shouldCopyTransferableAsFile() { + void shouldCopyTransferableAsFile() { try ( // transferableFile { GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) @@ -107,7 +107,7 @@ public void shouldCopyTransferableAsFile() { } @Test - public void shouldCopyTransferableAsFileWithFileMode() { + void shouldCopyTransferableAsFileWithFileMode() { try ( // transferableWithFileMode { GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) @@ -124,7 +124,7 @@ public void shouldCopyTransferableAsFileWithFileMode() { } @Test - public void shouldCopyTransferableAfterMountableFile() { + void shouldCopyTransferableAfterMountableFile() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withStartupCheckStrategy(new NoopStartupCheckStrategy()) @@ -140,7 +140,7 @@ public void shouldCopyTransferableAfterMountableFile() { } @Test - public void shouldOnlyPublishExposedPorts() { + void shouldOnlyPublishExposedPorts() { ImageFromDockerfile image = new ImageFromDockerfile("publish-multiple") .withDockerfileFromBuilder(builder -> { builder @@ -176,7 +176,7 @@ public void shouldOnlyPublishExposedPorts() { } @Test - public void shouldWaitUntilExposedPortIsMapped() { + void shouldWaitUntilExposedPortIsMapped() { ImageFromDockerfile image = new ImageFromDockerfile("publish-multiple") .withDockerfileFromBuilder(builder -> { builder @@ -198,7 +198,7 @@ public void shouldWaitUntilExposedPortIsMapped() { } @Test - public void testArchitectureCheck() { + void testArchitectureCheck() { assumeThat(DockerClientFactory.instance().client().versionCmd().exec().getArch()).isNotEqualTo("amd64"); // Choose an image that is *different* from the server architecture--this ensures we always get a warning. final String image; @@ -233,7 +233,7 @@ public void testArchitectureCheck() { } @Test - public void shouldReturnTheProvidedImage() { + void shouldReturnTheProvidedImage() { GenericContainer container = new GenericContainer(TestImages.REDIS_IMAGE); assertThat(container.getImage().get()).isEqualTo("redis:6-alpine"); container.setImage(new RemoteDockerImage(TestImages.ALPINE_IMAGE)); @@ -241,7 +241,7 @@ public void shouldReturnTheProvidedImage() { } @Test - public void shouldContainDefaultNetworkAlias() { + void shouldContainDefaultNetworkAlias() { try (GenericContainer container = new GenericContainer<>("testcontainers/helloworld:1.1.0")) { container.start(); assertThat(container.getNetworkAliases()).hasSize(1); @@ -249,7 +249,7 @@ public void shouldContainDefaultNetworkAlias() { } @Test - public void shouldContainDefaultNetworkAliasWhenUsingGenericContainer() { + void shouldContainDefaultNetworkAliasWhenUsingGenericContainer() { try (HelloWorldContainer container = new HelloWorldContainer("testcontainers/helloworld:1.1.0")) { container.start(); assertThat(container.getNetworkAliases()).hasSize(1); @@ -257,7 +257,7 @@ public void shouldContainDefaultNetworkAliasWhenUsingGenericContainer() { } @Test - public void shouldContainDefaultNetworkAliasWhenUsingContainerDef() { + void shouldContainDefaultNetworkAliasWhenUsingContainerDef() { try (TcHelloWorldContainer container = new TcHelloWorldContainer("testcontainers/helloworld:1.1.0")) { container.start(); assertThat(container.getNetworkAliases()).hasSize(1); @@ -265,7 +265,7 @@ public void shouldContainDefaultNetworkAliasWhenUsingContainerDef() { } @Test - public void shouldRespectWaitStrategy() { + void shouldRespectWaitStrategy() { try ( HelloWorldLogStrategyContainer container = new HelloWorldLogStrategyContainer( "testcontainers/helloworld:1.1.0" @@ -280,7 +280,7 @@ public void shouldRespectWaitStrategy() { } @Test - public void testStartupAttemptsDoesNotLeaveContainersRunningWhenWrongWaitStrategyIsUsed() { + void testStartupAttemptsDoesNotLeaveContainersRunningWhenWrongWaitStrategyIsUsed() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withLabel("waitstrategy", "wrong") diff --git a/core/src/test/java/org/testcontainers/containers/JibTest.java b/core/src/test/java/org/testcontainers/containers/JibTest.java index 1441ff00120..df045052bc3 100644 --- a/core/src/test/java/org/testcontainers/containers/JibTest.java +++ b/core/src/test/java/org/testcontainers/containers/JibTest.java @@ -1,7 +1,7 @@ package org.testcontainers.containers; import com.github.dockerjava.api.command.InspectImageResponse; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.output.OutputFrame.OutputType; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; @@ -12,10 +12,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class JibTest { +class JibTest { @Test - public void buildImage() { + void buildImage() { try ( // jibContainerUsage { GenericContainer busybox = new GenericContainer<>( @@ -36,7 +36,7 @@ public void buildImage() { } @Test - public void standardLabelsAreAddedWhenUsingJibSetLabels() { + void standardLabelsAreAddedWhenUsingJibSetLabels() { try ( GenericContainer busybox = new GenericContainer<>( new JibImage( @@ -56,7 +56,7 @@ public void standardLabelsAreAddedWhenUsingJibSetLabels() { } @Test - public void standardLabelsAreAddedWhenUsingJibAddLabel() { + void standardLabelsAreAddedWhenUsingJibAddLabel() { try ( GenericContainer busybox = new GenericContainer<>( new JibImage( diff --git a/core/src/test/java/org/testcontainers/containers/MultiStageBuildTest.java b/core/src/test/java/org/testcontainers/containers/MultiStageBuildTest.java index f5bed1020c0..b1ec1c707d5 100644 --- a/core/src/test/java/org/testcontainers/containers/MultiStageBuildTest.java +++ b/core/src/test/java/org/testcontainers/containers/MultiStageBuildTest.java @@ -1,6 +1,6 @@ package org.testcontainers.containers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.images.builder.ImageFromDockerfile; import java.io.IOException; @@ -8,10 +8,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class MultiStageBuildTest { +class MultiStageBuildTest { @Test - public void testDockerMultistageBuild() throws IOException, InterruptedException { + void testDockerMultistageBuild() throws IOException, InterruptedException { try ( GenericContainer container = new GenericContainer<>( new ImageFromDockerfile() @@ -27,7 +27,7 @@ public void testDockerMultistageBuild() throws IOException, InterruptedException } @Test - public void shouldBuildMultistageBuildWithBuildImageCmdModifier() throws IOException, InterruptedException { + void shouldBuildMultistageBuildWithBuildImageCmdModifier() throws IOException, InterruptedException { try ( GenericContainer container = new GenericContainer<>( new ImageFromDockerfile() diff --git a/core/src/test/java/org/testcontainers/containers/NetworkTest.java b/core/src/test/java/org/testcontainers/containers/NetworkTest.java index 099bef20ed7..675658b353a 100644 --- a/core/src/test/java/org/testcontainers/containers/NetworkTest.java +++ b/core/src/test/java/org/testcontainers/containers/NetworkTest.java @@ -1,44 +1,41 @@ package org.testcontainers.containers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.TestImages; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Enclosed.class) -public class NetworkTest { +class NetworkTest { - public static class WithRules { + @Nested + class WithRules { - @Rule public Network network = Network.newNetwork(); - @Rule public GenericContainer foo = new GenericContainer<>(TestImages.TINY_IMAGE) .withNetwork(network) .withNetworkAliases("foo") .withCommand("/bin/sh", "-c", "while true ; do printf 'HTTP/1.1 200 OK\\n\\nyay' | nc -l -p 8080; done"); - @Rule public GenericContainer bar = new GenericContainer<>(TestImages.TINY_IMAGE) .withNetwork(network) .withCommand("top"); - @Test - public void testNetworkSupport() throws Exception { + void testNetworkSupport() throws Exception { + foo.start(); + bar.start(); String response = bar.execInContainer("wget", "-O", "-", "http://foo:8080").getStdout(); assertThat(response).as("received response").isEqualTo("yay"); } } - public static class WithoutRules { + @Nested + class WithoutRules { @Test - public void testNetworkSupport() throws Exception { + void testNetworkSupport() throws Exception { // useCustomNetwork { try ( Network network = Network.newNetwork(); @@ -64,7 +61,7 @@ public void testNetworkSupport() throws Exception { } @Test - public void testBuilder() { + void testBuilder() { try (Network network = Network.builder().driver("macvlan").build()) { String id = network.getId(); assertThat( @@ -76,7 +73,7 @@ public void testBuilder() { } @Test - public void testModifiers() { + void testModifiers() { try ( Network network = Network.builder().createNetworkCmdModifier(cmd -> cmd.withDriver("macvlan")).build() ) { @@ -90,7 +87,7 @@ public void testModifiers() { } @Test - public void testReusability() { + void testReusability() { try (Network network = Network.newNetwork()) { String firstId = network.getId(); assertThat(DockerClientFactory.instance().client().inspectNetworkCmd().withNetworkId(firstId).exec()) diff --git a/core/src/test/java/org/testcontainers/containers/ParsedDockerComposeFileValidationTest.java b/core/src/test/java/org/testcontainers/containers/ParsedDockerComposeFileValidationTest.java index 9067d77d825..36126df6a38 100644 --- a/core/src/test/java/org/testcontainers/containers/ParsedDockerComposeFileValidationTest.java +++ b/core/src/test/java/org/testcontainers/containers/ParsedDockerComposeFileValidationTest.java @@ -3,12 +3,12 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import lombok.SneakyThrows; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.PrintWriter; +import java.nio.file.Path; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; @@ -16,13 +16,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; -public class ParsedDockerComposeFileValidationTest { +class ParsedDockerComposeFileValidationTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public Path temporaryFolder; @Test - public void shouldValidate() { + void shouldValidate() { File file = new File("src/test/resources/docker-compose-container-name-v1.yml"); assertThatThrownBy(() -> { new ParsedDockerComposeFile(file); @@ -32,7 +32,7 @@ public void shouldValidate() { } @Test - public void shouldRejectContainerNameV1() { + void shouldRejectContainerNameV1() { assertThatThrownBy(() -> { new ParsedDockerComposeFile(ImmutableMap.of("redis", ImmutableMap.of("container_name", "redis"))); }) @@ -40,7 +40,7 @@ public void shouldRejectContainerNameV1() { } @Test - public void shouldRejectContainerNameV2() { + void shouldRejectContainerNameV2() { assertThatThrownBy(() -> { new ParsedDockerComposeFile( ImmutableMap.of( @@ -55,7 +55,7 @@ public void shouldRejectContainerNameV2() { } @Test - public void shouldIgnoreUnknownStructure() { + void shouldIgnoreUnknownStructure() { // Everything is a list new ParsedDockerComposeFile(Collections.emptyMap()); @@ -71,7 +71,7 @@ public void shouldIgnoreUnknownStructure() { @Test @SneakyThrows - public void shouldRejectDeserializationOfArbitraryClasses() { + void shouldRejectDeserializationOfArbitraryClasses() { // Reject deserialization gadget chain attacks: https://nvd.nist.gov/vuln/detail/CVE-2022-1471 // https://raw.githubusercontent.com/mbechler/marshalsec/master/marshalsec.pdf @@ -86,7 +86,7 @@ public void shouldRejectDeserializationOfArbitraryClasses() { } @Test - public void shouldObtainImageNamesV1() { + void shouldObtainImageNamesV1() { File file = new File("src/test/resources/docker-compose-imagename-parsing-v1.yml"); ParsedDockerComposeFile parsedFile = new ParsedDockerComposeFile(file); assertThat(parsedFile.getServiceNameToImageNames()) @@ -99,7 +99,7 @@ public void shouldObtainImageNamesV1() { } @Test - public void shouldObtainImageNamesV2() { + void shouldObtainImageNamesV2() { File file = new File("src/test/resources/docker-compose-imagename-parsing-v2.yml"); ParsedDockerComposeFile parsedFile = new ParsedDockerComposeFile(file); assertThat(parsedFile.getServiceNameToImageNames()) @@ -112,7 +112,7 @@ public void shouldObtainImageNamesV2() { } @Test - public void shouldObtainImageNamesV2WithNoVersionTag() { + void shouldObtainImageNamesV2WithNoVersionTag() { File file = new File("src/test/resources/docker-compose-imagename-parsing-v2-no-version.yml"); ParsedDockerComposeFile parsedFile = new ParsedDockerComposeFile(file); assertThat(parsedFile.getServiceNameToImageNames()) @@ -125,7 +125,7 @@ public void shouldObtainImageNamesV2WithNoVersionTag() { } @Test - public void shouldObtainImageFromDockerfileBuild() { + void shouldObtainImageFromDockerfileBuild() { File file = new File("src/test/resources/docker-compose-imagename-parsing-dockerfile.yml"); ParsedDockerComposeFile parsedFile = new ParsedDockerComposeFile(file); assertThat(parsedFile.getServiceNameToImageNames()) @@ -138,7 +138,7 @@ public void shouldObtainImageFromDockerfileBuild() { } @Test - public void shouldObtainImageFromDockerfileBuildWithContext() { + void shouldObtainImageFromDockerfileBuildWithContext() { File file = new File("src/test/resources/docker-compose-imagename-parsing-dockerfile-with-context.yml"); ParsedDockerComposeFile parsedFile = new ParsedDockerComposeFile(file); assertThat(parsedFile.getServiceNameToImageNames()) @@ -151,8 +151,8 @@ public void shouldObtainImageFromDockerfileBuildWithContext() { } @Test - public void shouldSupportALotOfAliases() throws Exception { - File file = temporaryFolder.newFile(); + void shouldSupportALotOfAliases() throws Exception { + File file = temporaryFolder.resolve("tmp-docker-compose.yml").toFile(); try (PrintWriter writer = new PrintWriter(file)) { writer.println("x-entry: &entry"); writer.println(" key: value"); diff --git a/core/src/test/java/org/testcontainers/containers/ReusabilityUnitTests.java b/core/src/test/java/org/testcontainers/containers/ReusabilityUnitTests.java index 04f97fef514..2c70a3f894f 100644 --- a/core/src/test/java/org/testcontainers/containers/ReusabilityUnitTests.java +++ b/core/src/test/java/org/testcontainers/containers/ReusabilityUnitTests.java @@ -14,14 +14,12 @@ import com.github.dockerjava.core.command.InspectContainerCmdImpl; import com.github.dockerjava.core.command.ListContainersCmdImpl; import com.github.dockerjava.core.command.StartContainerCmdImpl; -import lombok.RequiredArgsConstructor; -import lombok.experimental.FieldDefaults; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; import org.mockito.Mockito; import org.mockito.stubbing.Answer; @@ -29,7 +27,7 @@ import org.testcontainers.TestImages; import org.testcontainers.containers.startupcheck.StartupCheckStrategy; import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy; -import org.testcontainers.utility.MockTestcontainersConfigurationRule; +import org.testcontainers.utility.MockTestcontainersConfigurationExtension; import org.testcontainers.utility.MountableFile; import org.testcontainers.utility.TestcontainersConfiguration; @@ -53,15 +51,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(Enclosed.class) -public class ReusabilityUnitTests { +class ReusabilityUnitTests { - @RunWith(Parameterized.class) - @RequiredArgsConstructor - @FieldDefaults(makeFinal = true) - public static class CanBeReusedTest { + @Nested + class CanBeReusedTest { - @Parameterized.Parameters(name = "{0}") public static Object[][] data() { return new Object[][] { { "generic", new GenericContainer<>(TestImages.TINY_IMAGE), true }, @@ -72,14 +66,9 @@ public static Object[][] data() { }; } - String name; - - GenericContainer container; - - boolean reusable; - - @Test - public void shouldBeReusable() { + @ParameterizedTest(name = "{0}") + @MethodSource("data") + void shouldBeReusable(String name, GenericContainer container, boolean reusable) { if (reusable) { assertThat(container.canBeReused()).as("Is reusable").isTrue(); } else { @@ -108,9 +97,8 @@ protected void containerIsCreated(String containerId) { } } - @RunWith(BlockJUnit4ClassRunner.class) - @FieldDefaults(makeFinal = true) - public static class HooksTest extends AbstractReusabilityTest { + @Nested + class HooksTest extends AbstractReusabilityTest { List script = new ArrayList<>(); @@ -140,7 +128,7 @@ protected void containerIsStarted(InspectContainerResponse containerInfo, boolea ); @Test - public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() { + void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() { Mockito.doReturn(false).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); String containerId = randomContainerId(); @@ -159,7 +147,7 @@ public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() { } @Test - public void shouldCallHookIfReused() { + void shouldCallHookIfReused() { Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); String containerId = randomContainerId(); when(client.createContainerCmd(any())).then(createContainerAnswer(containerId)); @@ -172,7 +160,7 @@ public void shouldCallHookIfReused() { } @Test - public void shouldNotCallHookIfNotReused() { + void shouldNotCallHookIfNotReused() { String containerId = randomContainerId(); when(client.createContainerCmd(any())).then(createContainerAnswer(containerId)); when(client.listContainersCmd()).then(listContainersAnswer()); @@ -189,9 +177,8 @@ public void shouldNotCallHookIfNotReused() { } } - @RunWith(BlockJUnit4ClassRunner.class) - @FieldDefaults(makeFinal = true) - public static class HashTest extends AbstractReusabilityTest { + @Nested + class HashTest extends AbstractReusabilityTest { protected GenericContainer container = makeReusable( new GenericContainer(TestImages.TINY_IMAGE) { @@ -203,7 +190,7 @@ public void copyFileToContainer(MountableFile mountableFile, String containerPat ); @Test - public void shouldStartIfListReturnsEmpty() { + void shouldStartIfListReturnsEmpty() { String containerId = randomContainerId(); when(client.createContainerCmd(any())).then(createContainerAnswer(containerId)); when(client.listContainersCmd()).then(listContainersAnswer()); @@ -216,7 +203,7 @@ public void shouldStartIfListReturnsEmpty() { } @Test - public void shouldReuseIfListReturnsID() { + void shouldReuseIfListReturnsID() { Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); String containerId = randomContainerId(); when(client.createContainerCmd(any())).then(createContainerAnswer(containerId)); @@ -231,7 +218,7 @@ public void shouldReuseIfListReturnsID() { } @Test - public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() { + void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() { Mockito.doReturn(false).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); AtomicReference commandRef = new AtomicReference<>(); String containerId = randomContainerId(); @@ -250,7 +237,7 @@ public void shouldSetLabelsIfEnvironmentDoesNotSupportReuse() { } @Test - public void shouldSetCopiedFilesHashLabel() { + void shouldSetCopiedFilesHashLabel() { Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); AtomicReference commandRef = new AtomicReference<>(); String containerId = randomContainerId(); @@ -266,7 +253,7 @@ public void shouldSetCopiedFilesHashLabel() { } @Test - public void shouldHashCopiedFiles() { + void shouldHashCopiedFiles() { Mockito.doReturn(true).when(TestcontainersConfiguration.getInstance()).environmentSupportsReuse(); AtomicReference commandRef = new AtomicReference<>(); String containerId = randomContainerId(); @@ -303,9 +290,10 @@ public void shouldHashCopiedFiles() { } } - @RunWith(Parameterized.class) - @FieldDefaults(makeFinal = true) - public static class CopyFilesHashTest { + @Nested + @ParameterizedClass + @MethodSource("strategies") + class CopyFilesHashTest { private final TestStrategy strategy; @@ -353,7 +341,6 @@ public void clear() { } } - @Parameterized.Parameters public static List, TestStrategy>> strategies() { return Arrays.asList(MountableFileTestStrategy::new, TransferableTestStrategy::new); } @@ -365,12 +352,12 @@ public CopyFilesHashTest(Function, TestStrategy> strategyFac } @Test - public void empty() { + void empty() { assertThat(container.hashCopiedFiles()).isNotNull(); } @Test - public void oneFile() { + void oneFile() { long emptyHash = container.hashCopiedFiles().getValue(); strategy.withCopyFileToContainer( @@ -382,7 +369,7 @@ public void oneFile() { } @Test - public void differentPath() { + void differentPath() { MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt"); strategy.withCopyFileToContainer(mountableFile, "/foo/bar"); @@ -396,7 +383,7 @@ public void differentPath() { } @Test - public void detectsChangesInFile() throws Exception { + void detectsChangesInFile() throws Exception { Path path = File.createTempFile("reusable_test", ".txt").toPath(); MountableFile mountableFile = MountableFile.forHostPath(path); strategy.withCopyFileToContainer(mountableFile, "/foo/bar"); @@ -409,7 +396,7 @@ public void detectsChangesInFile() throws Exception { } @Test - public void multipleFiles() { + void multipleFiles() { strategy.withCopyFileToContainer( MountableFile.forClasspathResource("test_copy_to_container.txt"), "/foo/bar" @@ -425,7 +412,7 @@ public void multipleFiles() { } @Test - public void folder() throws Exception { + void folder() throws Exception { long emptyHash = container.hashCopiedFiles().getValue(); Path tempDirectory = Files.createTempDirectory("reusable_test"); @@ -436,7 +423,7 @@ public void folder() throws Exception { } @Test - public void changesInFolder() throws Exception { + void changesInFolder() throws Exception { Path tempDirectory = Files.createTempDirectory("reusable_test"); MountableFile mountableFile = MountableFile.forHostPath(tempDirectory); assertThat(new File(mountableFile.getResolvedPath())).isDirectory(); @@ -455,7 +442,7 @@ public void changesInFolder() throws Exception { } @Test - public void folderAndFile() throws Exception { + void folderAndFile() throws Exception { Path tempDirectory = Files.createTempDirectory("reusable_test"); MountableFile mountableFile = MountableFile.forHostPath(tempDirectory); assertThat(new File(mountableFile.getResolvedPath())).isDirectory(); @@ -472,7 +459,7 @@ public void folderAndFile() throws Exception { } @Test - public void filePermissions() throws Exception { + void filePermissions() throws Exception { Path path = File.createTempFile("reusable_test", ".txt").toPath(); path.toFile().setExecutable(false); MountableFile mountableFile = MountableFile.forHostPath(path); @@ -487,7 +474,7 @@ public void filePermissions() throws Exception { } @Test - public void folderPermissions() throws Exception { + void folderPermissions() throws Exception { Path tempDirectory = Files.createTempDirectory("reusable_test"); MountableFile mountableFile = MountableFile.forHostPath(tempDirectory); assertThat(new File(mountableFile.getResolvedPath())).isDirectory(); @@ -505,12 +492,9 @@ public void folderPermissions() throws Exception { } } - @FieldDefaults(makeFinal = true) + @ExtendWith(MockTestcontainersConfigurationExtension.class) public abstract static class AbstractReusabilityTest { - @Rule - public MockTestcontainersConfigurationRule configurationMock = new MockTestcontainersConfigurationRule(); - protected DockerClient client = Mockito.mock(DockerClient.class); protected > T makeReusable(T container) { diff --git a/core/src/test/java/org/testcontainers/containers/output/ContainerLogsTest.java b/core/src/test/java/org/testcontainers/containers/output/ContainerLogsTest.java index cc3a98dba47..f742b29890b 100644 --- a/core/src/test/java/org/testcontainers/containers/output/ContainerLogsTest.java +++ b/core/src/test/java/org/testcontainers/containers/output/ContainerLogsTest.java @@ -1,18 +1,18 @@ package org.testcontainers.containers.output; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; import static org.assertj.core.api.Assertions.assertThat; -public class ContainerLogsTest { +class ContainerLogsTest { @Test - @Ignore("fails due to the timing of the shell's decision to flush") - public void getLogsReturnsAllLogsToDate() { + @Disabled("fails due to the timing of the shell's decision to flush") + void getLogsReturnsAllLogsToDate() { try (GenericContainer container = shortLivedContainer()) { container.start(); @@ -22,7 +22,7 @@ public void getLogsReturnsAllLogsToDate() { } @Test - public void getLogsContainsBothOutputTypes() { + void getLogsContainsBothOutputTypes() { try (GenericContainer container = shortLivedContainer()) { container.start(); @@ -35,7 +35,7 @@ public void getLogsContainsBothOutputTypes() { } @Test - public void getLogsReturnsStdOutToDate() { + void getLogsReturnsStdOutToDate() { try (GenericContainer container = shortLivedContainer()) { container.start(); @@ -47,7 +47,7 @@ public void getLogsReturnsStdOutToDate() { } @Test - public void getLogsReturnsStdErrToDate() { + void getLogsReturnsStdErrToDate() { try (GenericContainer container = shortLivedContainer()) { container.start(); @@ -59,7 +59,7 @@ public void getLogsReturnsStdErrToDate() { } @Test - public void getLogsForLongRunningContainer() throws InterruptedException { + void getLogsForLongRunningContainer() throws InterruptedException { try (GenericContainer container = longRunningContainer()) { container.start(); diff --git a/core/src/test/java/org/testcontainers/containers/output/FrameConsumerResultCallbackTest.java b/core/src/test/java/org/testcontainers/containers/output/FrameConsumerResultCallbackTest.java index f6e513c1fd8..33ae9fd17f5 100644 --- a/core/src/test/java/org/testcontainers/containers/output/FrameConsumerResultCallbackTest.java +++ b/core/src/test/java/org/testcontainers/containers/output/FrameConsumerResultCallbackTest.java @@ -2,7 +2,7 @@ import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.StreamType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -12,7 +12,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class FrameConsumerResultCallbackTest { +class FrameConsumerResultCallbackTest { private static final String FRAME_PAYLOAD = "\u001B[0;32mТест1\u001B[0m\n\u001B[1;33mTest2\u001B[0m\n\u001B[0;31mTest3\u001B[0m"; @@ -20,7 +20,7 @@ public class FrameConsumerResultCallbackTest { private static final String LOG_RESULT = "Тест1\nTest2\nTest3"; @Test - public void passStderrFrameWithoutColors() throws IOException { + void passStderrFrameWithoutColors() throws IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer(); callback.addConsumer(OutputFrame.OutputType.STDERR, consumer); @@ -30,7 +30,7 @@ public void passStderrFrameWithoutColors() throws IOException { } @Test - public void passStderrFrameWithColors() throws IOException { + void passStderrFrameWithColors() throws IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false); callback.addConsumer(OutputFrame.OutputType.STDERR, consumer); @@ -40,7 +40,7 @@ public void passStderrFrameWithColors() throws IOException { } @Test - public void passStdoutFrameWithoutColors() throws IOException { + void passStdoutFrameWithoutColors() throws IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer(); callback.addConsumer(OutputFrame.OutputType.STDOUT, consumer); @@ -50,7 +50,7 @@ public void passStdoutFrameWithoutColors() throws IOException { } @Test - public void passStdoutFrameWithColors() throws IOException { + void passStdoutFrameWithColors() throws IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false); callback.addConsumer(OutputFrame.OutputType.STDOUT, consumer); @@ -60,7 +60,7 @@ public void passStdoutFrameWithColors() throws IOException { } @Test - public void basicConsumer() throws IOException { + void basicConsumer() throws IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); BasicConsumer consumer = new BasicConsumer(); callback.addConsumer(OutputFrame.OutputType.STDOUT, consumer); @@ -70,7 +70,7 @@ public void basicConsumer() throws IOException { } @Test - public void passStdoutNull() throws IOException { + void passStdoutNull() throws IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false); callback.addConsumer(OutputFrame.OutputType.STDOUT, consumer); @@ -80,7 +80,7 @@ public void passStdoutNull() throws IOException { } @Test - public void passStdoutEmptyLine() throws IOException { + void passStdoutEmptyLine() throws IOException { String payload = ""; FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false); @@ -91,7 +91,7 @@ public void passStdoutEmptyLine() throws IOException { } @Test - public void passStdoutSingleLine() throws IOException { + void passStdoutSingleLine() throws IOException { String payload = "Test"; FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false); @@ -102,7 +102,7 @@ public void passStdoutSingleLine() throws IOException { } @Test - public void passStdoutSingleLineWithNewline() throws IOException { + void passStdoutSingleLineWithNewline() throws IOException { String payload = "Test\n"; FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); ToStringConsumer consumer = new ToStringConsumer().withRemoveAnsiCodes(false); @@ -113,7 +113,7 @@ public void passStdoutSingleLineWithNewline() throws IOException { } @Test - public void passRawFrameWithoutColors() throws TimeoutException, IOException { + void passRawFrameWithoutColors() throws TimeoutException, IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); WaitingConsumer waitConsumer = new WaitingConsumer(); callback.addConsumer(OutputFrame.OutputType.STDOUT, waitConsumer); @@ -148,7 +148,7 @@ public void passRawFrameWithoutColors() throws TimeoutException, IOException { } @Test - public void passRawFrameWithColors() throws TimeoutException, IOException { + void passRawFrameWithColors() throws TimeoutException, IOException { FrameConsumerResultCallback callback = new FrameConsumerResultCallback(); WaitingConsumer waitConsumer = new WaitingConsumer().withRemoveAnsiCodes(false); callback.addConsumer(OutputFrame.OutputType.STDOUT, waitConsumer); @@ -203,7 +203,7 @@ public void passRawFrameWithColors() throws TimeoutException, IOException { } @Test - public void reconstructBreakedUnicode() throws IOException { + void reconstructBreakedUnicode() throws IOException { String payload = "Тест"; byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8); byte[] bytes1 = new byte[(int) (payloadBytes.length * 0.6)]; diff --git a/core/src/test/java/org/testcontainers/containers/output/ToStringConsumerTest.java b/core/src/test/java/org/testcontainers/containers/output/ToStringConsumerTest.java index eaab250141c..45472771168 100644 --- a/core/src/test/java/org/testcontainers/containers/output/ToStringConsumerTest.java +++ b/core/src/test/java/org/testcontainers/containers/output/ToStringConsumerTest.java @@ -1,14 +1,15 @@ package org.testcontainers.containers.output; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.containers.Container.ExecResult; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; import static org.assertj.core.api.Assertions.assertThat; -public class ToStringConsumerTest { +class ToStringConsumerTest { private static final String LARGE_PAYLOAD; @@ -22,7 +23,7 @@ public class ToStringConsumerTest { } @Test - public void newlines_are_not_added_to_exec_output() throws Exception { + void newlines_are_not_added_to_exec_output() throws Exception { try (GenericContainer container = new GenericContainer<>("alpine:3.17")) { container.withCommand("sleep", "2m"); container.start(); @@ -32,8 +33,9 @@ public void newlines_are_not_added_to_exec_output() throws Exception { } } - @Test(timeout = 60_000L) - public void newlines_are_not_added_to_exec_output_with_tty() throws Exception { + @Test + @Timeout(60) + void newlines_are_not_added_to_exec_output_with_tty() throws Exception { try (GenericContainer container = new GenericContainer<>("alpine:3.17")) { container.withCreateContainerCmdModifier(cmd -> { cmd.withAttachStdin(true).withStdinOpen(true).withTty(true); @@ -47,7 +49,7 @@ public void newlines_are_not_added_to_exec_output_with_tty() throws Exception { } @Test - public void newlines_are_not_added_to_container_output() { + void newlines_are_not_added_to_container_output() { try (GenericContainer container = new GenericContainer<>("alpine:3.17")) { container.withCommand("echo", "-n", LARGE_PAYLOAD); container.setStartupCheckStrategy(new OneShotStartupCheckStrategy()); @@ -60,7 +62,7 @@ public void newlines_are_not_added_to_container_output() { } @Test - public void newlines_are_not_added_to_container_output_with_tty() { + void newlines_are_not_added_to_container_output_with_tty() { try (GenericContainer container = new GenericContainer<>("alpine:3.17")) { container.withCreateContainerCmdModifier(cmd -> { cmd.withTty(true); diff --git a/core/src/test/java/org/testcontainers/containers/startupcheck/IsRunningStartupCheckStrategyTest.java b/core/src/test/java/org/testcontainers/containers/startupcheck/IsRunningStartupCheckStrategyTest.java index 7e3bf1d814f..fc7a60c2115 100644 --- a/core/src/test/java/org/testcontainers/containers/startupcheck/IsRunningStartupCheckStrategyTest.java +++ b/core/src/test/java/org/testcontainers/containers/startupcheck/IsRunningStartupCheckStrategyTest.java @@ -1,24 +1,24 @@ package org.testcontainers.containers.startupcheck; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class IsRunningStartupCheckStrategyTest { +class IsRunningStartupCheckStrategyTest { @Test - public void testCommandQuickExitSuccess() { + void testCommandQuickExitSuccess() { try (GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE).withCommand("/bin/true")) { container.start(); // should start with no Exception } } @Test - @Ignore("This test can fail to throw an AssertionError if the container doesn't fail quickly enough") - public void testCommandQuickExitFailure() { + @Disabled("This test can fail to throw an AssertionError if the container doesn't fail quickly enough") + void testCommandQuickExitFailure() { try (GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE).withCommand("/bin/false")) { assertThatThrownBy(container::start) .hasStackTraceContaining("Container startup failed") @@ -27,7 +27,7 @@ public void testCommandQuickExitFailure() { } @Test - public void testCommandStaysRunning() { + void testCommandStaysRunning() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE).withCommand("/bin/sleep", "60") ) { diff --git a/core/src/test/java/org/testcontainers/containers/wait/internal/ExternalPortListeningCheckTest.java b/core/src/test/java/org/testcontainers/containers/wait/internal/ExternalPortListeningCheckTest.java index b7d9fd5a6fa..c494100544f 100644 --- a/core/src/test/java/org/testcontainers/containers/wait/internal/ExternalPortListeningCheckTest.java +++ b/core/src/test/java/org/testcontainers/containers/wait/internal/ExternalPortListeningCheckTest.java @@ -1,9 +1,9 @@ package org.testcontainers.containers.wait.internal; import com.google.common.collect.ImmutableSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.wait.strategy.WaitStrategyTarget; import java.net.ServerSocket; @@ -13,7 +13,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ExternalPortListeningCheckTest { +class ExternalPortListeningCheckTest { private ServerSocket listeningSocket1; @@ -23,7 +23,7 @@ public class ExternalPortListeningCheckTest { private WaitStrategyTarget mockContainer; - @Before + @BeforeEach public void setUp() throws Exception { listeningSocket1 = new ServerSocket(0); listeningSocket2 = new ServerSocket(0); @@ -36,7 +36,7 @@ public void setUp() throws Exception { } @Test - public void singleListening() { + void singleListening() { final ExternalPortListeningCheck check = new ExternalPortListeningCheck( mockContainer, ImmutableSet.of(listeningSocket1.getLocalPort()) @@ -48,7 +48,7 @@ public void singleListening() { } @Test - public void multipleListening() { + void multipleListening() { final ExternalPortListeningCheck check = new ExternalPortListeningCheck( mockContainer, ImmutableSet.of(listeningSocket1.getLocalPort(), listeningSocket2.getLocalPort()) @@ -60,7 +60,7 @@ public void multipleListening() { } @Test - public void oneNotListening() { + void oneNotListening() { final ExternalPortListeningCheck check = new ExternalPortListeningCheck( mockContainer, ImmutableSet.of(listeningSocket1.getLocalPort(), nonListeningSocket.getLocalPort()) @@ -71,7 +71,7 @@ public void oneNotListening() { .isInstanceOf(IllegalStateException.class); } - @After + @AfterEach public void tearDown() throws Exception { listeningSocket1.close(); listeningSocket2.close(); diff --git a/core/src/test/java/org/testcontainers/containers/wait/internal/InternalCommandPortListeningCheckTest.java b/core/src/test/java/org/testcontainers/containers/wait/internal/InternalCommandPortListeningCheckTest.java index d93eb90c339..936be73fd3e 100644 --- a/core/src/test/java/org/testcontainers/containers/wait/internal/InternalCommandPortListeningCheckTest.java +++ b/core/src/test/java/org/testcontainers/containers/wait/internal/InternalCommandPortListeningCheckTest.java @@ -1,48 +1,46 @@ package org.testcontainers.containers.wait.internal; import com.google.common.collect.ImmutableSet; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.rnorth.ducttape.TimeoutException; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.containers.GenericContainer; import org.testcontainers.images.builder.ImageFromDockerfile; import java.util.Arrays; +import java.util.List; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) -public class InternalCommandPortListeningCheckTest { +@ParameterizedClass(name = "{index} - {0}") +@MethodSource("data") +class InternalCommandPortListeningCheckTest { - @Parameterized.Parameters(name = "{index} - {0}") - public static Iterable data() { + public static List data() { return Arrays.asList( - new Object[][] { - { "internal-port-check-dockerfile/Dockerfile-tcp" }, - { "internal-port-check-dockerfile/Dockerfile-nc" }, - { "internal-port-check-dockerfile/Dockerfile-bash" }, - } + "internal-port-check-dockerfile/Dockerfile-tcp", + "internal-port-check-dockerfile/Dockerfile-nc", + "internal-port-check-dockerfile/Dockerfile-bash" ); } - @Rule - public GenericContainer container; + public GenericContainer container; public InternalCommandPortListeningCheckTest(String dockerfile) { container = - new GenericContainer( + new GenericContainer<>( new ImageFromDockerfile() .withFileFromClasspath("Dockerfile", dockerfile) .withFileFromClasspath("nginx.conf", "internal-port-check-dockerfile/nginx.conf") ); + container.start(); } @Test - public void singleListening() { + void singleListening() { final InternalCommandPortListeningCheck check = new InternalCommandPortListeningCheck( container, ImmutableSet.of(8080) @@ -52,7 +50,7 @@ public void singleListening() { } @Test - public void nonListening() { + void nonListening() { final InternalCommandPortListeningCheck check = new InternalCommandPortListeningCheck( container, ImmutableSet.of(8080, 1234) @@ -65,7 +63,7 @@ public void nonListening() { } @Test - public void lowAndHighPortListening() { + void lowAndHighPortListening() { final InternalCommandPortListeningCheck check = new InternalCommandPortListeningCheck( container, ImmutableSet.of(100, 8080) diff --git a/core/src/test/java/org/testcontainers/containers/wait/strategy/DockerHealthcheckWaitStrategyTest.java b/core/src/test/java/org/testcontainers/containers/wait/strategy/DockerHealthcheckWaitStrategyTest.java index 0cbf257e9b5..653bbca2e33 100644 --- a/core/src/test/java/org/testcontainers/containers/wait/strategy/DockerHealthcheckWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/containers/wait/strategy/DockerHealthcheckWaitStrategyTest.java @@ -1,7 +1,7 @@ package org.testcontainers.containers.wait.strategy; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ContainerLaunchException; import org.testcontainers.containers.GenericContainer; import org.testcontainers.images.builder.ImageFromDockerfile; @@ -11,11 +11,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -public class DockerHealthcheckWaitStrategyTest { +class DockerHealthcheckWaitStrategyTest { private GenericContainer container; - @Before + @BeforeEach public void setUp() { // Using a Dockerfile here, since Dockerfile builder DSL doesn't support HEALTHCHECK container = @@ -31,12 +31,12 @@ public void setUp() { } @Test - public void startsOnceHealthy() { + void startsOnceHealthy() { container.start(); } @Test - public void containerStartFailsIfContainerIsUnhealthy() { + void containerStartFailsIfContainerIsUnhealthy() { container.withCommand("tail", "-f", "/dev/null"); assertThat(catchThrowable(container::start)) .as("Container launch fails when unhealthy") diff --git a/core/src/test/java/org/testcontainers/containers/wait/strategy/WaitAllStrategyTest.java b/core/src/test/java/org/testcontainers/containers/wait/strategy/WaitAllStrategyTest.java index 8b69553e5ab..aeebe425776 100644 --- a/core/src/test/java/org/testcontainers/containers/wait/strategy/WaitAllStrategyTest.java +++ b/core/src/test/java/org/testcontainers/containers/wait/strategy/WaitAllStrategyTest.java @@ -1,7 +1,7 @@ package org.testcontainers.containers.wait.strategy; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -20,7 +20,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -public class WaitAllStrategyTest { +class WaitAllStrategyTest { @Mock private GenericContainer container; @@ -34,7 +34,7 @@ public class WaitAllStrategyTest { @Mock private WaitStrategy strategy3; - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); } @@ -43,7 +43,7 @@ public void setUp() { * Dummy-based tests, to check that timeout values are propagated correctly, without involving actual timing-sensitive code */ @Test - public void parentTimeoutApplies() { + void parentTimeoutApplies() { DummyStrategy child1 = new DummyStrategy(Duration.ofMillis(10)); child1.withStartupTimeout(Duration.ofMillis(20)); @@ -55,7 +55,7 @@ public void parentTimeoutApplies() { } @Test - public void parentTimeoutAppliesToMultipleChildren() { + void parentTimeoutAppliesToMultipleChildren() { Duration defaultInnerWait = Duration.ofMillis(2); Duration outerWait = Duration.ofMillis(6); @@ -73,7 +73,7 @@ public void parentTimeoutAppliesToMultipleChildren() { } @Test - public void parentTimeoutAppliesToAdditionalChildren() { + void parentTimeoutAppliesToAdditionalChildren() { Duration defaultInnerWait = Duration.ofMillis(2); Duration outerWait = Duration.ofMillis(20); @@ -94,7 +94,7 @@ public void parentTimeoutAppliesToAdditionalChildren() { * Mock-based tests to check overall behaviour, without involving timing-sensitive code */ @Test - public void childExecutionTest() { + void childExecutionTest() { final WaitStrategy underTest = new WaitAllStrategy().withStrategy(strategy1).withStrategy(strategy2); doNothing().when(strategy1).waitUntilReady(eq(container)); @@ -108,7 +108,7 @@ public void childExecutionTest() { } @Test - public void withoutOuterTimeoutShouldRelyOnInnerStrategies() { + void withoutOuterTimeoutShouldRelyOnInnerStrategies() { final WaitStrategy underTest = new WaitAllStrategy(WaitAllStrategy.Mode.WITH_INDIVIDUAL_TIMEOUTS_ONLY) .withStrategy(strategy1) .withStrategy(strategy2) @@ -132,7 +132,7 @@ public void withoutOuterTimeoutShouldRelyOnInnerStrategies() { } @Test - public void timeoutChangeShouldNotBePossibleWithIndividualTimeoutMode() { + void timeoutChangeShouldNotBePossibleWithIndividualTimeoutMode() { final WaitStrategy underTest = new WaitAllStrategy(WaitAllStrategy.Mode.WITH_INDIVIDUAL_TIMEOUTS_ONLY); assertThat( @@ -145,7 +145,7 @@ public void timeoutChangeShouldNotBePossibleWithIndividualTimeoutMode() { } @Test - public void shouldNotMessWithIndividualTimeouts() { + void shouldNotMessWithIndividualTimeouts() { new WaitAllStrategy(WaitAllStrategy.Mode.WITH_INDIVIDUAL_TIMEOUTS_ONLY) .withStrategy(strategy1) .withStrategy(strategy2); @@ -155,7 +155,7 @@ public void shouldNotMessWithIndividualTimeouts() { } @Test - public void shouldOverwriteIndividualTimeouts() { + void shouldOverwriteIndividualTimeouts() { Duration someSeconds = Duration.ofSeconds(23); new WaitAllStrategy().withStartupTimeout(someSeconds).withStrategy(strategy1).withStrategy(strategy2); diff --git a/core/src/test/java/org/testcontainers/dockerclient/AmbiguousImagePullTest.java b/core/src/test/java/org/testcontainers/dockerclient/AmbiguousImagePullTest.java index f67ad212d77..df351b9fd74 100644 --- a/core/src/test/java/org/testcontainers/dockerclient/AmbiguousImagePullTest.java +++ b/core/src/test/java/org/testcontainers/dockerclient/AmbiguousImagePullTest.java @@ -1,14 +1,16 @@ package org.testcontainers.dockerclient; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.DockerRegistryContainer; import org.testcontainers.containers.GenericContainer; import org.testcontainers.utility.DockerImageName; -public class AmbiguousImagePullTest { +class AmbiguousImagePullTest { - @Test(timeout = 30_000) - public void testNotUsingParse() { + @Test + @Timeout(30) + void testNotUsingParse() { try (DockerRegistryContainer registryContainer = new DockerRegistryContainer()) { registryContainer.start(); DockerImageName imageName = registryContainer.createImage("latest"); diff --git a/core/src/test/java/org/testcontainers/dockerclient/DockerClientConfigUtilsTest.java b/core/src/test/java/org/testcontainers/dockerclient/DockerClientConfigUtilsTest.java index 757816cb189..f3bc15d2c22 100644 --- a/core/src/test/java/org/testcontainers/dockerclient/DockerClientConfigUtilsTest.java +++ b/core/src/test/java/org/testcontainers/dockerclient/DockerClientConfigUtilsTest.java @@ -2,19 +2,20 @@ import com.github.dockerjava.api.DockerClient; import org.assertj.core.api.Assumptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.DockerClientFactory; import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; -public class DockerClientConfigUtilsTest { +class DockerClientConfigUtilsTest { DockerClient client = DockerClientFactory.lazyClient(); @Test - public void getDockerHostIpAddressShouldReturnLocalhostWhenUnixSocket() { + void getDockerHostIpAddressShouldReturnLocalhostWhenUnixSocket() { Assumptions.assumeThat(DockerClientConfigUtils.IN_A_CONTAINER).as("in a container").isFalse(); String actual = DockerClientProviderStrategy.resolveDockerHostIpAddress( @@ -26,7 +27,7 @@ public void getDockerHostIpAddressShouldReturnLocalhostWhenUnixSocket() { } @Test - public void getDockerHostIpAddressShouldReturnDockerHostIpWhenHttpsUri() { + void getDockerHostIpAddressShouldReturnDockerHostIpWhenHttpsUri() { String actual = DockerClientProviderStrategy.resolveDockerHostIpAddress( client, URI.create("http://12.23.34.45"), @@ -36,7 +37,7 @@ public void getDockerHostIpAddressShouldReturnDockerHostIpWhenHttpsUri() { } @Test - public void getDockerHostIpAddressShouldReturnDockerHostIpWhenTcpUri() { + void getDockerHostIpAddressShouldReturnDockerHostIpWhenTcpUri() { String actual = DockerClientProviderStrategy.resolveDockerHostIpAddress( client, URI.create("tcp://12.23.34.45"), @@ -46,7 +47,7 @@ public void getDockerHostIpAddressShouldReturnDockerHostIpWhenTcpUri() { } @Test - public void getDockerHostIpAddressShouldReturnNullWhenUnsupportedUriScheme() { + void getDockerHostIpAddressShouldReturnNullWhenUnsupportedUriScheme() { String actual = DockerClientProviderStrategy.resolveDockerHostIpAddress( client, URI.create("gopher://12.23.34.45"), @@ -55,8 +56,9 @@ public void getDockerHostIpAddressShouldReturnNullWhenUnsupportedUriScheme() { assertThat(actual).isNull(); } - @Test(timeout = 5_000) - public void getDefaultGateway() { + @Test + @Timeout(5) + void getDefaultGateway() { assertThat(DockerClientConfigUtils.getDefaultGateway()).isNotNull(); } } diff --git a/core/src/test/java/org/testcontainers/dockerclient/EnvironmentAndSystemPropertyClientProviderStrategyTest.java b/core/src/test/java/org/testcontainers/dockerclient/EnvironmentAndSystemPropertyClientProviderStrategyTest.java index 58bd6984401..be4dcd446a8 100644 --- a/core/src/test/java/org/testcontainers/dockerclient/EnvironmentAndSystemPropertyClientProviderStrategyTest.java +++ b/core/src/test/java/org/testcontainers/dockerclient/EnvironmentAndSystemPropertyClientProviderStrategyTest.java @@ -2,13 +2,11 @@ import com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.dockerjava.transport.SSLConfig; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.testcontainers.utility.MockTestcontainersConfigurationRule; +import org.testcontainers.utility.MockTestcontainersConfigurationExtension; import org.testcontainers.utility.TestcontainersConfiguration; import java.io.IOException; @@ -27,17 +25,14 @@ * Test that we can use Testcontainers configuration file to override settings. We assume that docker-java has test * coverage for detection of environment variables (e.g. DOCKER_HOST) and its own properties config file. */ -@RunWith(MockitoJUnitRunner.class) -public class EnvironmentAndSystemPropertyClientProviderStrategyTest { - - @Rule - public MockTestcontainersConfigurationRule mockConfig = new MockTestcontainersConfigurationRule(); +@ExtendWith(MockTestcontainersConfigurationExtension.class) +class EnvironmentAndSystemPropertyClientProviderStrategyTest { private URI defaultDockerHost; private com.github.dockerjava.core.SSLConfig defaultSSLConfig; - @Before + @BeforeEach public void checkEnvironmentClear() { // If docker-java picks up non-default settings from the environment, our test needs to know to expect those DefaultDockerClientConfig defaultConfig = DefaultDockerClientConfig.createDefaultConfigBuilder().build(); @@ -46,7 +41,7 @@ public void checkEnvironmentClear() { } @Test - public void testWhenConfigAbsent() { + void testWhenConfigAbsent() { Mockito .doReturn("auto") .when(TestcontainersConfiguration.getInstance()) @@ -72,7 +67,7 @@ public void testWhenConfigAbsent() { } @Test - public void testWhenDockerHostPresent() { + void testWhenDockerHostPresent() { Mockito .doReturn("auto") .when(TestcontainersConfiguration.getInstance()) @@ -98,7 +93,7 @@ public void testWhenDockerHostPresent() { } @Test - public void testWhenDockerHostAndSSLConfigPresent() throws IOException { + void testWhenDockerHostAndSSLConfigPresent() throws IOException { Path tempDir = Files.createTempDirectory("testcontainers-test"); String tempDirPath = tempDir.toAbsolutePath().toString(); @@ -129,7 +124,7 @@ public void testWhenDockerHostAndSSLConfigPresent() throws IOException { } @Test - public void applicableWhenIgnoringUserPropertiesAndConfigured() { + void applicableWhenIgnoringUserPropertiesAndConfigured() { Mockito .doReturn("autoIgnoringUserProperties") .when(TestcontainersConfiguration.getInstance()) @@ -147,7 +142,7 @@ public void applicableWhenIgnoringUserPropertiesAndConfigured() { } @Test - public void notApplicableWhenIgnoringUserPropertiesAndNotConfigured() { + void notApplicableWhenIgnoringUserPropertiesAndNotConfigured() { assumeThat(System.getenv("DOCKER_HOST")).isNull(); Mockito diff --git a/core/src/test/java/org/testcontainers/dockerclient/EventStreamTest.java b/core/src/test/java/org/testcontainers/dockerclient/EventStreamTest.java index 642eb6d7390..2976c56c7a9 100644 --- a/core/src/test/java/org/testcontainers/dockerclient/EventStreamTest.java +++ b/core/src/test/java/org/testcontainers/dockerclient/EventStreamTest.java @@ -4,9 +4,8 @@ import com.github.dockerjava.api.model.Event; import com.github.dockerjava.core.command.EventsResultCallback; import org.jetbrains.annotations.NotNull; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.DockerClientFactory; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; @@ -20,16 +19,14 @@ /** * Test that event streaming from the {@link DockerClient} works correctly */ -public class EventStreamTest { - - @Rule - public Timeout timeout = new Timeout(10, TimeUnit.SECONDS); +@Timeout(10) +class EventStreamTest { /** * Test that docker events can be streamed from the client. */ @Test - public void test() throws IOException, InterruptedException { + void test() throws IOException, InterruptedException { CountDownLatch latch = new CountDownLatch(1); try ( diff --git a/core/src/test/java/org/testcontainers/dockerclient/ImagePullTest.java b/core/src/test/java/org/testcontainers/dockerclient/ImagePullTest.java index 42cff09c335..d5329430e71 100644 --- a/core/src/test/java/org/testcontainers/dockerclient/ImagePullTest.java +++ b/core/src/test/java/org/testcontainers/dockerclient/ImagePullTest.java @@ -1,18 +1,13 @@ package org.testcontainers.dockerclient; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; import org.testcontainers.utility.DockerImageName; -@RunWith(Parameterized.class) -public class ImagePullTest { +class ImagePullTest { - private final String image; - - @Parameterized.Parameters(name = "{0}") public static String[] parameters() { return new String[] { "alpine:latest", @@ -26,12 +21,9 @@ public static String[] parameters() { }; } - public ImagePullTest(String image) { - this.image = image; - } - - @Test - public void test() { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + void test(String image) { try ( final GenericContainer container = new GenericContainer<>(DockerImageName.parse(image)) .withCommand("/bin/sh", "-c", "sleep 0") diff --git a/core/src/test/java/org/testcontainers/dockerclient/TestcontainersHostPropertyClientProviderStrategyTest.java b/core/src/test/java/org/testcontainers/dockerclient/TestcontainersHostPropertyClientProviderStrategyTest.java index 4ebdb300a2f..2c3d3ac40de 100644 --- a/core/src/test/java/org/testcontainers/dockerclient/TestcontainersHostPropertyClientProviderStrategyTest.java +++ b/core/src/test/java/org/testcontainers/dockerclient/TestcontainersHostPropertyClientProviderStrategyTest.java @@ -1,29 +1,20 @@ package org.testcontainers.dockerclient; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.testcontainers.utility.MockTestcontainersConfigurationRule; +import org.testcontainers.utility.MockTestcontainersConfigurationExtension; import org.testcontainers.utility.TestcontainersConfiguration; -import java.net.URI; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; -@RunWith(MockitoJUnitRunner.class) -public class TestcontainersHostPropertyClientProviderStrategyTest { - - @Rule - public MockTestcontainersConfigurationRule mockConfig = new MockTestcontainersConfigurationRule(); - - private URI defaultDockerHost; +@ExtendWith(MockTestcontainersConfigurationExtension.class) +class TestcontainersHostPropertyClientProviderStrategyTest { @Test - public void tcHostPropertyIsProvided() { + void tcHostPropertyIsProvided() { Mockito .doReturn("tcp://127.0.0.1:9000") .when(TestcontainersConfiguration.getInstance()) @@ -37,7 +28,7 @@ public void tcHostPropertyIsProvided() { } @Test - public void tcHostPropertyIsNotProvided() { + void tcHostPropertyIsNotProvided() { Mockito.doReturn(null).when(TestcontainersConfiguration.getInstance()).getUserProperty(eq("tc.host"), isNull()); TestcontainersHostPropertyClientProviderStrategy strategy = new TestcontainersHostPropertyClientProviderStrategy(); diff --git a/core/src/test/java/org/testcontainers/images/AgeBasedPullPolicyTest.java b/core/src/test/java/org/testcontainers/images/AgeBasedPullPolicyTest.java index 0bdf969688b..254633ea6e7 100644 --- a/core/src/test/java/org/testcontainers/images/AgeBasedPullPolicyTest.java +++ b/core/src/test/java/org/testcontainers/images/AgeBasedPullPolicyTest.java @@ -1,6 +1,6 @@ package org.testcontainers.images; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.utility.DockerImageName; import java.time.Duration; @@ -10,12 +10,12 @@ import static org.assertj.core.api.Assertions.assertThat; -public class AgeBasedPullPolicyTest { +class AgeBasedPullPolicyTest { final DockerImageName imageName = DockerImageName.parse(UUID.randomUUID().toString()); @Test - public void shouldPull() { + void shouldPull() { ImageData imageData = ImageData.builder().createdAt(Instant.now().minus(2, ChronoUnit.HOURS)).build(); AgeBasedPullPolicy oneHour = new AgeBasedPullPolicy(Duration.of(1L, ChronoUnit.HOURS)); diff --git a/core/src/test/java/org/testcontainers/images/ImageDataTest.java b/core/src/test/java/org/testcontainers/images/ImageDataTest.java index 6ff75e9e355..b9fe0ae3c42 100644 --- a/core/src/test/java/org/testcontainers/images/ImageDataTest.java +++ b/core/src/test/java/org/testcontainers/images/ImageDataTest.java @@ -1,23 +1,23 @@ package org.testcontainers.images; import com.github.dockerjava.api.command.InspectImageResponse; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import static org.assertj.core.api.Assertions.assertThat; -public class ImageDataTest { +class ImageDataTest { @Test - public void shouldReadTimestampWithoutOffsetFromInspectImageResponse() { + void shouldReadTimestampWithoutOffsetFromInspectImageResponse() { final String timestamp = "2020-07-27T18:23:31.365190246Z"; final ImageData imageData = ImageData.from(new InspectImageResponse().withCreated(timestamp)); assertThat(imageData.getCreatedAt()).isEqualTo(Instant.parse(timestamp)); } @Test - public void shouldReadTimestampWithOffsetFromInspectImageResponse() { + void shouldReadTimestampWithOffsetFromInspectImageResponse() { final String timestamp = "2020-07-27T18:23:31.365190246+02:00"; final ImageData imageData = ImageData.from(new InspectImageResponse().withCreated(timestamp)); assertThat(imageData.getCreatedAt()).isEqualTo(Instant.parse("2020-07-27T16:23:31.365190246Z")); diff --git a/core/src/test/java/org/testcontainers/images/ImagePullPolicyTest.java b/core/src/test/java/org/testcontainers/images/ImagePullPolicyTest.java index a885c035e5c..6c763de2962 100644 --- a/core/src/test/java/org/testcontainers/images/ImagePullPolicyTest.java +++ b/core/src/test/java/org/testcontainers/images/ImagePullPolicyTest.java @@ -1,8 +1,8 @@ package org.testcontainers.images; import com.github.dockerjava.api.exception.NotFoundException; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.testcontainers.DockerClientFactory; import org.testcontainers.DockerRegistryContainer; @@ -14,22 +14,26 @@ import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; -public class ImagePullPolicyTest { +class ImagePullPolicyTest { - @ClassRule + @AutoClose public static DockerRegistryContainer registry = new DockerRegistryContainer(); private final DockerImageName imageName = registry.createImage(); + static { + registry.start(); + } + @Test - public void pullsByDefault() { + void pullsByDefault() { try (GenericContainer container = new GenericContainer<>(imageName).withExposedPorts(8080)) { container.start(); } } @Test - public void shouldAlwaysPull() { + void shouldAlwaysPull() { try (GenericContainer container = new GenericContainer<>(imageName).withExposedPorts(8080)) { container.start(); } @@ -52,7 +56,7 @@ public void shouldAlwaysPull() { } @Test - public void shouldSupportCustomPolicies() { + void shouldSupportCustomPolicies() { try ( // custom_image_pull_policy { GenericContainer container = new GenericContainer<>(imageName) @@ -72,7 +76,7 @@ protected boolean shouldPullCached(DockerImageName imageName, ImageData localIma } @Test - public void shouldCheckPolicy() { + void shouldCheckPolicy() { ImagePullPolicy policy = Mockito.spy( new AbstractImagePullPolicy() { @Override @@ -93,7 +97,7 @@ protected boolean shouldPullCached(DockerImageName imageName, ImageData localIma } @Test - public void shouldNotForcePulling() { + void shouldNotForcePulling() { try ( GenericContainer container = new GenericContainer<>(imageName) .withImagePullPolicy(__ -> false) diff --git a/core/src/test/java/org/testcontainers/images/OverrideImagePullPolicyTest.java b/core/src/test/java/org/testcontainers/images/OverrideImagePullPolicyTest.java index 43c026ea294..a18d0130383 100644 --- a/core/src/test/java/org/testcontainers/images/OverrideImagePullPolicyTest.java +++ b/core/src/test/java/org/testcontainers/images/OverrideImagePullPolicyTest.java @@ -1,28 +1,26 @@ package org.testcontainers.images; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.testcontainers.DockerRegistryContainer; import org.testcontainers.containers.GenericContainer; import org.testcontainers.utility.FakeImagePullPolicy; -import org.testcontainers.utility.MockTestcontainersConfigurationRule; +import org.testcontainers.utility.MockTestcontainersConfigurationExtension; import org.testcontainers.utility.TestcontainersConfiguration; import static org.assertj.core.api.Assertions.assertThat; -public class OverrideImagePullPolicyTest { - - @Rule - public MockTestcontainersConfigurationRule config = new MockTestcontainersConfigurationRule(); +@ExtendWith(MockTestcontainersConfigurationExtension.class) +class OverrideImagePullPolicyTest { private ImagePullPolicy originalInstance; private ImagePullPolicy originalDefaultImplementation; - @Before + @BeforeEach public void setUp() { this.originalInstance = PullPolicy.instance; this.originalDefaultImplementation = PullPolicy.defaultImplementation; @@ -30,14 +28,14 @@ public void setUp() { PullPolicy.defaultImplementation = Mockito.mock(ImagePullPolicy.class); } - @After + @AfterEach public void tearDown() { PullPolicy.instance = originalInstance; PullPolicy.defaultImplementation = originalDefaultImplementation; } @Test - public void simpleConfigurationTest() { + void simpleConfigurationTest() { Mockito .doReturn(FakeImagePullPolicy.class.getCanonicalName()) .when(TestcontainersConfiguration.getInstance()) @@ -53,7 +51,7 @@ public void simpleConfigurationTest() { } @Test - public void alwaysPullConfigurationTest() { + void alwaysPullConfigurationTest() { Mockito .doReturn(AlwaysPullPolicy.class.getCanonicalName()) .when(TestcontainersConfiguration.getInstance()) diff --git a/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java b/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java index f8c66860022..e881f0167e2 100644 --- a/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java +++ b/core/src/test/java/org/testcontainers/images/ParsedDockerfileTest.java @@ -1,17 +1,17 @@ package org.testcontainers.images; import com.google.common.collect.Sets; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.file.Paths; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; -public class ParsedDockerfileTest { +class ParsedDockerfileTest { @Test - public void doesSimpleParsing() { + void doesSimpleParsing() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM someimage", "RUN something") ); @@ -21,7 +21,7 @@ public void doesSimpleParsing() { } @Test - public void isCaseInsensitive() { + void isCaseInsensitive() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("from someimage", "RUN something") ); @@ -31,7 +31,7 @@ public void isCaseInsensitive() { } @Test - public void handlesTags() { + void handlesTags() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM someimage:tag", "RUN something") ); @@ -41,7 +41,7 @@ public void handlesTags() { } @Test - public void handlesDigests() { + void handlesDigests() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM someimage@sha256:abc123", "RUN something") ); @@ -51,7 +51,7 @@ public void handlesDigests() { } @Test - public void ignoringCommentedFromLines() { + void ignoringCommentedFromLines() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM someimage", "#FROM somethingelse") ); @@ -61,7 +61,7 @@ public void ignoringCommentedFromLines() { } @Test - public void ignoringBuildStageNames() { + void ignoringBuildStageNames() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM someimage --as=base", "RUN something", "FROM nextimage", "RUN something") ); @@ -71,7 +71,7 @@ public void ignoringBuildStageNames() { } @Test - public void ignoringPlatformArgs() { + void ignoringPlatformArgs() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM --platform=linux/amd64 someimage", "RUN something") ); @@ -81,7 +81,7 @@ public void ignoringPlatformArgs() { } @Test - public void ignoringExtraPlatformArgs() { + void ignoringExtraPlatformArgs() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("FROM --platform=linux/amd64 --somethingelse=value someimage", "RUN something") ); @@ -91,7 +91,7 @@ public void ignoringExtraPlatformArgs() { } @Test - public void handlesGracefullyIfNoFromLine() { + void handlesGracefullyIfNoFromLine() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile( Arrays.asList("RUN something", "# is this even a valid Dockerfile?") ); @@ -101,7 +101,7 @@ public void handlesGracefullyIfNoFromLine() { } @Test - public void handlesGracefullyIfDockerfileNotFound() { + void handlesGracefullyIfDockerfileNotFound() { final ParsedDockerfile parsedDockerfile = new ParsedDockerfile(Paths.get("nonexistent.Dockerfile")); assertThat(parsedDockerfile.getDependencyImageNames()) .as("handles missing Dockerfiles gracefully") diff --git a/core/src/test/java/org/testcontainers/images/RemoteDockerImageTest.java b/core/src/test/java/org/testcontainers/images/RemoteDockerImageTest.java index 9e4ac66fb53..156df3ae7d3 100644 --- a/core/src/test/java/org/testcontainers/images/RemoteDockerImageTest.java +++ b/core/src/test/java/org/testcontainers/images/RemoteDockerImageTest.java @@ -1,6 +1,7 @@ package org.testcontainers.images; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.utility.Base58; import org.testcontainers.utility.DockerImageName; import org.testcontainers.utility.LazyFuture; @@ -11,17 +12,17 @@ import static org.assertj.core.api.Assertions.assertThat; -public class RemoteDockerImageTest { +class RemoteDockerImageTest { @Test - public void toStringContainsOnlyImageName() { + void toStringContainsOnlyImageName() { String imageName = Base58.randomString(8).toLowerCase(); RemoteDockerImage remoteDockerImage = new RemoteDockerImage(DockerImageName.parse(imageName)); assertThat(remoteDockerImage.toString()).contains("imageName=" + imageName); } @Test - public void toStringWithExceptionContainsOnlyImageNameFuture() { + void toStringWithExceptionContainsOnlyImageNameFuture() { CompletableFuture imageNameFuture = new CompletableFuture<>(); imageNameFuture.completeExceptionally(new RuntimeException("arbitrary")); @@ -29,8 +30,9 @@ public void toStringWithExceptionContainsOnlyImageNameFuture() { assertThat(remoteDockerImage.toString()).contains("imageName=java.lang.RuntimeException: arbitrary"); } - @Test(timeout = 5000L) - public void toStringDoesntResolveImageNameFuture() { + @Test + @Timeout(5) + void toStringDoesntResolveImageNameFuture() { CompletableFuture imageNameFuture = new CompletableFuture<>(); // verify that we've set up the test properly @@ -47,8 +49,9 @@ public void toStringDoesntResolveImageNameFuture() { assertThat(remoteDockerImage.toString()).contains("imageName=" + imageName); } - @Test(timeout = 5000L) - public void toStringDoesntResolveLazyFuture() throws Exception { + @Test + @Timeout(5) + void toStringDoesntResolveLazyFuture() throws Exception { String imageName = Base58.randomString(8).toLowerCase(); AtomicBoolean resolved = new AtomicBoolean(false); Future imageNameFuture = new LazyFuture() { diff --git a/core/src/test/java/org/testcontainers/images/builder/DockerfileBuildTest.java b/core/src/test/java/org/testcontainers/images/builder/DockerfileBuildTest.java index b2c7075f4d2..fae6fc3193d 100644 --- a/core/src/test/java/org/testcontainers/images/builder/DockerfileBuildTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/DockerfileBuildTest.java @@ -1,8 +1,8 @@ package org.testcontainers.images.builder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; @@ -10,20 +10,15 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class DockerfileBuildTest { +class DockerfileBuildTest { static final Path RESOURCE_PATH = Paths.get("src/test/resources/dockerfile-build-test"); - public String expectedFileContent; - - public ImageFromDockerfile image; - - @Parameterized.Parameters - public static Object[][] parameters() { + public static Stream parameters() { Map buildArgs = new HashMap<>(4); buildArgs.put("BUILD_IMAGE", "alpine:3.16"); buildArgs.put("BASE_IMAGE", "alpine"); @@ -31,55 +26,50 @@ public static Object[][] parameters() { buildArgs.put("UNUSED", "ignored"); //noinspection deprecation - return new Object[][] { + return Stream.of( // Dockerfile build without explicit per-file inclusion - new Object[] { + Arguments.of( "test1234", // spotless:off // docsShowRecursiveFileInclusion { new ImageFromDockerfile() - .withFileFromPath(".", RESOURCE_PATH), + .withFileFromPath(".", RESOURCE_PATH)), // } // spotless:on - }, // Dockerfile build using a non-standard Dockerfile - new Object[] { + Arguments.of( "test4567", - new ImageFromDockerfile().withFileFromPath(".", RESOURCE_PATH).withDockerfilePath("./Dockerfile-alt"), - }, + new ImageFromDockerfile().withFileFromPath(".", RESOURCE_PATH).withDockerfilePath("./Dockerfile-alt") + ), // Dockerfile build using withBuildArg() - new Object[] { + Arguments.of( "test7890", new ImageFromDockerfile() .withFileFromPath(".", RESOURCE_PATH) .withDockerfilePath("./Dockerfile-buildarg") - .withBuildArg("CUSTOM_ARG", "test7890"), - }, + .withBuildArg("CUSTOM_ARG", "test7890") + ), // Dockerfile build using withBuildArgs() with build args in FROM statement - new Object[] { + Arguments.of( "test1234", new ImageFromDockerfile() .withFileFromPath(".", RESOURCE_PATH) .withDockerfile(RESOURCE_PATH.resolve("Dockerfile-from-buildarg")) - .withBuildArgs(buildArgs), - }, + .withBuildArgs(buildArgs) + ), // Dockerfile build using withDockerfile(File) - new Object[] { + Arguments.of( "test4567", new ImageFromDockerfile() .withFileFromPath(".", RESOURCE_PATH) - .withDockerfile(RESOURCE_PATH.resolve("Dockerfile-alt")), - }, - }; - } - - public DockerfileBuildTest(String expectedFileContent, ImageFromDockerfile image) { - this.expectedFileContent = expectedFileContent; - this.image = image; + .withDockerfile(RESOURCE_PATH.resolve("Dockerfile-alt")) + ) + ); } - @Test - public void performTest() { + @ParameterizedTest + @MethodSource("parameters") + void performTest(String expectedFileContent, ImageFromDockerfile image) { try ( final GenericContainer container = new GenericContainer<>(image) .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) diff --git a/core/src/test/java/org/testcontainers/images/builder/DockerignoreTest.java b/core/src/test/java/org/testcontainers/images/builder/DockerignoreTest.java index 8c6d288da99..6f7329f9dd2 100644 --- a/core/src/test/java/org/testcontainers/images/builder/DockerignoreTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/DockerignoreTest.java @@ -1,7 +1,7 @@ package org.testcontainers.images.builder; import com.github.dockerjava.api.exception.DockerClientException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; import org.testcontainers.utility.DockerImageName; @@ -12,12 +12,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -public class DockerignoreTest { +class DockerignoreTest { private static final Path INVALID_DOCKERIGNORE_PATH = Paths.get("src/test/resources/dockerfile-build-invalid"); @Test - public void testInvalidDockerignore() throws Exception { + void testInvalidDockerignore() throws Exception { try { new ImageFromDockerfile() .withFileFromPath(".", INVALID_DOCKERIGNORE_PATH) @@ -33,7 +33,7 @@ public void testInvalidDockerignore() throws Exception { @SuppressWarnings("resource") @Test - public void testValidDockerignore() throws Exception { + void testValidDockerignore() throws Exception { ImageFromDockerfile img = new ImageFromDockerfile() .withFileFromPath(".", DockerfileBuildTest.RESOURCE_PATH) .withDockerfile(DockerfileBuildTest.RESOURCE_PATH.resolve("Dockerfile-currentdir")); diff --git a/core/src/test/java/org/testcontainers/images/builder/ImageFromDockerfileTest.java b/core/src/test/java/org/testcontainers/images/builder/ImageFromDockerfileTest.java index b761d984187..0ce8ec041bf 100644 --- a/core/src/test/java/org/testcontainers/images/builder/ImageFromDockerfileTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/ImageFromDockerfileTest.java @@ -2,16 +2,16 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectImageResponse; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.utility.Base58; import static org.assertj.core.api.Assertions.assertThat; -public class ImageFromDockerfileTest { +class ImageFromDockerfileTest { @Test - public void shouldAddDefaultLabels() { + void shouldAddDefaultLabels() { ImageFromDockerfile image = new ImageFromDockerfile().withDockerfileFromBuilder(it -> it.from("scratch")); String imageId = image.resolve(); @@ -25,7 +25,7 @@ public void shouldAddDefaultLabels() { } @Test - public void shouldNotAddSessionLabelIfDeleteOnExitIsFalse() { + void shouldNotAddSessionLabelIfDeleteOnExitIsFalse() { ImageFromDockerfile image = new ImageFromDockerfile( "localhost/testcontainers/" + Base58.randomString(16).toLowerCase(), false diff --git a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/AbstractStatementTest.java b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/AbstractStatementTest.java index 0c47d556137..28cb0407f25 100644 --- a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/AbstractStatementTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/AbstractStatementTest.java @@ -3,8 +3,7 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.junit.Rule; -import org.junit.rules.TestName; +import org.junit.jupiter.api.TestInfo; import org.rnorth.ducttape.Preconditions; import java.io.InputStream; @@ -14,13 +13,17 @@ public abstract class AbstractStatementTest { - @Rule - public TestName testName = new TestName(); + private final TestInfo testInfo; + + AbstractStatementTest(TestInfo testInfo) { + this.testInfo = testInfo; + } protected void assertStatement(Statement statement) { + String testName = testInfo.getTestMethod().get().getName(); String[] expectedLines = new String[0]; try { - String path = "fixtures/statements/" + getClass().getSimpleName() + "/" + testName.getMethodName(); + String path = "fixtures/statements/" + getClass().getSimpleName() + "/" + testName; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path); Preconditions.check("inputStream is null for path " + path, inputStream != null); @@ -29,7 +32,7 @@ protected void assertStatement(Statement statement) { IOUtils.closeQuietly(inputStream); expectedLines = StringUtils.chomp(content.replaceAll("\r\n", "\n").trim()).split("\n"); } catch (Exception e) { - fail("can't load fixture '" + testName.getMethodName() + "'\n" + ExceptionUtils.getStackTrace(e)); + fail("can't load fixture '" + testName + "'\n" + ExceptionUtils.getStackTrace(e)); } StringBuilder builder = new StringBuilder(); diff --git a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/KeyValuesStatementTest.java b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/KeyValuesStatementTest.java index f446e48b42c..3ccd78faf7f 100644 --- a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/KeyValuesStatementTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/KeyValuesStatementTest.java @@ -1,14 +1,19 @@ package org.testcontainers.images.builder.dockerfile.statement; import com.google.common.collect.ImmutableMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import java.util.Collections; -public class KeyValuesStatementTest extends AbstractStatementTest { +class KeyValuesStatementTest extends AbstractStatementTest { + + KeyValuesStatementTest(TestInfo testInfo) { + super(testInfo); + } @Test - public void multilineTest() throws Exception { + void multilineTest() throws Exception { ImmutableMap pairs = ImmutableMap .builder() .put("line1", "1") @@ -20,22 +25,22 @@ public void multilineTest() throws Exception { } @Test - public void keyWithSpacesTest() throws Exception { + void keyWithSpacesTest() throws Exception { assertStatement(new KeyValuesStatement("TEST", Collections.singletonMap("key with spaces", "1"))); } @Test - public void keyWithNewLinesTest() throws Exception { + void keyWithNewLinesTest() throws Exception { assertStatement(new KeyValuesStatement("TEST", Collections.singletonMap("key\nwith\nnewlines", "1"))); } @Test - public void keyWithTabsTest() throws Exception { + void keyWithTabsTest() throws Exception { assertStatement(new KeyValuesStatement("TEST", Collections.singletonMap("key\twith\ttab", "1"))); } @Test - public void valueIsEscapedTest() throws Exception { + void valueIsEscapedTest() throws Exception { ImmutableMap pairs = ImmutableMap .builder() .put("1", "value with spaces") diff --git a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/MultiArgsStatementTest.java b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/MultiArgsStatementTest.java index 50bc8bedd96..06d8fccccc0 100644 --- a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/MultiArgsStatementTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/MultiArgsStatementTest.java @@ -1,16 +1,21 @@ package org.testcontainers.images.builder.dockerfile.statement; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; -public class MultiArgsStatementTest extends AbstractStatementTest { +class MultiArgsStatementTest extends AbstractStatementTest { + + MultiArgsStatementTest(TestInfo testInfo) { + super(testInfo); + } @Test - public void simpleTest() throws Exception { + void simpleTest() { assertStatement(new MultiArgsStatement("TEST", "a", "b", "c")); } @Test - public void multilineTest() throws Exception { + void multilineTest() { assertStatement(new MultiArgsStatement("TEST", "some\nmultiline\nargument")); } } diff --git a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/RawStatementTest.java b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/RawStatementTest.java index 70724a03f09..d6964e0e5d7 100644 --- a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/RawStatementTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/RawStatementTest.java @@ -1,11 +1,16 @@ package org.testcontainers.images.builder.dockerfile.statement; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; -public class RawStatementTest extends AbstractStatementTest { +class RawStatementTest extends AbstractStatementTest { + + RawStatementTest(TestInfo testInfo) { + super(testInfo); + } @Test - public void simpleTest() throws Exception { + void simpleTest() throws Exception { assertStatement(new RawStatement("TEST", "value\nas\t\\\nis")); } } diff --git a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/SingleArgumentStatementTest.java b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/SingleArgumentStatementTest.java index dbdabab9fff..cf446ef1018 100644 --- a/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/SingleArgumentStatementTest.java +++ b/core/src/test/java/org/testcontainers/images/builder/dockerfile/statement/SingleArgumentStatementTest.java @@ -1,16 +1,21 @@ package org.testcontainers.images.builder.dockerfile.statement; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; -public class SingleArgumentStatementTest extends AbstractStatementTest { +class SingleArgumentStatementTest extends AbstractStatementTest { + + SingleArgumentStatementTest(TestInfo testInfo) { + super(testInfo); + } @Test - public void simpleTest() throws Exception { + void simpleTest() throws Exception { assertStatement(new SingleArgumentStatement("TEST", "hello")); } @Test - public void multilineTest() throws Exception { + void multilineTest() throws Exception { assertStatement(new SingleArgumentStatement("TEST", "hello\nworld")); } } diff --git a/core/src/test/java/org/testcontainers/junit/BaseComposeTest.java b/core/src/test/java/org/testcontainers/junit/BaseComposeTest.java index 4d919388eb7..fc28f771749 100644 --- a/core/src/test/java/org/testcontainers/junit/BaseComposeTest.java +++ b/core/src/test/java/org/testcontainers/junit/BaseComposeTest.java @@ -1,11 +1,11 @@ package org.testcontainers.junit; import com.github.dockerjava.api.model.Network; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.utility.TestEnvironment; @@ -25,13 +25,13 @@ public abstract class BaseComposeTest { private List existingNetworks = new ArrayList<>(); - @BeforeClass + @BeforeAll public static void checkVersion() { - Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); + Assumptions.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); } @Test - public void simpleTest() { + void simpleTest() { Jedis jedis = new Jedis( getEnvironment().getServiceHost("redis-1", REDIS_PORT), getEnvironment().getServicePort("redis-1", REDIS_PORT) @@ -45,7 +45,7 @@ public void simpleTest() { } @Test - public void secondTest() { + void secondTest() { // used in manual checking for cleanup in between tests Jedis jedis = new Jedis( getEnvironment().getServiceHost("redis-1", REDIS_PORT), @@ -61,12 +61,12 @@ public void secondTest() { // However, @Rule creates a separate DockerComposeContainer instance per test, so this just shouldn't happen } - @Before + @BeforeEach public void captureNetworks() { existingNetworks.addAll(findAllNetworks()); } - @After + @AfterEach public void verifyNoNetworks() { assertThat(findAllNetworks()).as("The networks").isEqualTo(existingNetworks); } diff --git a/core/src/test/java/org/testcontainers/junit/BaseDockerComposeTest.java b/core/src/test/java/org/testcontainers/junit/BaseDockerComposeTest.java index c1aee4d7f2b..926fa301836 100644 --- a/core/src/test/java/org/testcontainers/junit/BaseDockerComposeTest.java +++ b/core/src/test/java/org/testcontainers/junit/BaseDockerComposeTest.java @@ -1,11 +1,11 @@ package org.testcontainers.junit; import com.github.dockerjava.api.model.Network; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.utility.TestEnvironment; @@ -28,13 +28,13 @@ public abstract class BaseDockerComposeTest { private List existingNetworks = new ArrayList<>(); - @BeforeClass + @BeforeAll public static void checkVersion() { - Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); + Assumptions.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); } @Test - public void simpleTest() { + void simpleTest() { Jedis jedis = new Jedis( getEnvironment().getServiceHost("redis_1", REDIS_PORT), getEnvironment().getServicePort("redis_1", REDIS_PORT) @@ -48,7 +48,7 @@ public void simpleTest() { } @Test - public void secondTest() { + void secondTest() { // used in manual checking for cleanup in between tests Jedis jedis = new Jedis( getEnvironment().getServiceHost("redis_1", REDIS_PORT), @@ -64,12 +64,12 @@ public void secondTest() { // However, @Rule creates a separate DockerComposeContainer instance per test, so this just shouldn't happen } - @Before + @BeforeEach public void captureNetworks() { existingNetworks.addAll(findAllNetworks()); } - @After + @AfterEach public void verifyNoNetworks() { assertThat(findAllNetworks()).as("The networks").isEqualTo(existingNetworks); } diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerOverrideTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerOverrideTest.java index 453fe9207ad..8e5651903f6 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerOverrideTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerOverrideTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; import com.github.dockerjava.api.command.InspectContainerResponse; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.containers.ContainerState; @@ -9,14 +9,14 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ComposeContainerOverrideTest { +class ComposeContainerOverrideTest { private static final File BASE = new File("src/test/resources/compose-override/compose.yml"); private static final File OVERRIDE = new File("src/test/resources/compose-override/compose-override.yml"); @Test - public void readEnvironment() { + void readEnvironment() { try (ComposeContainer compose = new ComposeContainer(BASE).withExposedService("redis", 6379)) { compose.start(); InspectContainerResponse container = compose @@ -28,7 +28,7 @@ public void readEnvironment() { } @Test - public void resetEnvironment() { + void resetEnvironment() { try (ComposeContainer compose = new ComposeContainer(BASE, OVERRIDE).withExposedService("redis", 6379)) { compose.start(); InspectContainerResponse container = compose diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerPortViaEnvTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerPortViaEnvTest.java index b27f4b080da..dfe51acbebb 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerPortViaEnvTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerPortViaEnvTest.java @@ -1,19 +1,23 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.ComposeContainer; import java.io.File; -public class ComposeContainerPortViaEnvTest extends BaseComposeTest { +class ComposeContainerPortViaEnvTest extends BaseComposeTest { - @Rule + @AutoClose public ComposeContainer environment = new ComposeContainer( new File("src/test/resources/v2-compose-test-port-via-env.yml") ) .withExposedService("redis-1", REDIS_PORT) .withEnv("REDIS_PORT", String.valueOf(REDIS_PORT)); + ComposeContainerPortViaEnvTest() { + this.environment.start(); + } + @Override protected ComposeContainer getEnvironment() { return environment; diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerScalingTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerScalingTest.java index 83bc894b516..7614b49e303 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerScalingTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerScalingTest.java @@ -1,10 +1,10 @@ package org.testcontainers.junit; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.assertj.core.api.Assumptions; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.utility.TestEnvironment; import redis.clients.jedis.Jedis; @@ -13,18 +13,18 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ComposeContainerScalingTest { +class ComposeContainerScalingTest { private static final int REDIS_PORT = 6379; private Jedis[] clients = new Jedis[3]; - @BeforeClass + @BeforeAll public static void checkVersion() { - Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); + Assumptions.assumeThat(TestEnvironment.dockerApiAtLeast("1.22")).isTrue(); } - @Rule + @AutoClose public ComposeContainer environment = new ComposeContainer( new File("src/test/resources/composev2/scaled-compose-test.yml") ) @@ -33,7 +33,11 @@ public static void checkVersion() { .withExposedService("redis-2", REDIS_PORT) // explicit service index .withExposedService("redis", 3, REDIS_PORT); // explicit service index via parameter - @Before + ComposeContainerScalingTest() { + environment.start(); + } + + @BeforeEach public void setupClients() { for (int i = 0; i < 3; i++) { String name = String.format("redis-%d", i + 1); @@ -44,7 +48,7 @@ public void setupClients() { } @Test - public void simpleTest() { + void simpleTest() { for (int i = 0; i < 3; i++) { clients[i].incr("somekey"); diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerTest.java index 39c7ff2baf5..2d87cd3aa49 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerTest.java @@ -1,7 +1,6 @@ package org.testcontainers.junit; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.containers.ContainerState; import org.testcontainers.containers.DockerComposeContainer; @@ -15,9 +14,8 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ComposeContainerTest extends BaseComposeTest { +class ComposeContainerTest extends BaseComposeTest { - @Rule // composeContainerConstructor { public ComposeContainer environment = new ComposeContainer( new File("src/test/resources/composev2/compose-test.yml") @@ -27,13 +25,17 @@ public class ComposeContainerTest extends BaseComposeTest { // } + ComposeContainerTest() { + environment.start(); + } + @Override protected ComposeContainer getEnvironment() { return environment; } @Test - public void testGetServiceHostAndPort() { + void testGetServiceHostAndPort() { // getServiceHostAndPort { String serviceHost = environment.getServiceHost("redis-1", REDIS_PORT); int serviceWithInstancePort = environment.getServicePort("redis-1", REDIS_PORT); @@ -48,7 +50,7 @@ public void testGetServiceHostAndPort() { } @Test - public void shouldRetrieveContainerByServiceName() { + void shouldRetrieveContainerByServiceName() { String existingServiceName = "db-1"; Optional result = environment.getContainerByServiceName(existingServiceName); assertThat(result) @@ -60,7 +62,7 @@ public void shouldRetrieveContainerByServiceName() { } @Test - public void shouldReturnEmptyResultOnNoneExistingService() { + void shouldReturnEmptyResultOnNoneExistingService() { String notExistingServiceName = "db-256"; Optional result = environment.getContainerByServiceName(notExistingServiceName); assertThat(result) @@ -69,7 +71,7 @@ public void shouldReturnEmptyResultOnNoneExistingService() { } @Test - public void shouldCreateContainerWhenFileNotPrefixedWithPath() throws IOException { + void shouldCreateContainerWhenFileNotPrefixedWithPath() throws IOException { String validYaml = "version: '2.2'\n" + "services:\n" + diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerVolumeRemovalTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerVolumeRemovalTest.java index 65cc7b92aa5..1898f5d580b 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerVolumeRemovalTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerVolumeRemovalTest.java @@ -1,8 +1,8 @@ package org.testcontainers.junit; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.ComposeContainer; @@ -15,35 +15,22 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -@RunWith(Parameterized.class) -public class ComposeContainerVolumeRemovalTest { +class ComposeContainerVolumeRemovalTest { - public ComposeContainerVolumeRemovalTest( - final boolean removeVolumes, - final boolean shouldVolumesBePresentAfterRunning - ) { - this.removeVolumes = removeVolumes; - this.shouldVolumesBePresentAfterRunning = shouldVolumesBePresentAfterRunning; + public static Stream params() { + return Stream.of(Arguments.of(true, false), Arguments.of(false, true)); } - public final boolean removeVolumes; - - public final boolean shouldVolumesBePresentAfterRunning; - - @Parameterized.Parameters(name = "removeVolumes = {0}") - public static Object[][] params() { - return new Object[][] { { true, false }, { false, true } }; - } - - @Test - public void performTest() { + @ParameterizedTest + @MethodSource("params") + void performTest(boolean removeVolumes, boolean shouldVolumesBePresentAfterRunning) { final File composeFile = new File("src/test/resources/v2-compose-test.yml"); final AtomicReference volumeName = new AtomicReference<>(""); try ( ComposeContainer environment = new ComposeContainer(composeFile) .withExposedService("redis", 6379) - .withRemoveVolumes(this.removeVolumes) + .withRemoveVolumes(removeVolumes) .withRemoveImages(ComposeContainer.RemoveImages.ALL) ) { environment.start(); @@ -58,7 +45,7 @@ public void performTest() { final boolean isVolumePresentAfterRunning = isVolumePresent(volumeName.get()); assertThat(isVolumePresentAfterRunning) .as("the container volume is present after running") - .isEqualTo(this.shouldVolumesBePresentAfterRunning); + .isEqualTo(shouldVolumesBePresentAfterRunning); }); } diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithBuildTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithBuildTest.java index 7d13f72e300..589766f9184 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithBuildTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithBuildTest.java @@ -1,9 +1,9 @@ package org.testcontainers.junit; import com.github.dockerjava.api.model.Container; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.ComposeContainer; @@ -15,36 +15,23 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class ComposeContainerWithBuildTest { +class ComposeContainerWithBuildTest { - public ComposeContainerWithBuildTest( - final ComposeContainer.RemoveImages removeMode, - final boolean shouldBuiltImageBePresentAfterRunning, - final boolean shouldPulledImageBePresentAfterRunning - ) { - this.removeMode = removeMode; - this.shouldBuiltImageBePresentAfterRunning = shouldBuiltImageBePresentAfterRunning; - this.shouldPulledImageBePresentAfterRunning = shouldPulledImageBePresentAfterRunning; - } - - public final ComposeContainer.RemoveImages removeMode; - - public final boolean shouldBuiltImageBePresentAfterRunning; - - public final boolean shouldPulledImageBePresentAfterRunning; - - @Parameterized.Parameters(name = "removeMode = {0}") - public static Object[][] params() { - return new Object[][] { - { null, true, true }, - { ComposeContainer.RemoveImages.LOCAL, false, true }, - { ComposeContainer.RemoveImages.ALL, false, false }, - }; + public static Stream params() { + return Stream.of( + Arguments.of(null, true, true), + Arguments.of(ComposeContainer.RemoveImages.LOCAL, false, true), + Arguments.of(ComposeContainer.RemoveImages.ALL, false, false) + ); } - @Test - public void performTest() { + @ParameterizedTest + @MethodSource("params") + void performTest( + ComposeContainer.RemoveImages removeMode, + boolean shouldBuiltImageBePresentAfterRunning, + boolean shouldPulledImageBePresentAfterRunning + ) { final File composeFile = new File("src/test/resources/compose-v2-build-test/docker-compose.yml"); final AtomicReference builtImageName = new AtomicReference<>(""); diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithCopyFilesTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithCopyFilesTest.java index 2b1e2cd4081..33dc092cc51 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithCopyFilesTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithCopyFilesTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; import io.restassured.RestAssured; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.containers.ContainerLaunchException; @@ -11,10 +11,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -public class ComposeContainerWithCopyFilesTest { +class ComposeContainerWithCopyFilesTest { @Test - public void testShouldCopyAllFilesByDefault() throws IOException { + void testShouldCopyAllFilesByDefault() throws IOException { try ( ComposeContainer environment = new ComposeContainer( new File("src/test/resources/compose-file-copy-inclusions/compose.yml") @@ -29,7 +29,7 @@ public void testShouldCopyAllFilesByDefault() throws IOException { } @Test - public void testWithFileCopyInclusionUsingFilePath() throws IOException { + void testWithFileCopyInclusionUsingFilePath() throws IOException { try ( ComposeContainer environment = new ComposeContainer( new File("src/test/resources/compose-file-copy-inclusions/compose-root-only.yml") @@ -47,7 +47,7 @@ public void testWithFileCopyInclusionUsingFilePath() throws IOException { } @Test - public void testWithFileCopyInclusionUsingDirectoryPath() throws IOException { + void testWithFileCopyInclusionUsingDirectoryPath() throws IOException { try ( // composeContainerWithCopyFiles { ComposeContainer environment = new ComposeContainer( @@ -66,7 +66,7 @@ public void testWithFileCopyInclusionUsingDirectoryPath() throws IOException { } @Test - public void testShouldNotBeAbleToStartIfNeededEnvFileIsNotCopied() { + void testShouldNotBeAbleToStartIfNeededEnvFileIsNotCopied() { try ( ComposeContainer environment = new ComposeContainer( new File("src/test/resources/compose-file-copy-inclusions/compose-test-only.yml") diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithOptionsTest.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithOptionsTest.java index 9a6c581eb3b..e8bca173a54 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithOptionsTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithOptionsTest.java @@ -2,92 +2,65 @@ import com.google.common.collect.ImmutableSet; import org.assertj.core.api.Assumptions; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.utility.CommandLine; import java.io.File; import java.util.Set; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; /** * Tests the options associated with the docker-compose command. */ -@RunWith(Parameterized.class) -public class ComposeContainerWithOptionsTest { +class ComposeContainerWithOptionsTest { - public ComposeContainerWithOptionsTest( - final File composeFile, - final boolean localMode, - final Set options, - final boolean expectError - ) { - this.composeFile = composeFile; - this.localMode = localMode; - this.options = options; - this.expectError = expectError; - } - - private final File composeFile; - - private final boolean localMode; - - private final Set options; - - private final boolean expectError; - - @Parameterized.Parameters( - name = "docker-compose test [compose file: {0}, local: {1}, options: {2}, expected result: {3}]" - ) - public static Object[][] params() { - return new Object[][] { + public static Stream params() { + return Stream.of( // Test the happy day case. THe compatibility option should be accepted by docker-compose. - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), false, ImmutableSet.of("--compatibility"), - false, - }, + false + ), // Test with flags absent. Docker compose will warn but continue, ignoring the deploy block. - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), false, ImmutableSet.of(""), - false, - }, + false + ), // Test with a bad option. Compose will complain. - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), false, ImmutableSet.of("--bad-option"), - true, - }, + true + ), // Local compose - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), true, ImmutableSet.of("--compatibility"), - false, - }, - }; + false + ) + ); } - @Before - public void setUp() { - if (this.localMode) { + @ParameterizedTest(name = "docker-compose test [compose file: {0}, local: {1}, options: {2}, expected result: {3}]") + @MethodSource("params") + void performTest(File composeFile, boolean localMode, Set options, boolean expectError) { + if (localMode) { Assumptions .assumeThat(CommandLine.executableExists(ComposeContainer.COMPOSE_EXECUTABLE)) .as("docker executable exists") .isTrue(); } - } - - @Test - public void performTest() { try ( ComposeContainer environment = new ComposeContainer(composeFile) .withOptions(options.stream().toArray(String[]::new)) diff --git a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithWaitStrategies.java b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithWaitStrategies.java index 1304413dce5..82a1a5e57ad 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeContainerWithWaitStrategies.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeContainerWithWaitStrategies.java @@ -1,6 +1,6 @@ package org.testcontainers.junit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.containers.wait.strategy.Wait; @@ -9,12 +9,12 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ComposeContainerWithWaitStrategies { +class ComposeContainerWithWaitStrategies { private static final int REDIS_PORT = 6379; @Test - public void testComposeContainerConstructor() { + void testComposeContainerConstructor() { try ( // composeContainerWithCombinedWaitStrategies { ComposeContainer compose = new ComposeContainer(new File("src/test/resources/composev2/compose-test.yml")) @@ -28,7 +28,7 @@ public void testComposeContainerConstructor() { } @Test - public void testComposeContainerWaitForPortWithTimeout() { + void testComposeContainerWaitForPortWithTimeout() { try ( // composeContainerWaitForPortWithTimeout { ComposeContainer compose = new ComposeContainer(new File("src/test/resources/composev2/compose-test.yml")) diff --git a/core/src/test/java/org/testcontainers/junit/ComposeErrorHandlingTest.java b/core/src/test/java/org/testcontainers/junit/ComposeErrorHandlingTest.java index 496ede74497..a5e8e77c12f 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeErrorHandlingTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeErrorHandlingTest.java @@ -1,6 +1,6 @@ package org.testcontainers.junit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import java.io.File; @@ -8,10 +8,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -public class ComposeErrorHandlingTest { +class ComposeErrorHandlingTest { @Test - public void simpleTest() { + void simpleTest() { assertThat( catchThrowable(() -> { ComposeContainer environment = new ComposeContainer(new File("src/test/resources/invalid-compose.yml")) diff --git a/core/src/test/java/org/testcontainers/junit/ComposePassthroughTest.java b/core/src/test/java/org/testcontainers/junit/ComposePassthroughTest.java index d1724cb1e70..97ea43d38c9 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposePassthroughTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposePassthroughTest.java @@ -1,9 +1,9 @@ package org.testcontainers.junit; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.assertj.core.api.Assumptions; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.containers.ContainerState; import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy; @@ -15,24 +15,28 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ComposePassthroughTest { +class ComposePassthroughTest { private final TestWaitStrategy waitStrategy = new TestWaitStrategy(); - @BeforeClass + @BeforeAll public static void checkVersion() { - Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); + Assumptions.assumeThat(TestEnvironment.dockerApiAtLeast("1.22")).isTrue(); } - @Rule + @AutoClose public ComposeContainer compose = new ComposeContainer( new File("src/test/resources/v2-compose-test-passthrough.yml") ) .withEnv("foo", "bar") .withExposedService("alpine-1", 3000, waitStrategy); + ComposePassthroughTest() { + compose.start(); + } + @Test - public void testContainerInstanceProperties() { + void testContainerInstanceProperties() { final ContainerState container = waitStrategy.getContainer(); //check environment variable was set diff --git a/core/src/test/java/org/testcontainers/junit/ComposeWaitStrategyTest.java b/core/src/test/java/org/testcontainers/junit/ComposeWaitStrategyTest.java index a77f80d227e..73553f70fdf 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeWaitStrategyTest.java @@ -1,9 +1,8 @@ package org.testcontainers.junit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Description; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.testcontainers.containers.ComposeContainer; import org.testcontainers.containers.wait.strategy.Wait; @@ -16,61 +15,61 @@ import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.fail; -public class ComposeWaitStrategyTest { +class ComposeWaitStrategyTest { private static final int REDIS_PORT = 6379; private ComposeContainer environment; - @Before + @BeforeEach public final void setUp() { environment = new ComposeContainer(new File("src/test/resources/composev2/compose-test.yml")); } - @After + @AfterEach public final void cleanUp() { environment.stop(); } @Test - public void testWaitOnListeningPort() { + void testWaitOnListeningPort() { environment.withExposedService("redis-1", REDIS_PORT, Wait.forListeningPort()); try { - environment.starting(Description.createTestDescription(Object.class, "name")); + environment.start(); } catch (RuntimeException e) { fail("Docker compose should start after waiting for listening port with failed with: " + e); } } @Test - public void testWaitOnMultipleStrategiesPassing() { + void testWaitOnMultipleStrategiesPassing() { environment .withExposedService("redis-1", REDIS_PORT, Wait.forListeningPort()) .withExposedService("db-1", 3306, Wait.forLogMessage(".*ready for connections.*\\s", 1)) .withTailChildContainers(true); try { - environment.starting(Description.createTestDescription(Object.class, "name")); + environment.start(); } catch (RuntimeException e) { fail("Docker compose should start after waiting for listening port with failed with: " + e); } } @Test - public void testWaitingFails() { + void testWaitingFails() { environment.withExposedService( "redis-1", REDIS_PORT, Wait.forHttp("/test").withStartupTimeout(Duration.ofSeconds(10)) ); - assertThat(catchThrowable(() -> environment.starting(Description.createTestDescription(Object.class, "name")))) + assertThat(catchThrowable(() -> environment.start())) .as("waiting on an invalid http path times out") .isInstanceOf(RuntimeException.class); } @Test - public void testWaitOnOneOfMultipleStrategiesFailing() { + void testWaitOnOneOfMultipleStrategiesFailing() { environment .withExposedService( "redis-1", @@ -83,13 +82,13 @@ public void testWaitOnOneOfMultipleStrategiesFailing() { ) .withTailChildContainers(true); - assertThat(catchThrowable(() -> environment.starting(Description.createTestDescription(Object.class, "name")))) + assertThat(catchThrowable(() -> environment.start())) .as("waiting on one failing strategy to time out") .isInstanceOf(RuntimeException.class); } @Test - public void testWaitingForNonexistentServices() { + void testWaitingForNonexistentServices() { String existentServiceName = "db-1"; String nonexistentServiceName1 = "some-nonexistent_service-1"; String nonexistentServiceName2 = "some-nonexistent_service-2"; diff --git a/core/src/test/java/org/testcontainers/junit/ComposeWithIdentifierTest.java b/core/src/test/java/org/testcontainers/junit/ComposeWithIdentifierTest.java index f94449bb39f..71d80918d7c 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeWithIdentifierTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeWithIdentifierTest.java @@ -1,19 +1,23 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.ComposeContainer; import java.io.File; -public class ComposeWithIdentifierTest extends BaseComposeTest { +class ComposeWithIdentifierTest extends BaseComposeTest { - @Rule + @AutoClose public ComposeContainer environment = new ComposeContainer( "TEST", new File("src/test/resources/v2-compose-test.yml") ) .withExposedService("redis-1", REDIS_PORT); + ComposeWithIdentifierTest() { + environment.start(); + } + @Override protected ComposeContainer getEnvironment() { return this.environment; diff --git a/core/src/test/java/org/testcontainers/junit/ComposeWithNetworkTest.java b/core/src/test/java/org/testcontainers/junit/ComposeWithNetworkTest.java index 3ce63b2a5fe..cfda1971600 100644 --- a/core/src/test/java/org/testcontainers/junit/ComposeWithNetworkTest.java +++ b/core/src/test/java/org/testcontainers/junit/ComposeWithNetworkTest.java @@ -1,18 +1,22 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.ComposeContainer; import java.io.File; -public class ComposeWithNetworkTest extends BaseComposeTest { +class ComposeWithNetworkTest extends BaseComposeTest { - @Rule + @AutoClose public ComposeContainer environment = new ComposeContainer( new File("src/test/resources/v2-compose-test-with-network.yml") ) .withExposedService("redis-1", REDIS_PORT); + ComposeWithNetworkTest() { + environment.start(); + } + @Override protected ComposeContainer getEnvironment() { return environment; diff --git a/core/src/test/java/org/testcontainers/junit/CopyFileToContainerTest.java b/core/src/test/java/org/testcontainers/junit/CopyFileToContainerTest.java index 1aa017d6894..1acac36e6ad 100644 --- a/core/src/test/java/org/testcontainers/junit/CopyFileToContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/CopyFileToContainerTest.java @@ -2,8 +2,8 @@ import com.google.common.io.Files; import com.google.common.io.Resources; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.GenericContainer; @@ -16,7 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class CopyFileToContainerTest { +class CopyFileToContainerTest { private static String destinationOnHost; @@ -24,13 +24,13 @@ public class CopyFileToContainerTest { private static String fileName = "test-resource.txt"; - @Before + @BeforeEach public void setup() throws IOException { destinationOnHost = File.createTempFile("testcontainers", null).getAbsolutePath(); } @Test - public void checkFileCopied() throws IOException, InterruptedException { + void checkFileCopied() throws IOException, InterruptedException { try ( // copyToContainer { GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) @@ -55,7 +55,7 @@ public void checkFileCopied() throws IOException, InterruptedException { } @Test - public void shouldUseCopyForReadOnlyClasspathResources() throws Exception { + void shouldUseCopyForReadOnlyClasspathResources() throws Exception { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withCommand("sleep", "3000") @@ -68,7 +68,7 @@ public void shouldUseCopyForReadOnlyClasspathResources() throws Exception { } @Test - public void shouldUseCopyOnlyWithReadOnlyClasspathResources() { + void shouldUseCopyOnlyWithReadOnlyClasspathResources() { String resource = "/test_copy_to_container.txt"; GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withClasspathResourceMapping(resource, "/readOnly", BindMode.READ_ONLY) @@ -82,7 +82,7 @@ public void shouldUseCopyOnlyWithReadOnlyClasspathResources() { } @Test - public void shouldCreateFoldersStructureWithCopy() throws Exception { + void shouldCreateFoldersStructureWithCopy() throws Exception { String resource = "/test_copy_to_container.txt"; try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) diff --git a/core/src/test/java/org/testcontainers/junit/DependenciesTest.java b/core/src/test/java/org/testcontainers/junit/DependenciesTest.java index effa9b06447..cbb305c30f8 100644 --- a/core/src/test/java/org/testcontainers/junit/DependenciesTest.java +++ b/core/src/test/java/org/testcontainers/junit/DependenciesTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; import lombok.Getter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; @@ -18,10 +18,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class DependenciesTest { +class DependenciesTest { @Test - public void shouldWorkWithSimpleDependency() { + void shouldWorkWithSimpleDependency() { InvocationCountingStartable startable = new InvocationCountingStartable(); try ( @@ -37,7 +37,7 @@ public void shouldWorkWithSimpleDependency() { } @Test - public void shouldWorkWithMultipleDependencies() { + void shouldWorkWithMultipleDependencies() { InvocationCountingStartable startable1 = new InvocationCountingStartable(); InvocationCountingStartable startable2 = new InvocationCountingStartable(); @@ -54,7 +54,7 @@ public void shouldWorkWithMultipleDependencies() { } @Test - public void shouldStartEveryTime() { + void shouldStartEveryTime() { InvocationCountingStartable startable = new InvocationCountingStartable(); try ( @@ -76,7 +76,7 @@ public void shouldStartEveryTime() { } @Test - public void shouldStartTransitiveDependencies() { + void shouldStartTransitiveDependencies() { InvocationCountingStartable transitiveOfTransitiveStartable = new InvocationCountingStartable(); InvocationCountingStartable transitiveStartable = new InvocationCountingStartable(); transitiveStartable.getDependencies().add(transitiveOfTransitiveStartable); @@ -101,7 +101,7 @@ public void shouldStartTransitiveDependencies() { } @Test - public void shouldHandleDiamondDependencies() throws Exception { + void shouldHandleDiamondDependencies() throws Exception { InvocationCountingStartable a = new InvocationCountingStartable(); InvocationCountingStartable b = new InvocationCountingStartable(); InvocationCountingStartable c = new InvocationCountingStartable(); @@ -124,7 +124,7 @@ public void shouldHandleDiamondDependencies() throws Exception { } @Test - public void shouldHandleParallelStream() throws Exception { + void shouldHandleParallelStream() throws Exception { List startables = Stream .generate(InvocationCountingStartable::new) .limit(10) diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerPortViaEnvTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerPortViaEnvTest.java index 849e2a8e6a6..0cf523836a5 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerPortViaEnvTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerPortViaEnvTest.java @@ -1,19 +1,23 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; -public class DockerComposeContainerPortViaEnvTest extends BaseDockerComposeTest { +class DockerComposeContainerPortViaEnvTest extends BaseDockerComposeTest { - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/v2-compose-test-port-via-env.yml") ) .withExposedService("redis_1", REDIS_PORT) .withEnv("REDIS_PORT", String.valueOf(REDIS_PORT)); + DockerComposeContainerPortViaEnvTest() { + environment.start(); + } + @Override protected DockerComposeContainer getEnvironment() { return environment; diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerScalingTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerScalingTest.java index 5571e42dcf7..90256bb0f37 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerScalingTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerScalingTest.java @@ -1,10 +1,10 @@ package org.testcontainers.junit; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.assertj.core.api.Assumptions; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.utility.TestEnvironment; import redis.clients.jedis.Jedis; @@ -16,18 +16,18 @@ /** * Created by rnorth on 08/08/2015. */ -public class DockerComposeContainerScalingTest { +class DockerComposeContainerScalingTest { private static final int REDIS_PORT = 6379; private Jedis[] clients = new Jedis[3]; - @BeforeClass + @BeforeAll public static void checkVersion() { - Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); + Assumptions.assumeThat(TestEnvironment.dockerApiAtLeast("1.22")).isTrue(); } - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/scaled-compose-test.yml") ) @@ -36,8 +36,9 @@ public static void checkVersion() { .withExposedService("redis_2", REDIS_PORT) // explicit service index .withExposedService("redis", 3, REDIS_PORT); // explicit service index via parameter - @Before + @BeforeEach public void setupClients() { + this.environment.start(); for (int i = 0; i < 3; i++) { String name = String.format("redis_%d", i + 1); @@ -47,7 +48,7 @@ public void setupClients() { } @Test - public void simpleTest() { + void simpleTest() { for (int i = 0; i < 3; i++) { clients[i].incr("somekey"); diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerTest.java index 96989af90a4..568eaae53cf 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ContainerState; import org.testcontainers.containers.DockerComposeContainer; @@ -17,22 +17,26 @@ /** * Created by rnorth on 08/08/2015. */ -public class DockerComposeContainerTest extends BaseDockerComposeTest { +class DockerComposeContainerTest extends BaseDockerComposeTest { - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/compose-test.yml") ) .withExposedService("redis_1", REDIS_PORT) .withExposedService("db_1", 3306); + DockerComposeContainerTest() { + environment.start(); + } + @Override protected DockerComposeContainer getEnvironment() { return environment; } @Test - public void testGetServicePort() { + void testGetServicePort() { int serviceWithInstancePort = environment.getServicePort("redis_1", REDIS_PORT); assertThat(serviceWithInstancePort).as("Port is set for service with instance number").isNotNull(); int serviceWithoutInstancePort = environment.getServicePort("redis", REDIS_PORT); @@ -41,7 +45,7 @@ public void testGetServicePort() { } @Test - public void shouldRetrieveContainerByServiceName() { + void shouldRetrieveContainerByServiceName() { String existingServiceName = "db_1"; Optional result = environment.getContainerByServiceName(existingServiceName); @@ -54,7 +58,7 @@ public void shouldRetrieveContainerByServiceName() { } @Test - public void shouldRetrieveContainerByServiceNameWithoutNumberedSuffix() { + void shouldRetrieveContainerByServiceNameWithoutNumberedSuffix() { String existingServiceName = "db"; Optional result = environment.getContainerByServiceName(existingServiceName); @@ -67,7 +71,7 @@ public void shouldRetrieveContainerByServiceNameWithoutNumberedSuffix() { } @Test - public void shouldReturnEmptyResultOnNoneExistingService() { + void shouldReturnEmptyResultOnNoneExistingService() { String notExistingServiceName = "db_256"; Optional result = environment.getContainerByServiceName(notExistingServiceName); assertThat(result) @@ -76,7 +80,7 @@ public void shouldReturnEmptyResultOnNoneExistingService() { } @Test - public void shouldCreateContainerWhenFileNotPrefixedWithPath() throws IOException { + void shouldCreateContainerWhenFileNotPrefixedWithPath() throws IOException { String validYaml = "version: '2.2'\n" + "services:\n" + diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerVolumeRemovalTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerVolumeRemovalTest.java index 764000a3cae..557cc7e27db 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerVolumeRemovalTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerVolumeRemovalTest.java @@ -1,8 +1,7 @@ package org.testcontainers.junit; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.DockerComposeContainer; @@ -15,35 +14,22 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -@RunWith(Parameterized.class) -public class DockerComposeContainerVolumeRemovalTest { +class DockerComposeContainerVolumeRemovalTest { - public DockerComposeContainerVolumeRemovalTest( - final boolean removeVolumes, - final boolean shouldVolumesBePresentAfterRunning - ) { - this.removeVolumes = removeVolumes; - this.shouldVolumesBePresentAfterRunning = shouldVolumesBePresentAfterRunning; - } - - public final boolean removeVolumes; - - public final boolean shouldVolumesBePresentAfterRunning; - - @Parameterized.Parameters(name = "removeVolumes = {0}") public static Object[][] params() { return new Object[][] { { true, false }, { false, true } }; } - @Test - public void performTest() { + @ParameterizedTest + @MethodSource("params") + void performTest(boolean removeVolumes, boolean shouldVolumesBePresentAfterRunning) { final File composeFile = new File("src/test/resources/compose-test.yml"); final AtomicReference volumeName = new AtomicReference<>(""); try ( DockerComposeContainer environment = new DockerComposeContainer<>(composeFile) .withExposedService("redis", 6379) - .withRemoveVolumes(this.removeVolumes) + .withRemoveVolumes(removeVolumes) .withRemoveImages(DockerComposeContainer.RemoveImages.ALL) ) { environment.start(); @@ -58,7 +44,7 @@ public void performTest() { final boolean isVolumePresentAfterRunning = isVolumePresent(volumeName.get()); assertThat(isVolumePresentAfterRunning) .as("the container volume is present after running") - .isEqualTo(this.shouldVolumesBePresentAfterRunning); + .isEqualTo(shouldVolumesBePresentAfterRunning); }); } diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithBuildTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithBuildTest.java index ea7e35689d0..8f8da1e6450 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithBuildTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithBuildTest.java @@ -1,9 +1,9 @@ package org.testcontainers.junit; import com.github.dockerjava.api.model.Container; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.DockerComposeContainer; @@ -15,36 +15,23 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class DockerComposeContainerWithBuildTest { +class DockerComposeContainerWithBuildTest { - public DockerComposeContainerWithBuildTest( - final DockerComposeContainer.RemoveImages removeMode, - final boolean shouldBuiltImageBePresentAfterRunning, - final boolean shouldPulledImageBePresentAfterRunning - ) { - this.removeMode = removeMode; - this.shouldBuiltImageBePresentAfterRunning = shouldBuiltImageBePresentAfterRunning; - this.shouldPulledImageBePresentAfterRunning = shouldPulledImageBePresentAfterRunning; - } - - public final DockerComposeContainer.RemoveImages removeMode; - - public final boolean shouldBuiltImageBePresentAfterRunning; - - public final boolean shouldPulledImageBePresentAfterRunning; - - @Parameterized.Parameters(name = "removeMode = {0}") - public static Object[][] params() { - return new Object[][] { - { null, true, true }, - { DockerComposeContainer.RemoveImages.LOCAL, false, true }, - { DockerComposeContainer.RemoveImages.ALL, false, false }, - }; + public static Stream params() { + return Stream.of( + Arguments.of(null, true, true), + Arguments.of(DockerComposeContainer.RemoveImages.LOCAL, false, true), + Arguments.of(DockerComposeContainer.RemoveImages.ALL, false, false) + ); } - @Test - public void performTest() { + @ParameterizedTest + @MethodSource("params") + void performTest( + DockerComposeContainer.RemoveImages removeMode, + boolean shouldBuiltImageBePresentAfterRunning, + boolean shouldPulledImageBePresentAfterRunning + ) { final File composeFile = new File("src/test/resources/compose-build-test/docker-compose.yml"); final AtomicReference builtImageName = new AtomicReference<>(""); diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithCopyFilesTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithCopyFilesTest.java index 46dd4c65b3c..69853a4e0d3 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithCopyFilesTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithCopyFilesTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; import io.restassured.RestAssured; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; @@ -9,10 +9,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class DockerComposeContainerWithCopyFilesTest { +class DockerComposeContainerWithCopyFilesTest { @Test - public void testShouldCopyAllFilesByDefault() throws IOException { + void testShouldCopyAllFilesByDefault() throws IOException { try ( DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/compose-file-copy-inclusions/compose.yml") @@ -27,7 +27,7 @@ public void testShouldCopyAllFilesByDefault() throws IOException { } @Test - public void testWithFileCopyInclusionUsingFilePath() throws IOException { + void testWithFileCopyInclusionUsingFilePath() throws IOException { try ( DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/compose-file-copy-inclusions/compose-root-only.yml") @@ -45,7 +45,7 @@ public void testWithFileCopyInclusionUsingFilePath() throws IOException { } @Test - public void testWithFileCopyInclusionUsingDirectoryPath() throws IOException { + void testWithFileCopyInclusionUsingDirectoryPath() throws IOException { try ( DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/compose-file-copy-inclusions/compose-test-only.yml") diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithOptionsTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithOptionsTest.java index ae5dbc1d0b4..d4b684ef010 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithOptionsTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeContainerWithOptionsTest.java @@ -2,83 +2,60 @@ import com.google.common.collect.ImmutableSet; import org.assertj.core.api.Assumptions; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.utility.CommandLine; import java.io.File; import java.util.Set; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; /** * Tests the options associated with the docker-compose command. */ -@RunWith(Parameterized.class) -public class DockerComposeContainerWithOptionsTest { +class DockerComposeContainerWithOptionsTest { - public DockerComposeContainerWithOptionsTest( - final File composeFile, - final boolean localMode, - final Set options, - final boolean expectError - ) { - this.composeFile = composeFile; - this.localMode = localMode; - this.options = options; - this.expectError = expectError; - } - - private final File composeFile; - - private final boolean localMode; - - private final Set options; - - private final boolean expectError; - - @Parameterized.Parameters( - name = "docker-compose test [compose file: {0}, local: {1}, options: {2}, expected result: {3}]" - ) - public static Object[][] params() { - return new Object[][] { + public static Stream params() { + return Stream.of( // Test the happy day case. THe compatibility option should be accepted by docker-compose. - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), false, ImmutableSet.of("--compatibility"), - false, - }, + false + ), // Test with flags absent. Docker compose will warn but continue, ignoring the deploy block. - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), false, ImmutableSet.of(""), - false, - }, + false + ), // Test with a bad option. Compose will complain. - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), false, ImmutableSet.of("--bad-option"), - true, - }, + true + ), // Local compose - { + Arguments.of( new File("src/test/resources/compose-options-test/with-deploy-block.yml"), true, ImmutableSet.of("--compatibility"), - false, - }, - }; + false + ) + ); } - @Before - public void setUp() { - if (this.localMode) { + @ParameterizedTest(name = "docker-compose test [compose file: {0}, local: {1}, options: {2}, expected result: {3}]") + @MethodSource("params") + void performTest(File composeFile, boolean localMode, Set options, boolean expectError) { + if (localMode) { Assumptions .assumeThat(CommandLine.executableExists(DockerComposeContainer.COMPOSE_EXECUTABLE)) .as("docker-compose executable exists") @@ -87,10 +64,6 @@ public void setUp() { .assumeThat(CommandLine.runShellCommand("docker-compose", "--version")) .doesNotStartWith("Docker Compose version v2"); } - } - - @Test - public void performTest() { try ( DockerComposeContainer environment = new DockerComposeContainer<>(composeFile) .withOptions(options.stream().toArray(String[]::new)) diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeErrorHandlingTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeErrorHandlingTest.java index 63383bb7175..9d0f4a19f1e 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeErrorHandlingTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeErrorHandlingTest.java @@ -1,6 +1,6 @@ package org.testcontainers.junit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; @@ -8,10 +8,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -public class DockerComposeErrorHandlingTest { +class DockerComposeErrorHandlingTest { @Test - public void simpleTest() { + void simpleTest() { assertThat( catchThrowable(() -> { DockerComposeContainer environment = new DockerComposeContainer( diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeLocalImageTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeLocalImageTest.java index 69b674bca71..2c77092e1bd 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeLocalImageTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeLocalImageTest.java @@ -2,16 +2,16 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.core.command.PullImageResultCallback; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; -public class DockerComposeLocalImageTest { +class DockerComposeLocalImageTest { @Test - public void usesLocalImageEvenWhenPullFails() throws InterruptedException { + void usesLocalImageEvenWhenPullFails() throws InterruptedException { tagImage("redis:6-alpine", "redis-local", "latest"); DockerComposeContainer composeContainer = new DockerComposeContainer( diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeLogConsumerTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeLogConsumerTest.java index 97e686a9b92..a712fb19664 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeLogConsumerTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeLogConsumerTest.java @@ -1,6 +1,6 @@ package org.testcontainers.junit; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.runner.Description; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.containers.output.OutputFrame.OutputType; @@ -10,10 +10,10 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -public class DockerComposeLogConsumerTest { +class DockerComposeLogConsumerTest { @Test - public void testLogConsumer() throws TimeoutException { + void testLogConsumer() throws TimeoutException { WaitingConsumer logConsumer = new WaitingConsumer(); DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/v2-compose-test.yml") diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposePassthroughTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposePassthroughTest.java index 10a26306248..0bc8ace7ab7 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposePassthroughTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposePassthroughTest.java @@ -1,9 +1,7 @@ package org.testcontainers.junit; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.assertj.core.api.Assumptions; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.ContainerState; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy; @@ -18,35 +16,34 @@ /** * Created by rnorth on 11/06/2016. */ -public class DockerComposePassthroughTest { - - private final TestWaitStrategy waitStrategy = new TestWaitStrategy(); - - @BeforeClass - public static void checkVersion() { - Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22")); - } - - @Rule - public DockerComposeContainer compose = new DockerComposeContainer( - new File("src/test/resources/v2-compose-test-passthrough.yml") - ) - .withEnv("foo", "bar") - .withExposedService("alpine_1", 3000, waitStrategy); +class DockerComposePassthroughTest { @Test - public void testContainerInstanceProperties() { - final ContainerState container = waitStrategy.getContainer(); - - //check environment variable was set - assertThat(Arrays.asList(Objects.requireNonNull(container.getContainerInfo().getConfig().getEnv()))) - .as("Environment variable set correctly") - .containsOnlyOnce("bar=bar"); - - //check other container properties - assertThat(container.getContainerId()).as("Container id is not null").isNotNull(); - assertThat(container.getMappedPort(3000)).as("Port mapped").isNotNull(); - assertThat(container.getExposedPorts()).containsExactly(3000); + void testContainerInstanceProperties() { + Assumptions.assumeThat(TestEnvironment.dockerApiAtLeast("1.22")).isTrue(); + + TestWaitStrategy waitStrategy = new TestWaitStrategy(); + try ( + DockerComposeContainer compose = new DockerComposeContainer( + new File("src/test/resources/v2-compose-test-passthrough.yml") + ) + .withEnv("foo", "bar") + .withExposedService("alpine_1", 3000, waitStrategy) + ) { + compose.start(); + + final ContainerState container = waitStrategy.getContainer(); + + //check environment variable was set + assertThat(Arrays.asList(Objects.requireNonNull(container.getContainerInfo().getConfig().getEnv()))) + .as("Environment variable set correctly") + .containsOnlyOnce("bar=bar"); + + //check other container properties + assertThat(container.getContainerId()).as("Container id is not null").isNotNull(); + assertThat(container.getMappedPort(3000)).as("Port mapped").isNotNull(); + assertThat(container.getExposedPorts()).containsExactly(3000); + } } /* diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeServiceTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeServiceTest.java index ccca85407f3..2496b7ee0bc 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeServiceTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeServiceTest.java @@ -1,34 +1,42 @@ package org.testcontainers.junit; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class DockerComposeServiceTest extends BaseDockerComposeTest { +class DockerComposeServiceTest extends BaseDockerComposeTest { - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/compose-test.yml") ) .withServices("redis") .withExposedService("redis_1", REDIS_PORT); + DockerComposeServiceTest() { + environment.start(); + } + @Override protected DockerComposeContainer getEnvironment() { return environment; } - @Test(expected = IllegalArgumentException.class) - public void testDbIsNotStarting() { - environment.getServicePort("db_1", 10001); + @Test + void testDbIsNotStarting() { + assertThatThrownBy(() -> { + environment.getServicePort("db_1", 10001); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test - public void testRedisIsStarting() { + void testRedisIsStarting() { assertThat(environment.getServicePort("redis_1", REDIS_PORT)).as("Redis server started").isNotNull(); } } diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatTest.java index f3dc2ee3cc8..c7b066b39b8 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatTest.java @@ -1,6 +1,6 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; @@ -8,14 +8,18 @@ /** * Created by rnorth on 21/05/2016. */ -public class DockerComposeV2FormatTest extends BaseDockerComposeTest { +class DockerComposeV2FormatTest extends BaseDockerComposeTest { - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/v2-compose-test.yml") ) .withExposedService("redis_1", REDIS_PORT); + DockerComposeV2FormatTest() { + environment.start(); + } + @Override protected DockerComposeContainer getEnvironment() { return environment; diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatWithIdentifierTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatWithIdentifierTest.java index 90c041b53b6..d8f4e57dbd9 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatWithIdentifierTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeV2FormatWithIdentifierTest.java @@ -1,19 +1,23 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; -public class DockerComposeV2FormatWithIdentifierTest extends BaseDockerComposeTest { +class DockerComposeV2FormatWithIdentifierTest extends BaseDockerComposeTest { - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( "TEST", new File("src/test/resources/v2-compose-test.yml") ) .withExposedService("redis_1", REDIS_PORT); + DockerComposeV2FormatWithIdentifierTest() { + environment.start(); + } + @Override protected DockerComposeContainer getEnvironment() { return this.environment; diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeV2WithNetworkTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeV2WithNetworkTest.java index b28dfc3ee51..bc95f0229b7 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeV2WithNetworkTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeV2WithNetworkTest.java @@ -1,18 +1,22 @@ package org.testcontainers.junit; -import org.junit.Rule; +import org.junit.jupiter.api.AutoClose; import org.testcontainers.containers.DockerComposeContainer; import java.io.File; -public class DockerComposeV2WithNetworkTest extends BaseDockerComposeTest { +class DockerComposeV2WithNetworkTest extends BaseDockerComposeTest { - @Rule + @AutoClose public DockerComposeContainer environment = new DockerComposeContainer( new File("src/test/resources/v2-compose-test-with-network.yml") ) .withExposedService("redis_1", REDIS_PORT); + DockerComposeV2WithNetworkTest() { + environment.start(); + } + @Override protected DockerComposeContainer getEnvironment() { return environment; diff --git a/core/src/test/java/org/testcontainers/junit/DockerComposeWaitStrategyTest.java b/core/src/test/java/org/testcontainers/junit/DockerComposeWaitStrategyTest.java index b110e776285..9f8c2c9ab49 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerComposeWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerComposeWaitStrategyTest.java @@ -1,9 +1,8 @@ package org.testcontainers.junit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.Description; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.containers.wait.strategy.Wait; @@ -16,61 +15,61 @@ import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.Assertions.fail; -public class DockerComposeWaitStrategyTest { +class DockerComposeWaitStrategyTest { private static final int REDIS_PORT = 6379; private DockerComposeContainer environment; - @Before + @BeforeEach public final void setUp() { environment = new DockerComposeContainer<>(new File("src/test/resources/compose-test.yml")); } - @After + @AfterEach public final void cleanUp() { environment.stop(); } @Test - public void testWaitOnListeningPort() { + void testWaitOnListeningPort() { environment.withExposedService("redis_1", REDIS_PORT, Wait.forListeningPort()); try { - environment.starting(Description.createTestDescription(Object.class, "name")); + environment.start(); } catch (RuntimeException e) { fail("Docker compose should start after waiting for listening port with failed with: " + e); } } @Test - public void testWaitOnMultipleStrategiesPassing() { + void testWaitOnMultipleStrategiesPassing() { environment .withExposedService("redis_1", REDIS_PORT, Wait.forListeningPort()) .withExposedService("db_1", 3306, Wait.forLogMessage(".*ready for connections.*\\s", 1)) .withTailChildContainers(true); try { - environment.starting(Description.createTestDescription(Object.class, "name")); + environment.start(); } catch (RuntimeException e) { fail("Docker compose should start after waiting for listening port with failed with: " + e); } } @Test - public void testWaitingFails() { + void testWaitingFails() { environment.withExposedService( "redis_1", REDIS_PORT, Wait.forHttp("/test").withStartupTimeout(Duration.ofSeconds(10)) ); - assertThat(catchThrowable(() -> environment.starting(Description.createTestDescription(Object.class, "name")))) + assertThat(catchThrowable(() -> environment.start())) .as("waiting on an invalid http path times out") .isInstanceOf(RuntimeException.class); } @Test - public void testWaitOnOneOfMultipleStrategiesFailing() { + void testWaitOnOneOfMultipleStrategiesFailing() { environment .withExposedService( "redis_1", @@ -83,13 +82,13 @@ public void testWaitOnOneOfMultipleStrategiesFailing() { ) .withTailChildContainers(true); - assertThat(catchThrowable(() -> environment.starting(Description.createTestDescription(Object.class, "name")))) + assertThat(catchThrowable(() -> environment.start())) .as("waiting on one failing strategy to time out") .isInstanceOf(RuntimeException.class); } @Test - public void testWaitingForNonexistentServices() { + void testWaitingForNonexistentServices() { String existentServiceName = "db_1"; String nonexistentServiceName1 = "some_nonexistent_service_1"; String nonexistentServiceName2 = "some_nonexistent_service_2"; diff --git a/core/src/test/java/org/testcontainers/junit/DockerNetworkModeTest.java b/core/src/test/java/org/testcontainers/junit/DockerNetworkModeTest.java index b048e4716fd..c35809f74e9 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerNetworkModeTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerNetworkModeTest.java @@ -2,7 +2,7 @@ import com.github.dockerjava.api.model.NetworkSettings; import lombok.extern.slf4j.Slf4j; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; @@ -14,10 +14,10 @@ * without other setup steps. */ @Slf4j -public class DockerNetworkModeTest { +class DockerNetworkModeTest { @Test - public void testNoNetworkContainer() { + void testNoNetworkContainer() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) @@ -33,7 +33,7 @@ public void testNoNetworkContainer() { } @Test - public void testHostNetworkContainer() { + void testHostNetworkContainer() { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) diff --git a/core/src/test/java/org/testcontainers/junit/DockerfileContainerTest.java b/core/src/test/java/org/testcontainers/junit/DockerfileContainerTest.java index 9ed143aca9c..61500ca7993 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerfileContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerfileContainerTest.java @@ -4,8 +4,8 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.images.builder.ImageFromDockerfile; @@ -16,9 +16,9 @@ /** * Simple test case / demonstration of creating a fresh container image from a Dockerfile DSL */ -public class DockerfileContainerTest { +class DockerfileContainerTest { - @Rule + @AutoClose public GenericContainer dslContainer = new GenericContainer( new ImageFromDockerfile("tcdockerfile/nginx", false) .withDockerfileFromBuilder(builder -> { @@ -32,7 +32,9 @@ public class DockerfileContainerTest { .withExposedPorts(80); @Test - public void simpleDslTest() throws IOException { + void simpleDslTest() throws IOException { + dslContainer.start(); + String address = String.format("http://%s:%s", dslContainer.getHost(), dslContainer.getMappedPort(80)); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); diff --git a/core/src/test/java/org/testcontainers/junit/DockerfileTest.java b/core/src/test/java/org/testcontainers/junit/DockerfileTest.java index 113fd7f4c63..9f85af8d209 100644 --- a/core/src/test/java/org/testcontainers/junit/DockerfileTest.java +++ b/core/src/test/java/org/testcontainers/junit/DockerfileTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; import com.github.dockerjava.api.command.BuildImageCmd; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; @@ -16,12 +16,12 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -public class DockerfileTest { +class DockerfileTest { private static final Logger LOGGER = LoggerFactory.getLogger(DockerfileTest.class); @Test - public void simpleDockerfileWorks() { + void simpleDockerfileWorks() { ImageFromDockerfile image = new ImageFromDockerfile() .withFileFromString("folder/someFile.txt", "hello") .withFileFromClasspath("test.txt", "mappable-resource/test-resource.txt") @@ -31,7 +31,7 @@ public void simpleDockerfileWorks() { } @Test - public void customizableImage() { + void customizableImage() { ImageFromDockerfile image = new ImageFromDockerfile() { @Override protected void configure(BuildImageCmd buildImageCmd) { @@ -52,7 +52,7 @@ protected void configure(BuildImageCmd buildImageCmd) { } @Test - public void dockerfileBuilderWorks() { + void dockerfileBuilderWorks() { ImageFromDockerfile image = new ImageFromDockerfile() .withFileFromClasspath("test.txt", "mappable-resource/test-resource.txt") .withFileFromString("folder/someFile.txt", "hello") @@ -71,7 +71,7 @@ public void dockerfileBuilderWorks() { } @Test - public void filePermissions() throws TimeoutException { + void filePermissions() throws TimeoutException { WaitingConsumer consumer = new WaitingConsumer(); ImageFromDockerfile image = new ImageFromDockerfile() diff --git a/core/src/test/java/org/testcontainers/junit/ExecInContainerTest.java b/core/src/test/java/org/testcontainers/junit/ExecInContainerTest.java index a3dd21318d2..365229e5909 100644 --- a/core/src/test/java/org/testcontainers/junit/ExecInContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/ExecInContainerTest.java @@ -1,8 +1,8 @@ package org.testcontainers.junit; -import org.junit.Assume; -import org.junit.ClassRule; -import org.junit.Test; +import org.assertj.core.api.Assumptions; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.ExecConfig; import org.testcontainers.containers.GenericContainer; @@ -12,17 +12,21 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ExecInContainerTest { +class ExecInContainerTest { - @ClassRule + @AutoClose public static GenericContainer redis = new GenericContainer<>(TestImages.REDIS_IMAGE).withExposedPorts(6379); + static { + redis.start(); + } + @Test - public void shouldExecuteCommand() throws Exception { + void shouldExecuteCommand() throws Exception { // The older "lxc" execution driver doesn't support "exec". At the time of writing (2016/03/29), // that's the case for CircleCI. // Once they resolve the issue, this clause can be removed. - Assume.assumeTrue(TestEnvironment.dockerExecutionDriverSupportsExec()); + Assumptions.assumeThat(TestEnvironment.dockerExecutionDriverSupportsExec()).isTrue(); final GenericContainer.ExecResult result = redis.execInContainer("redis-cli", "role"); assertThat(result.getStdout()) @@ -33,11 +37,11 @@ public void shouldExecuteCommand() throws Exception { } @Test - public void shouldExecuteCommandWithUser() throws Exception { + void shouldExecuteCommandWithUser() throws Exception { // The older "lxc" execution driver doesn't support "exec". At the time of writing (2016/03/29), // that's the case for CircleCI. // Once they resolve the issue, this clause can be removed. - Assume.assumeTrue(TestEnvironment.dockerExecutionDriverSupportsExec()); + Assumptions.assumeThat(TestEnvironment.dockerExecutionDriverSupportsExec()).isTrue(); final GenericContainer.ExecResult result = redis.execInContainerWithUser("redis", "whoami"); assertThat(result.getStdout()) @@ -48,8 +52,8 @@ public void shouldExecuteCommandWithUser() throws Exception { } @Test - public void shouldExecuteCommandWithWorkdir() throws Exception { - Assume.assumeTrue(TestEnvironment.dockerExecutionDriverSupportsExec()); + void shouldExecuteCommandWithWorkdir() throws Exception { + Assumptions.assumeThat(TestEnvironment.dockerExecutionDriverSupportsExec()).isTrue(); final GenericContainer.ExecResult result = redis.execInContainer( ExecConfig.builder().workDir("/opt").command(new String[] { "pwd" }).build() @@ -58,8 +62,8 @@ public void shouldExecuteCommandWithWorkdir() throws Exception { } @Test - public void shouldExecuteCommandWithEnvVars() throws Exception { - Assume.assumeTrue(TestEnvironment.dockerExecutionDriverSupportsExec()); + void shouldExecuteCommandWithEnvVars() throws Exception { + Assumptions.assumeThat(TestEnvironment.dockerExecutionDriverSupportsExec()).isTrue(); final GenericContainer.ExecResult result = redis.execInContainer( ExecConfig diff --git a/core/src/test/java/org/testcontainers/junit/FileOperationsTest.java b/core/src/test/java/org/testcontainers/junit/FileOperationsTest.java index 767deacfb00..f2c8117a905 100644 --- a/core/src/test/java/org/testcontainers/junit/FileOperationsTest.java +++ b/core/src/test/java/org/testcontainers/junit/FileOperationsTest.java @@ -4,9 +4,8 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.CountingOutputStream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.testcontainers.TestImages; import org.testcontainers.containers.Container; import org.testcontainers.containers.GenericContainer; @@ -17,17 +16,18 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.Path; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class FileOperationsTest { +class FileOperationsTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public Path temporaryFolder; @Test - public void copyFileToContainerFileTest() throws Exception { + void copyFileToContainerFileTest() throws Exception { try ( GenericContainer alpineCopyToContainer = new GenericContainer(TestImages.ALPINE_IMAGE) // .withCommand("top") @@ -36,7 +36,7 @@ public void copyFileToContainerFileTest() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt"); alpineCopyToContainer.copyFileToContainer(mountableFile, "/test.txt"); - File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_to_container.txt"); + File actualFile = new File(temporaryFolder.toFile().getAbsolutePath() + "/test_copy_to_container.txt"); alpineCopyToContainer.copyFileFromContainer("/test.txt", actualFile.getPath()); File expectedFile = new File(mountableFile.getResolvedPath()); @@ -45,8 +45,8 @@ public void copyFileToContainerFileTest() throws Exception { } @Test - public void copyLargeFilesToContainer() throws Exception { - File tempFile = temporaryFolder.newFile(); + void copyLargeFilesToContainer() throws Exception { + File tempFile = temporaryFolder.resolve("large-file").toFile(); try ( GenericContainer alpineCopyToContainer = new GenericContainer<>(TestImages.ALPINE_IMAGE) // .withCommand("sleep", "infinity") @@ -82,7 +82,7 @@ public void copyLargeFilesToContainer() throws Exception { } @Test - public void copyFileToContainerFolderTest() throws Exception { + void copyFileToContainerFolderTest() throws Exception { try ( GenericContainer alpineCopyToContainer = new GenericContainer(TestImages.ALPINE_IMAGE) // .withCommand("top") @@ -91,7 +91,7 @@ public void copyFileToContainerFolderTest() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt"); alpineCopyToContainer.copyFileToContainer(mountableFile, "/home/"); - File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_to_container.txt"); + File actualFile = new File(temporaryFolder.toFile().getAbsolutePath() + "/test_copy_to_container.txt"); alpineCopyToContainer.copyFileFromContainer("/home/test_copy_to_container.txt", actualFile.getPath()); File expectedFile = new File(mountableFile.getResolvedPath()); @@ -100,7 +100,7 @@ public void copyFileToContainerFolderTest() throws Exception { } @Test - public void copyFolderToContainerFolderTest() throws Exception { + void copyFolderToContainerFolderTest() throws Exception { try ( GenericContainer alpineCopyToContainer = new GenericContainer(TestImages.ALPINE_IMAGE) // .withCommand("top") @@ -109,7 +109,7 @@ public void copyFolderToContainerFolderTest() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("mappable-resource/"); alpineCopyToContainer.copyFileToContainer(mountableFile, "/home/test/"); - File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_to_container.txt"); + File actualFile = new File(temporaryFolder.toFile().getAbsolutePath() + "/test_copy_to_container.txt"); alpineCopyToContainer.copyFileFromContainer("/home/test/test-resource.txt", actualFile.getPath()); File expectedFile = new File(mountableFile.getResolvedPath() + "/test-resource.txt"); @@ -117,19 +117,25 @@ public void copyFolderToContainerFolderTest() throws Exception { } } - @Test(expected = NotFoundException.class) - public void copyFromContainerShouldFailBecauseNoFileTest() throws NotFoundException { - try ( - GenericContainer alpineCopyToContainer = new GenericContainer(TestImages.ALPINE_IMAGE) // - .withCommand("top") - ) { - alpineCopyToContainer.start(); - alpineCopyToContainer.copyFileFromContainer("/home/test.txt", "src/test/resources/copy-from/test.txt"); - } + @Test + void copyFromContainerShouldFailBecauseNoFileTest() { + assertThatThrownBy(() -> { + try ( + GenericContainer alpineCopyToContainer = new GenericContainer(TestImages.ALPINE_IMAGE) // + .withCommand("top") + ) { + alpineCopyToContainer.start(); + alpineCopyToContainer.copyFileFromContainer( + "/home/test.txt", + "src/test/resources/copy-from/test.txt" + ); + } + }) + .isInstanceOf(NotFoundException.class); } @Test - public void shouldCopyFileFromContainerTest() throws IOException { + void shouldCopyFileFromContainerTest() throws IOException { try ( GenericContainer alpineCopyToContainer = new GenericContainer(TestImages.ALPINE_IMAGE) // .withCommand("top") @@ -138,7 +144,7 @@ public void shouldCopyFileFromContainerTest() throws IOException { final MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt"); alpineCopyToContainer.copyFileToContainer(mountableFile, "/home/"); - File actualFile = new File(temporaryFolder.getRoot().getAbsolutePath() + "/test_copy_from_container.txt"); + File actualFile = new File(temporaryFolder.toFile().getAbsolutePath() + "/test_copy_from_container.txt"); alpineCopyToContainer.copyFileFromContainer("/home/test_copy_to_container.txt", actualFile.getPath()); File expectedFile = new File(mountableFile.getResolvedPath()); @@ -147,7 +153,7 @@ public void shouldCopyFileFromContainerTest() throws IOException { } @Test - public void copyFileOperationsShouldFailWhenNotStartedTest() { + void copyFileOperationsShouldFailWhenNotStartedTest() { try (GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE).withCommand("top")) { assertThatThrownBy(() -> { MountableFile mountableFile = MountableFile.forClasspathResource("test_copy_to_container.txt"); @@ -165,7 +171,7 @@ public void copyFileOperationsShouldFailWhenNotStartedTest() { } @Test - public void shouldCopyFileFromExitedContainerTest() throws IOException { + void shouldCopyFileFromExitedContainerTest() { try ( GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withCommand("sh", "-c", "echo -n 'Hello!' > /home/file_in_container.txt") diff --git a/core/src/test/java/org/testcontainers/junit/FixedHostPortContainerTest.java b/core/src/test/java/org/testcontainers/junit/FixedHostPortContainerTest.java index a123b800f3a..38f1f5c9a6f 100644 --- a/core/src/test/java/org/testcontainers/junit/FixedHostPortContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/FixedHostPortContainerTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit; import org.awaitility.Awaitility; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.FixedHostPortGenericContainer; import org.testcontainers.containers.GenericContainer; @@ -20,7 +20,7 @@ * is managed completely within the test method to allow a free port to be found and assigned before the container * is started. */ -public class FixedHostPortContainerTest { +class FixedHostPortContainerTest { private static final String TEST_IMAGE = "alpine:3.17"; @@ -44,7 +44,7 @@ public class FixedHostPortContainerTest { ); @Test - public void testFixedHostPortMapping() throws IOException { + void testFixedHostPortMapping() throws IOException { // first find a free port on the docker host that will work for testing final Integer unusedHostPort; try ( diff --git a/core/src/test/java/org/testcontainers/junit/GenericContainerRuleTest.java b/core/src/test/java/org/testcontainers/junit/GenericContainerRuleTest.java index 5a9d7c1616d..5719f3e0268 100644 --- a/core/src/test/java/org/testcontainers/junit/GenericContainerRuleTest.java +++ b/core/src/test/java/org/testcontainers/junit/GenericContainerRuleTest.java @@ -14,10 +14,9 @@ import com.rabbitmq.client.Envelope; import org.apache.commons.io.FileUtils; import org.bson.Document; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.rnorth.ducttape.RetryCountExceededException; import org.rnorth.ducttape.unreliables.Unreliables; import org.testcontainers.TestImages; @@ -51,7 +50,7 @@ /** * Tests for GenericContainerRules */ -public class GenericContainerRuleTest { +class GenericContainerRuleTest { private static final int REDIS_PORT = 6379; @@ -68,7 +67,7 @@ public class GenericContainerRuleTest { /* * Test data setup */ - @BeforeClass + @BeforeAll public static void setupContent() throws FileNotFoundException { File contentFolder = new File(System.getProperty("user.home") + "/.tmp-test-container"); contentFolder.mkdir(); @@ -78,21 +77,18 @@ public static void setupContent() throws FileNotFoundException { /** * Redis */ - @ClassRule public static GenericContainer redis = new GenericContainer<>(TestImages.REDIS_IMAGE) .withExposedPorts(REDIS_PORT); /** * RabbitMQ */ - @ClassRule public static GenericContainer rabbitMq = new GenericContainer<>(TestImages.RABBITMQ_IMAGE) .withExposedPorts(RABBITMQ_PORT); /** * MongoDB */ - @ClassRule public static GenericContainer mongo = new GenericContainer<>(TestImages.MONGODB_IMAGE) .withExposedPorts(MONGO_PORT); @@ -100,7 +96,6 @@ public static void setupContent() throws FileNotFoundException { * Pass an environment variable to the container, then run a shell script that exposes the variable in a quick and * dirty way for testing. */ - @ClassRule public static GenericContainer alpineEnvVar = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts(80) .withEnv("MAGIC_NUMBER", "4") @@ -111,7 +106,6 @@ public static void setupContent() throws FileNotFoundException { * Pass environment variables to the container, then run a shell script that exposes the variables in a quick and * dirty way for testing. */ - @ClassRule public static GenericContainer alpineEnvVarFromMap = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts(80) .withEnv(ImmutableMap.of("FIRST", "42", "SECOND", "50")) @@ -120,7 +114,6 @@ public static void setupContent() throws FileNotFoundException { /** * Map a file on the classpath to a file in the container, and then expose the content for testing. */ - @ClassRule public static GenericContainer alpineClasspathResource = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts(80) .withClasspathResourceMapping("mappable-resource/test-resource.txt", "/content.txt", BindMode.READ_ONLY) @@ -129,7 +122,6 @@ public static void setupContent() throws FileNotFoundException { /** * Map a file on the classpath to a file in the container, and then expose the content for testing. */ - @ClassRule public static GenericContainer alpineClasspathResourceSelinux = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts(80) .withClasspathResourceMapping( @@ -143,14 +135,24 @@ public static void setupContent() throws FileNotFoundException { /** * Create a container with an extra host entry and expose the content of /etc/hosts for testing. */ - @ClassRule public static GenericContainer alpineExtrahost = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts(80) .withExtraHost("somehost", "192.168.1.10") .withCommand("/bin/sh", "-c", "while true; do cat /etc/hosts | nc -l -p 80; done"); + static { + redis.start(); + rabbitMq.start(); + mongo.start(); + alpineEnvVar.start(); + alpineEnvVarFromMap.start(); + alpineClasspathResource.start(); + alpineClasspathResourceSelinux.start(); + alpineExtrahost.start(); + } + @Test - public void testIsRunning() { + void testIsRunning() { try (GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE).withCommand("top")) { assertThat(container.isRunning()).as("Container is not started and not running").isFalse(); container.start(); @@ -159,7 +161,7 @@ public void testIsRunning() { } @Test - public void withTmpFsTest() throws Exception { + void withTmpFsTest() throws Exception { try ( GenericContainer container = new GenericContainer<>(TestImages.TINY_IMAGE) .withCommand("top") @@ -180,7 +182,7 @@ public void withTmpFsTest() throws Exception { } @Test - public void simpleRabbitMqTest() throws IOException, TimeoutException { + void simpleRabbitMqTest() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMq.getHost()); factory.setPort(rabbitMq.getMappedPort(RABBITMQ_PORT)); @@ -230,7 +232,7 @@ public void handleDelivery( } @Test - public void simpleMongoDbTest() { + void simpleMongoDbTest() { MongoClient mongoClient = new MongoClient(mongo.getHost(), mongo.getMappedPort(MONGO_PORT)); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection collection = database.getCollection("testCollection"); @@ -243,21 +245,21 @@ public void simpleMongoDbTest() { } @Test - public void environmentAndCustomCommandTest() throws IOException { + void environmentAndCustomCommandTest() throws IOException { String line = getReaderForContainerPort80(alpineEnvVar).readLine(); assertThat(line).as("An environment variable can be passed into a command").isEqualTo("42"); } @Test - public void environmentFromMapTest() throws IOException { + void environmentFromMapTest() throws IOException { String line = getReaderForContainerPort80(alpineEnvVarFromMap).readLine(); assertThat(line).as("Environment variables can be passed into a command from a map").isEqualTo("42 and 50"); } @Test - public void customLabelTest() { + void customLabelTest() { try ( final GenericContainer alpineCustomLabel = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withLabel("our.custom", "label") @@ -285,7 +287,7 @@ public void customLabelTest() { } @Test - public void exceptionThrownWhenTryingToOverrideTestcontainersLabels() { + void exceptionThrownWhenTryingToOverrideTestcontainersLabels() { assertThat( catchThrowable(() -> { new GenericContainer<>(TestImages.ALPINE_IMAGE).withLabel("org.testcontainers.foo", "false"); @@ -296,7 +298,7 @@ public void exceptionThrownWhenTryingToOverrideTestcontainersLabels() { } @Test - public void customClasspathResourceMappingTest() throws IOException { + void customClasspathResourceMappingTest() throws IOException { // Note: This functionality doesn't work if you are running your build inside a Docker container; // in that case this test will fail. String line = getReaderForContainerPort80(alpineClasspathResource).readLine(); @@ -307,7 +309,7 @@ public void customClasspathResourceMappingTest() throws IOException { } @Test - public void customClasspathResourceMappingWithSelinuxTest() throws IOException { + void customClasspathResourceMappingWithSelinuxTest() throws IOException { String line = getReaderForContainerPort80(alpineClasspathResourceSelinux).readLine(); assertThat(line) .as("Resource on the classpath can be mapped using calls to withClasspathResourceMappingSelinux") @@ -315,7 +317,7 @@ public void customClasspathResourceMappingWithSelinuxTest() throws IOException { } @Test - public void exceptionThrownWhenMappedPortNotFound() { + void exceptionThrownWhenMappedPortNotFound() { assertThat(catchThrowable(() -> redis.getMappedPort(666))) .as("When the requested port is not mapped, getMappedPort() throws an exception") .isInstanceOf(IllegalArgumentException.class); @@ -331,8 +333,8 @@ protected static void writeStringToFile(File contentFolder, String filename, Str } @Test - @Ignore //TODO investigate intermittent failures - public void failFastWhenContainerHaltsImmediately() { + @Disabled //TODO investigate intermittent failures + void failFastWhenContainerHaltsImmediately() { long startingTimeNano = System.nanoTime(); final GenericContainer failsImmediately = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withCommand("/bin/sh", "-c", "return false") @@ -358,7 +360,7 @@ public void failFastWhenContainerHaltsImmediately() { } @Test - public void extraHostTest() throws IOException { + void extraHostTest() throws IOException { BufferedReader br = getReaderForContainerPort80(alpineExtrahost); // read hosts file from container @@ -375,7 +377,7 @@ public void extraHostTest() throws IOException { } @Test - public void createContainerCmdHookTest() { + void createContainerCmdHookTest() { // Use random name to avoid the conflicts between the tests String randomName = Base58.randomString(5); try ( @@ -410,7 +412,7 @@ private BufferedReader getReaderForContainerPort80(GenericContainer container) { } @Test - public void addExposedPortAfterWithExposedPortsTest() { + void addExposedPortAfterWithExposedPortsTest() { redis.addExposedPort(8987); assertThat(redis.getExposedPorts()).as("Both ports should be exposed").hasSize(2); assertThat(redis.getExposedPorts()).as("withExposedPort should be exposed").contains(REDIS_PORT); @@ -418,7 +420,7 @@ public void addExposedPortAfterWithExposedPortsTest() { } @Test - public void addingExposedPortTwiceShouldNotFail() { + void addingExposedPortTwiceShouldNotFail() { redis.addExposedPort(8987); redis.addExposedPort(8987); assertThat(redis.getExposedPorts()).as("Both ports should be exposed").hasSize(2); // 2 ports = de-duplicated port 8897 and original port 6379 @@ -427,7 +429,7 @@ public void addingExposedPortTwiceShouldNotFail() { } @Test - public void sharedMemorySetTest() { + void sharedMemorySetTest() { try ( GenericContainer containerWithSharedMemory = new GenericContainer<>(TestImages.TINY_IMAGE) .withSharedMemorySize(42L * FileUtils.ONE_MB) diff --git a/core/src/test/java/org/testcontainers/junit/NonExistentImagePullTest.java b/core/src/test/java/org/testcontainers/junit/NonExistentImagePullTest.java index aff9b29cbe7..2978777aae7 100644 --- a/core/src/test/java/org/testcontainers/junit/NonExistentImagePullTest.java +++ b/core/src/test/java/org/testcontainers/junit/NonExistentImagePullTest.java @@ -1,6 +1,7 @@ package org.testcontainers.junit; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.containers.ContainerFetchException; import org.testcontainers.containers.GenericContainer; import org.testcontainers.utility.DockerImageName; @@ -11,10 +12,11 @@ /** * Created by rnorth on 20/03/2016. */ -public class NonExistentImagePullTest { +class NonExistentImagePullTest { - @Test(timeout = 60_000L) - public void pullingNonExistentImageFailsGracefully() { + @Test + @Timeout(60) + void pullingNonExistentImageFailsGracefully() { assertThat( catchThrowable(() -> { new GenericContainer<>(DockerImageName.parse("testcontainers/nonexistent:latest")).getDockerImageName(); diff --git a/core/src/test/java/org/testcontainers/junit/OutputStreamTest.java b/core/src/test/java/org/testcontainers/junit/OutputStreamTest.java index 17b1d247cbb..42fc7ff584b 100644 --- a/core/src/test/java/org/testcontainers/junit/OutputStreamTest.java +++ b/core/src/test/java/org/testcontainers/junit/OutputStreamTest.java @@ -1,7 +1,9 @@ package org.testcontainers.junit; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.TestImages; @@ -21,16 +23,26 @@ /** * Simple test for following container output. */ -public class OutputStreamTest { +class OutputStreamTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(OutputStreamTest.class); - @Rule public GenericContainer container = new GenericContainer(TestImages.ALPINE_IMAGE) .withCommand("ping -c 5 127.0.0.1"); - private static final Logger LOGGER = LoggerFactory.getLogger(OutputStreamTest.class); + @BeforeEach + void setUp() { + container.start(); + } + + @AfterEach + void tearDown() { + container.stop(); + } - @Test(timeout = 60_000L) - public void testFetchStdout() throws TimeoutException { + @Test + @Timeout(value = 60) + void testFetchStdout() throws TimeoutException { WaitingConsumer consumer = new WaitingConsumer(); container.followOutput(consumer, OutputFrame.OutputType.STDOUT); @@ -42,8 +54,9 @@ public void testFetchStdout() throws TimeoutException { ); } - @Test(timeout = 60_000L) - public void testFetchStdoutWithTimeout() { + @Test + @Timeout(value = 60) + void testFetchStdoutWithTimeout() { WaitingConsumer consumer = new WaitingConsumer(); container.followOutput(consumer, OutputFrame.OutputType.STDOUT); @@ -65,8 +78,9 @@ public void testFetchStdoutWithTimeout() { .isInstanceOf(TimeoutException.class); } - @Test(timeout = 60_000L) - public void testFetchStdoutWithNoLimit() throws TimeoutException { + @Test + @Timeout(value = 60) + void testFetchStdoutWithNoLimit() throws TimeoutException { WaitingConsumer consumer = new WaitingConsumer(); container.followOutput(consumer, OutputFrame.OutputType.STDOUT); @@ -76,8 +90,9 @@ public void testFetchStdoutWithNoLimit() throws TimeoutException { }); } - @Test(timeout = 60_000L) - public void testLogConsumer() throws TimeoutException { + @Test + @Timeout(value = 60) + void testLogConsumer() throws TimeoutException { WaitingConsumer waitingConsumer = new WaitingConsumer(); Slf4jLogConsumer logConsumer = new Slf4jLogConsumer(LOGGER); @@ -89,8 +104,9 @@ public void testLogConsumer() throws TimeoutException { }); } - @Test(timeout = 60_000L) - public void testToStringConsumer() throws TimeoutException { + @Test + @Timeout(value = 60) + void testToStringConsumer() throws TimeoutException { WaitingConsumer waitingConsumer = new WaitingConsumer(); ToStringConsumer toStringConsumer = new ToStringConsumer(); diff --git a/core/src/test/java/org/testcontainers/junit/OutputStreamWithTTYTest.java b/core/src/test/java/org/testcontainers/junit/OutputStreamWithTTYTest.java index c340f26d3fb..a6dbfa06343 100644 --- a/core/src/test/java/org/testcontainers/junit/OutputStreamWithTTYTest.java +++ b/core/src/test/java/org/testcontainers/junit/OutputStreamWithTTYTest.java @@ -1,9 +1,10 @@ package org.testcontainers.junit; import lombok.extern.slf4j.Slf4j; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.AutoClose; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.OutputFrame; @@ -20,19 +21,22 @@ import static org.assertj.core.api.Assertions.catchThrowable; @Slf4j -public class OutputStreamWithTTYTest { +@Timeout(10) +class OutputStreamWithTTYTest { - @Rule + @AutoClose public GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withCommand("ls -1") .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) .withCreateContainerCmdModifier(command -> command.withTty(true)); - @Rule - public Timeout globalTimeout = Timeout.seconds(10); + @BeforeEach + void setUp() { + container.start(); + } @Test - public void testFetchStdout() throws TimeoutException { + void testFetchStdout() throws TimeoutException { WaitingConsumer consumer = new WaitingConsumer(); container.followOutput(consumer, OutputFrame.OutputType.STDOUT); @@ -47,7 +51,7 @@ public void testFetchStdout() throws TimeoutException { } @Test - public void testFetchStdoutWithTimeout() { + void testFetchStdoutWithTimeout() { WaitingConsumer consumer = new WaitingConsumer(); container.followOutput(consumer, OutputFrame.OutputType.STDOUT); @@ -70,7 +74,7 @@ public void testFetchStdoutWithTimeout() { } @Test - public void testFetchStdoutWithNoLimit() throws TimeoutException { + void testFetchStdoutWithNoLimit() throws TimeoutException { WaitingConsumer consumer = new WaitingConsumer(); container.followOutput(consumer, OutputFrame.OutputType.STDOUT); @@ -81,7 +85,7 @@ public void testFetchStdoutWithNoLimit() throws TimeoutException { } @Test - public void testLogConsumer() throws TimeoutException { + void testLogConsumer() throws TimeoutException { WaitingConsumer waitingConsumer = new WaitingConsumer(); Slf4jLogConsumer logConsumer = new Slf4jLogConsumer(log); @@ -94,7 +98,7 @@ public void testLogConsumer() throws TimeoutException { } @Test - public void testToStringConsumer() throws TimeoutException { + void testToStringConsumer() throws TimeoutException { WaitingConsumer waitingConsumer = new WaitingConsumer(); ToStringConsumer toStringConsumer = new ToStringConsumer(); diff --git a/core/src/test/java/org/testcontainers/junit/ParameterizedDockerfileContainerTest.java b/core/src/test/java/org/testcontainers/junit/ParameterizedDockerfileContainerTest.java index 8437123f97a..0f98a35893b 100644 --- a/core/src/test/java/org/testcontainers/junit/ParameterizedDockerfileContainerTest.java +++ b/core/src/test/java/org/testcontainers/junit/ParameterizedDockerfileContainerTest.java @@ -1,24 +1,26 @@ package org.testcontainers.junit; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.images.builder.ImageFromDockerfile; +import java.util.stream.Stream; + import static org.assertj.core.api.Assertions.assertThat; /** * Simple test case / demonstration of creating a fresh container image from a Dockerfile DSL when the test * is parameterized. */ -@RunWith(Parameterized.class) -public class ParameterizedDockerfileContainerTest { +@ParameterizedClass(name = "{0}") +@MethodSource("data") +class ParameterizedDockerfileContainerTest { private final String expectedVersion; - @Rule public GenericContainer container; public ParameterizedDockerfileContainerTest(String baseImage, String expectedVersion) { @@ -34,22 +36,22 @@ public ParameterizedDockerfileContainerTest(String baseImage, String expectedVer }) ) .withCommand("top"); + container.start(); this.expectedVersion = expectedVersion; } - @Parameterized.Parameters(name = "{0}") - public static Object[][] data() { - return new Object[][] { // - { "alpine:3.12", "3.12" }, - { "alpine:3.13", "3.13" }, - { "alpine:3.14", "3.14" }, - { "alpine:3.15", "3.15" }, - { "alpine:3.16", "3.16" }, - }; + public static Stream data() { + return Stream.of( + Arguments.of("alpine:3.12", "3.12"), + Arguments.of("alpine:3.13", "3.13"), + Arguments.of("alpine:3.14", "3.14"), + Arguments.of("alpine:3.15", "3.15"), + Arguments.of("alpine:3.16", "3.16") + ); } @Test - public void simpleTest() throws Exception { + void simpleTest() throws Exception { final String release = container.execInContainer("cat", "/etc/alpine-release").getStdout(); assertThat(release).as("/etc/alpine-release starts with " + expectedVersion).startsWith(expectedVersion); diff --git a/core/src/test/java/org/testcontainers/junit/WorkingDirectoryTest.java b/core/src/test/java/org/testcontainers/junit/WorkingDirectoryTest.java index 05f65e1f493..a31b38e06ed 100644 --- a/core/src/test/java/org/testcontainers/junit/WorkingDirectoryTest.java +++ b/core/src/test/java/org/testcontainers/junit/WorkingDirectoryTest.java @@ -1,7 +1,6 @@ package org.testcontainers.junit; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; @@ -11,16 +10,19 @@ /** * Created by rnorth on 26/07/2016. */ -public class WorkingDirectoryTest { +class WorkingDirectoryTest { - @ClassRule public static GenericContainer container = new GenericContainer(TestImages.ALPINE_IMAGE) .withWorkingDirectory("/etc") .withStartupCheckStrategy(new OneShotStartupCheckStrategy()) .withCommand("ls", "-al"); + static { + container.start(); + } + @Test - public void checkOutput() { + void checkOutput() { String listing = container.getLogs(); assertThat(listing).as("Directory listing contains expected /etc content").contains("hostname"); diff --git a/core/src/test/java/org/testcontainers/junit/wait/strategy/AbstractWaitStrategyTest.java b/core/src/test/java/org/testcontainers/junit/wait/strategy/AbstractWaitStrategyTest.java index 6c2dbb50244..fa97bbc25c3 100644 --- a/core/src/test/java/org/testcontainers/junit/wait/strategy/AbstractWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/wait/strategy/AbstractWaitStrategyTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit.wait.strategy; import org.jetbrains.annotations.NotNull; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.rnorth.ducttape.RetryCountExceededException; import org.testcontainers.TestImages; import org.testcontainers.containers.ContainerLaunchException; @@ -36,7 +36,7 @@ public abstract class AbstractWaitStrategyTest { @NotNull protected abstract W buildWaitStrategy(final AtomicBoolean ready); - @Before + @BeforeEach public void setUp() { ready = new AtomicBoolean(false); } diff --git a/core/src/test/java/org/testcontainers/junit/wait/strategy/HostPortWaitStrategyTest.java b/core/src/test/java/org/testcontainers/junit/wait/strategy/HostPortWaitStrategyTest.java index bed23566899..15b6aa74961 100644 --- a/core/src/test/java/org/testcontainers/junit/wait/strategy/HostPortWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/wait/strategy/HostPortWaitStrategyTest.java @@ -1,9 +1,7 @@ package org.testcontainers.junit.wait.strategy; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; import org.testcontainers.TestImages; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; @@ -14,32 +12,35 @@ * Test wait strategy with overloaded waitingFor methods. * Other implementations of WaitStrategy are tested through backwards compatible wait strategy tests */ -@RunWith(Enclosed.class) -public class HostPortWaitStrategyTest { +class HostPortWaitStrategyTest { - public static class DefaultHostPortWaitStrategyTest { + @Nested + class DefaultHostPortWaitStrategyTest { - @ClassRule - public static GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE) + public GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts() .withCommand("sh", "-c", "while true; do nc -lp 8080; done") .withExposedPorts(8080) .waitingFor(Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(10))); @Test - public void testWaiting() {} + void testWaiting() { + container.start(); + } } - public static class ExplicitHostPortWaitStrategyTest { + @Nested + class ExplicitHostPortWaitStrategyTest { - @ClassRule - public static GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE) + public GenericContainer container = new GenericContainer<>(TestImages.ALPINE_IMAGE) .withExposedPorts() .withCommand("sh", "-c", "while true; do nc -lp 8080; done") .withExposedPorts(8080) .waitingFor(Wait.forListeningPorts(8080).withStartupTimeout(Duration.ofSeconds(10))); @Test - public void testWaiting() {} + void testWaiting() { + container.start(); + } } } diff --git a/core/src/test/java/org/testcontainers/junit/wait/strategy/HttpWaitStrategyTest.java b/core/src/test/java/org/testcontainers/junit/wait/strategy/HttpWaitStrategyTest.java index 91c94009086..89a12ec3aea 100644 --- a/core/src/test/java/org/testcontainers/junit/wait/strategy/HttpWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/wait/strategy/HttpWaitStrategyTest.java @@ -2,7 +2,7 @@ import org.assertj.core.api.Assertions; import org.jetbrains.annotations.NotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.rnorth.ducttape.RetryCountExceededException; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.HttpWaitStrategy; @@ -18,7 +18,7 @@ /** * Tests for {@link HttpWaitStrategy}. */ -public class HttpWaitStrategyTest extends AbstractWaitStrategyTest { +class HttpWaitStrategyTest extends AbstractWaitStrategyTest { /** * newline sequence indicating end of the HTTP header. @@ -31,7 +31,7 @@ public class HttpWaitStrategyTest extends AbstractWaitStrategyTest headers = new HashMap<>(); headers.put("baz", "boo"); try ( @@ -64,7 +64,7 @@ public void testWaitUntilReadyWithSuccessWithCustomHeaders() { * certificate validation chains (to support self-signed certificates for example). */ @Test - public void testWaitUntilReadyWithTlsAndAllowUnsecure() { + void testWaitUntilReadyWithTlsAndAllowUnsecure() { try ( GenericContainer container = startContainerWithCommand( createHttpsShellCommand("200 OK", GOOD_RESPONSE_BODY, 8080), @@ -80,7 +80,7 @@ public void testWaitUntilReadyWithTlsAndAllowUnsecure() { * This 401 response is checked with a lambda using {@link HttpWaitStrategy#forStatusCodeMatching(Predicate)} */ @Test - public void testWaitUntilReadyWithUnauthorizedWithLambda() { + void testWaitUntilReadyWithUnauthorizedWithLambda() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("401 UNAUTHORIZED", GOOD_RESPONSE_BODY), @@ -96,7 +96,7 @@ public void testWaitUntilReadyWithUnauthorizedWithLambda() { * This 401 response is checked with many status codes using {@link HttpWaitStrategy#forStatusCode(int)} */ @Test - public void testWaitUntilReadyWithManyStatusCodes() { + void testWaitUntilReadyWithManyStatusCodes() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("401 UNAUTHORIZED", GOOD_RESPONSE_BODY), @@ -113,7 +113,7 @@ public void testWaitUntilReadyWithManyStatusCodes() { * and a lambda using {@link HttpWaitStrategy#forStatusCodeMatching(Predicate)} */ @Test - public void testWaitUntilReadyWithManyStatusCodesAndLambda() { + void testWaitUntilReadyWithManyStatusCodesAndLambda() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("401 UNAUTHORIZED", GOOD_RESPONSE_BODY), @@ -133,7 +133,7 @@ public void testWaitUntilReadyWithManyStatusCodesAndLambda() { * and {@link HttpWaitStrategy#forStatusCodeMatching(Predicate)} */ @Test - public void testWaitUntilReadyWithTimeoutAndWithManyStatusCodesAndLambda() { + void testWaitUntilReadyWithTimeoutAndWithManyStatusCodesAndLambda() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("401 UNAUTHORIZED", GOOD_RESPONSE_BODY), @@ -152,7 +152,7 @@ public void testWaitUntilReadyWithTimeoutAndWithManyStatusCodesAndLambda() { * Test case for: https://github.com/testcontainers/testcontainers-java/issues/880 */ @Test - public void testWaitUntilReadyWithTimeoutAndWithLambdaShouldNotMatchOk() { + void testWaitUntilReadyWithTimeoutAndWithLambdaShouldNotMatchOk() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("200 OK", GOOD_RESPONSE_BODY), @@ -168,7 +168,7 @@ public void testWaitUntilReadyWithTimeoutAndWithLambdaShouldNotMatchOk() { * response from the container within the timeout period. */ @Test - public void testWaitUntilReadyWithTimeout() { + void testWaitUntilReadyWithTimeout() { waitUntilReadyAndTimeout(createShellCommand("400 Bad Request", GOOD_RESPONSE_BODY)); } @@ -177,7 +177,7 @@ public void testWaitUntilReadyWithTimeout() { * from the container within the timeout period. */ @Test - public void testWaitUntilReadyWithTimeoutAndBadResponseBody() { + void testWaitUntilReadyWithTimeoutAndBadResponseBody() { waitUntilReadyAndTimeout(createShellCommand("200 OK", "Bad Response")); } @@ -185,7 +185,7 @@ public void testWaitUntilReadyWithTimeoutAndBadResponseBody() { * Expects the WaitStrategy probing the right port. */ @Test - public void testWaitUntilReadyWithSpecificPort() { + void testWaitUntilReadyWithSpecificPort() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("200 OK", GOOD_RESPONSE_BODY, 9090), @@ -200,7 +200,7 @@ public void testWaitUntilReadyWithSpecificPort() { } @Test - public void testWaitUntilReadyWithTimeoutCausedByReadTimeout() { + void testWaitUntilReadyWithTimeoutCausedByReadTimeout() { try ( GenericContainer container = startContainerWithCommand( createShellCommand("0 Connection Refused", GOOD_RESPONSE_BODY, 9090), @@ -217,7 +217,7 @@ public void testWaitUntilReadyWithTimeoutCausedByReadTimeout() { * The exceptions we should see in the stacktrace ('/' means 'caused by'): ContainerLaunchException / TimeoutException / RuntimeException / SSLHandshakeException / ValidatorException (in sun.* package so not accessible) / SunCertPathBuilderException (in sun.* package so not accessible). */ @Test - public void testWaitUntilReadyWithTimeoutCausedBySslHandshakeError() { + void testWaitUntilReadyWithTimeoutCausedBySslHandshakeError() { try ( GenericContainer container = new GenericContainer<>( new ImageFromDockerfile() diff --git a/core/src/test/java/org/testcontainers/junit/wait/strategy/LogMessageWaitStrategyTest.java b/core/src/test/java/org/testcontainers/junit/wait/strategy/LogMessageWaitStrategyTest.java index 5dd9623107b..537254a60a1 100644 --- a/core/src/test/java/org/testcontainers/junit/wait/strategy/LogMessageWaitStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/wait/strategy/LogMessageWaitStrategyTest.java @@ -1,9 +1,9 @@ package org.testcontainers.junit.wait.strategy; import org.jetbrains.annotations.NotNull; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; import java.util.concurrent.atomic.AtomicBoolean; @@ -11,12 +11,12 @@ /** * Tests for {@link LogMessageWaitStrategy}. */ -@RunWith(Parameterized.class) -public class LogMessageWaitStrategyTest extends AbstractWaitStrategyTest { +@ParameterizedClass(name = "{0}") +@MethodSource("parameters") +class LogMessageWaitStrategyTest extends AbstractWaitStrategyTest { private final String pattern; - @Parameterized.Parameters(name = "{0}") public static Object[] parameters() { return new String[] { ".*ready.*\\s", // previous recommended style (explicit line ending) @@ -32,7 +32,7 @@ public LogMessageWaitStrategyTest(String pattern) { private static final String READY_MESSAGE = "I'm ready!"; @Test - public void testWaitUntilReady_Success() { + void testWaitUntilReady_Success() { waitUntilReadyAndSucceed( "echo -e \"" + READY_MESSAGE + @@ -46,7 +46,7 @@ public void testWaitUntilReady_Success() { } @Test - public void testWaitUntilReady_Timeout() { + void testWaitUntilReady_Timeout() { waitUntilReadyAndTimeout("echo -e \"" + READY_MESSAGE + "\";" + "echo -e \"foobar\";" + "sleep 300"); } diff --git a/core/src/test/java/org/testcontainers/junit/wait/strategy/ShellStrategyTest.java b/core/src/test/java/org/testcontainers/junit/wait/strategy/ShellStrategyTest.java index 0a85037cc14..20b08a5f396 100644 --- a/core/src/test/java/org/testcontainers/junit/wait/strategy/ShellStrategyTest.java +++ b/core/src/test/java/org/testcontainers/junit/wait/strategy/ShellStrategyTest.java @@ -1,7 +1,7 @@ package org.testcontainers.junit.wait.strategy; import org.jetbrains.annotations.NotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.wait.strategy.ShellStrategy; import java.util.concurrent.atomic.AtomicBoolean; @@ -9,17 +9,17 @@ /** * Tests for {@link ShellStrategy}. */ -public class ShellStrategyTest extends AbstractWaitStrategyTest { +class ShellStrategyTest extends AbstractWaitStrategyTest { private static final String LOCK_FILE = "/tmp/ready.lock"; @Test - public void testWaitUntilReady_Success() { + void testWaitUntilReady_Success() { waitUntilReadyAndSucceed(String.format("touch %s; sleep 300", LOCK_FILE)); } @Test - public void testWaitUntilReady_Timeout() { + void testWaitUntilReady_Timeout() { waitUntilReadyAndTimeout("sleep 300"); } diff --git a/core/src/test/java/org/testcontainers/utility/AuthenticatedImagePullTest.java b/core/src/test/java/org/testcontainers/utility/AuthenticatedImagePullTest.java index 0e00dd87bf7..1f6fbc1551a 100644 --- a/core/src/test/java/org/testcontainers/utility/AuthenticatedImagePullTest.java +++ b/core/src/test/java/org/testcontainers/utility/AuthenticatedImagePullTest.java @@ -2,10 +2,9 @@ import com.github.dockerjava.api.model.AuthConfig; import org.intellij.lang.annotations.Language; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.testcontainers.DockerRegistryContainer; import org.testcontainers.TestImages; @@ -37,7 +36,6 @@ public class AuthenticatedImagePullTest { /** * Containerised docker image registry, with simple hardcoded credentials */ - @ClassRule public static DockerRegistryContainer authenticatedRegistry = new DockerRegistryContainer( new ImageFromDockerfile() .withDockerfileFromBuilder(builder -> { @@ -54,8 +52,10 @@ public class AuthenticatedImagePullTest { private final DockerImageName testImageName = authenticatedRegistry.createImage(); - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { + authenticatedRegistry.start(); + originalAuthLocatorSingleton = RegistryAuthLocator.instance(); String testRegistryAddress = authenticatedRegistry.getEndpoint(); @@ -77,13 +77,13 @@ public static void beforeClass() throws Exception { .thenReturn(authConfig); } - @AfterClass + @AfterAll public static void tearDown() { RegistryAuthLocator.setInstance(originalAuthLocatorSingleton); } @Test - public void testThatAuthLocatorIsUsedForContainerCreation() { + void testThatAuthLocatorIsUsedForContainerCreation() { // actually start a container, which will require an authenticated pull try ( final GenericContainer container = new GenericContainer<>(testImageName) @@ -96,7 +96,7 @@ public void testThatAuthLocatorIsUsedForContainerCreation() { } @Test - public void testThatAuthLocatorIsUsedForDockerfileBuild() throws IOException { + void testThatAuthLocatorIsUsedForDockerfileBuild() throws IOException { // Prepare a simple temporary Dockerfile which requires our custom private image Path tempFile = getLocalTempFile(".Dockerfile"); String dockerFileContent = "FROM " + testImageName.asCanonicalNameString(); @@ -116,7 +116,7 @@ public void testThatAuthLocatorIsUsedForDockerfileBuild() throws IOException { } @Test - public void testThatAuthLocatorIsUsedForDockerComposePull() throws IOException { + void testThatAuthLocatorIsUsedForDockerComposePull() throws IOException { // Prepare a simple temporary Docker Compose manifest which requires our custom private image Path tempFile = getLocalTempFile(".docker-compose.yml"); @Language("yaml") diff --git a/core/src/test/java/org/testcontainers/utility/ClasspathScannerTest.java b/core/src/test/java/org/testcontainers/utility/ClasspathScannerTest.java index e775a2cd492..63812c998e3 100644 --- a/core/src/test/java/org/testcontainers/utility/ClasspathScannerTest.java +++ b/core/src/test/java/org/testcontainers/utility/ClasspathScannerTest.java @@ -1,7 +1,7 @@ package org.testcontainers.utility; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.URL; @@ -15,7 +15,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ClasspathScannerTest { +class ClasspathScannerTest { private static URL FILE_A; @@ -27,7 +27,7 @@ public class ClasspathScannerTest { private static URL FILE_C; - @BeforeClass + @BeforeAll public static void setUp() throws Exception { FILE_A = new URL("file:///a/someName"); FILE_B = new URL("file:///b/someName"); @@ -37,7 +37,7 @@ public static void setUp() throws Exception { } @Test - public void realClassLoaderLookupOccurs() { + void realClassLoaderLookupOccurs() { // look for a resource that we know exists only once final List foundURLs = ClasspathScanner.scanFor("expectedClasspathFile.txt").collect(Collectors.toList()); @@ -45,7 +45,7 @@ public void realClassLoaderLookupOccurs() { } @Test - public void multipleResultsOnOneClassLoaderAreFound() throws IOException { + void multipleResultsOnOneClassLoaderAreFound() throws IOException { final ClassLoader firstMockClassLoader = mock(ClassLoader.class); when(firstMockClassLoader.getResources(eq("someName"))) .thenReturn(Collections.enumeration(Arrays.asList(FILE_A, FILE_B))); @@ -57,7 +57,7 @@ public void multipleResultsOnOneClassLoaderAreFound() throws IOException { } @Test - public void orderIsAlphabeticalForDeterminism() throws IOException { + void orderIsAlphabeticalForDeterminism() throws IOException { final ClassLoader firstMockClassLoader = mock(ClassLoader.class); when(firstMockClassLoader.getResources(eq("someName"))) .thenReturn(Collections.enumeration(Arrays.asList(FILE_B, JAR_A, JAR_B, FILE_A))); @@ -71,7 +71,7 @@ public void orderIsAlphabeticalForDeterminism() throws IOException { } @Test - public void multipleClassLoadersAreQueried() throws IOException { + void multipleClassLoadersAreQueried() throws IOException { final ClassLoader firstMockClassLoader = mock(ClassLoader.class); when(firstMockClassLoader.getResources(eq("someName"))) .thenReturn(Collections.enumeration(Arrays.asList(FILE_A, FILE_B))); diff --git a/core/src/test/java/org/testcontainers/utility/ComparableVersionTest.java b/core/src/test/java/org/testcontainers/utility/ComparableVersionTest.java index cd95d8a5f3d..dadf3983926 100644 --- a/core/src/test/java/org/testcontainers/utility/ComparableVersionTest.java +++ b/core/src/test/java/org/testcontainers/utility/ComparableVersionTest.java @@ -1,32 +1,20 @@ package org.testcontainers.utility; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) -public class ComparableVersionTest { +class ComparableVersionTest { - private final int[] expected; - - private final String given; - - public ComparableVersionTest(final String given, final int[] expected) { - this.given = given; - this.expected = expected; - } - - @Test - public void shouldParseVersions() { + @ParameterizedTest(name = "Parsed version: {0}={1}") + @MethodSource("data") + void shouldParseVersions(String given, int[] expected) { assertThat(ComparableVersion.parseVersion(given)).containsExactly(expected); } - @Parameters(name = "Parsed version: {0}={1}") public static Iterable data() { return Arrays.asList( new Object[][] { diff --git a/core/src/test/java/org/testcontainers/utility/DefaultImageNameSubstitutorTest.java b/core/src/test/java/org/testcontainers/utility/DefaultImageNameSubstitutorTest.java index 90f7745edd7..143455d5b16 100644 --- a/core/src/test/java/org/testcontainers/utility/DefaultImageNameSubstitutorTest.java +++ b/core/src/test/java/org/testcontainers/utility/DefaultImageNameSubstitutorTest.java @@ -1,14 +1,15 @@ package org.testcontainers.utility; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; -public class DefaultImageNameSubstitutorTest { +@ExtendWith(MockTestcontainersConfigurationExtension.class) +class DefaultImageNameSubstitutorTest { public static final DockerImageName ORIGINAL_IMAGE = DockerImageName.parse("foo"); @@ -16,16 +17,13 @@ public class DefaultImageNameSubstitutorTest { private ConfigurationFileImageNameSubstitutor underTest; - @Rule - public MockTestcontainersConfigurationRule config = new MockTestcontainersConfigurationRule(); - - @Before + @BeforeEach public void setUp() { underTest = new ConfigurationFileImageNameSubstitutor(TestcontainersConfiguration.getInstance()); } @Test - public void testConfigurationLookup() { + void testConfigurationLookup() { Mockito .doReturn(SUBSTITUTE_IMAGE) .when(TestcontainersConfiguration.getInstance()) diff --git a/core/src/test/java/org/testcontainers/utility/DirectoryTarResourceTest.java b/core/src/test/java/org/testcontainers/utility/DirectoryTarResourceTest.java index a56315085ae..bfd3641adeb 100644 --- a/core/src/test/java/org/testcontainers/utility/DirectoryTarResourceTest.java +++ b/core/src/test/java/org/testcontainers/utility/DirectoryTarResourceTest.java @@ -1,7 +1,7 @@ package org.testcontainers.utility; import org.assertj.core.api.Condition; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.startupcheck.OneShotStartupCheckStrategy; import org.testcontainers.images.builder.ImageFromDockerfile; @@ -11,10 +11,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class DirectoryTarResourceTest { +class DirectoryTarResourceTest { @Test - public void simpleRecursiveFileTest() { + void simpleRecursiveFileTest() { // 'src' is expected to be the project base directory, so all source code/resources should be copied in File directory = new File("src"); @@ -41,7 +41,7 @@ public void simpleRecursiveFileTest() { } @Test - public void simpleRecursiveFileWithPermissionTest() { + void simpleRecursiveFileWithPermissionTest() { try ( GenericContainer container = new GenericContainer( new ImageFromDockerfile() @@ -67,7 +67,7 @@ public void simpleRecursiveFileWithPermissionTest() { } @Test - public void simpleRecursiveClasspathResourceTest() { + void simpleRecursiveClasspathResourceTest() { // This test combines the copying of classpath resources from JAR files with the recursive TAR approach, to allow JARed classpath resources to be copied in to an image try ( diff --git a/core/src/test/java/org/testcontainers/utility/DockerImageNameCompatibilityTest.java b/core/src/test/java/org/testcontainers/utility/DockerImageNameCompatibilityTest.java index dd17981111f..dc7bf9ba1ab 100644 --- a/core/src/test/java/org/testcontainers/utility/DockerImageNameCompatibilityTest.java +++ b/core/src/test/java/org/testcontainers/utility/DockerImageNameCompatibilityTest.java @@ -1,21 +1,21 @@ package org.testcontainers.utility; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class DockerImageNameCompatibilityTest { +class DockerImageNameCompatibilityTest { @Test - public void testPlainImage() { + void testPlainImage() { DockerImageName subject = DockerImageName.parse("foo"); assertThat(subject.isCompatibleWith(DockerImageName.parse("bar"))).as("image name foo != bar").isFalse(); } @Test - public void testNoTagTreatedAsWildcard() { + void testNoTagTreatedAsWildcard() { final DockerImageName subject = DockerImageName.parse("foo:4.5.6"); /* foo:1.2.3 != foo:4.5.6 @@ -28,7 +28,7 @@ public void testNoTagTreatedAsWildcard() { } @Test - public void testImageWithAutomaticCompatibilityForFullPath() { + void testImageWithAutomaticCompatibilityForFullPath() { DockerImageName subject = DockerImageName.parse("repo/foo:1.2.3"); assertThat(subject.isCompatibleWith(DockerImageName.parse("repo/foo"))) @@ -37,7 +37,7 @@ public void testImageWithAutomaticCompatibilityForFullPath() { } @Test - public void testImageWithClaimedCompatibility() { + void testImageWithClaimedCompatibility() { DockerImageName subject = DockerImageName.parse("foo").asCompatibleSubstituteFor("bar"); assertThat(subject.isCompatibleWith(DockerImageName.parse("bar"))).as("foo(bar) ~= bar").isTrue(); @@ -45,14 +45,14 @@ public void testImageWithClaimedCompatibility() { } @Test - public void testImageWithClaimedCompatibilityAndVersion() { + void testImageWithClaimedCompatibilityAndVersion() { DockerImageName subject = DockerImageName.parse("foo:1.2.3").asCompatibleSubstituteFor("bar"); assertThat(subject.isCompatibleWith(DockerImageName.parse("bar"))).as("foo:1.2.3(bar) ~= bar").isTrue(); } @Test - public void testImageWithClaimedCompatibilityForFullPath() { + void testImageWithClaimedCompatibilityForFullPath() { DockerImageName subject = DockerImageName.parse("foo").asCompatibleSubstituteFor("registry/repo/bar"); assertThat(subject.isCompatibleWith(DockerImageName.parse("registry/repo/bar"))) @@ -67,7 +67,7 @@ public void testImageWithClaimedCompatibilityForFullPath() { } @Test - public void testImageWithClaimedCompatibilityForVersion() { + void testImageWithClaimedCompatibilityForVersion() { DockerImageName subject = DockerImageName.parse("foo").asCompatibleSubstituteFor("bar:1.2.3"); assertThat(subject.isCompatibleWith(DockerImageName.parse("bar"))).as("foo(bar:1.2.3) ~= bar").isTrue(); @@ -86,19 +86,19 @@ public void testImageWithClaimedCompatibilityForVersion() { } @Test - public void testAssertMethodAcceptsCompatible() { + void testAssertMethodAcceptsCompatible() { DockerImageName subject = DockerImageName.parse("foo").asCompatibleSubstituteFor("bar"); subject.assertCompatibleWith(DockerImageName.parse("bar")); } @Test - public void testAssertMethodAcceptsCompatibleLibraryPrefix() { + void testAssertMethodAcceptsCompatibleLibraryPrefix() { DockerImageName subject = DockerImageName.parse("library/foo"); subject.assertCompatibleWith(DockerImageName.parse("foo")); } @Test - public void testAssertMethodRejectsIncompatible() { + void testAssertMethodRejectsIncompatible() { DockerImageName subject = DockerImageName.parse("foo"); assertThatThrownBy(() -> subject.assertCompatibleWith(DockerImageName.parse("bar"))) .isInstanceOf(IllegalStateException.class) diff --git a/core/src/test/java/org/testcontainers/utility/DockerImageNameTest.java b/core/src/test/java/org/testcontainers/utility/DockerImageNameTest.java index b1a0cbc980f..7d6f8cd2633 100644 --- a/core/src/test/java/org/testcontainers/utility/DockerImageNameTest.java +++ b/core/src/test/java/org/testcontainers/utility/DockerImageNameTest.java @@ -1,19 +1,20 @@ package org.testcontainers.utility; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -@RunWith(Enclosed.class) -public class DockerImageNameTest { +class DockerImageNameTest { - @RunWith(Parameterized.class) - public static class ValidNames { + @Nested + class ValidNames { - @Parameterized.Parameters(name = "{0}") public static String[] getNames() { return new String[] { "myname:latest", @@ -30,19 +31,16 @@ public static String[] getNames() { }; } - @Parameterized.Parameter - public String imageName; - - @Test - public void testValidNameAccepted() { + @ParameterizedTest + @MethodSource("getNames") + void testValidNameAccepted(String imageName) { DockerImageName.parse(imageName).assertValid(); } } - @RunWith(Parameterized.class) - public static class InvalidNames { + @Nested + class InvalidNames { - @Parameterized.Parameters(name = "{0}") public static String[] getNames() { return new String[] { ":latest", @@ -53,62 +51,58 @@ public static String[] getNames() { }; } - @Parameterized.Parameter - public String imageName; - - @Test(expected = IllegalArgumentException.class) - public void testInvalidNameRejected() { - DockerImageName.parse(imageName).assertValid(); + @ParameterizedTest + @MethodSource("getNames") + void testInvalidNameRejected(String imageName) { + assertThatThrownBy(() -> DockerImageName.parse(imageName).assertValid()) + .isInstanceOf(IllegalArgumentException.class); } } - @RunWith(Parameterized.class) - public static class Parsing { - - @Parameterized.Parameters(name = "{0}{1}{2}{3}{4}") - public static String[][] getNames() { - return new String[][] { - { "", "", "myname", ":", null }, - { "", "", "myname", ":", "latest" }, - { "", "", "repo/myname", ":", null }, - { "", "", "repo/myname", ":", "latest" }, - { "registry.foo.com:1234", "/", "my-name", ":", null }, - { "registry.foo.com:1234", "/", "my-name", ":", "1.0" }, - { "registry.foo.com", "/", "my-name", ":", "1.0" }, - { "registry.foo.com:1234", "/", "repo_here/my-name", ":", null }, - { "registry.foo.com:1234", "/", "repo_here/my-name", ":", "1.0" }, - { "1.2.3.4:1234", "/", "repo_here/my-name", ":", null }, - { "1.2.3.4:1234", "/", "repo_here/my-name", ":", "1.0" }, - { "1.2.3.4:1234", "/", "my-name", ":", null }, - { "1.2.3.4:1234", "/", "my-name", ":", "1.0" }, - { "", "", "myname", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "", "", "repo/myname", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "registry.foo.com:1234", "/", "repo-here/my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "registry.foo.com:1234", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "1.2.3.4", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "1.2.3.4:1234", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "1.2.3.4", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - { "1.2.3.4:1234", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd" }, - }; + @Nested + class Parsing { + + public static Stream getNames() { + return Stream.of( + Arguments.of("", "", "myname", ":", null), + Arguments.of("", "", "myname", ":", "latest"), + Arguments.of("", "", "repo/myname", ":", null), + Arguments.of("", "", "repo/myname", ":", "latest"), + Arguments.of("registry.foo.com:1234", "/", "my-name", ":", null), + Arguments.of("registry.foo.com:1234", "/", "my-name", ":", "1.0"), + Arguments.of("registry.foo.com", "/", "my-name", ":", "1.0"), + Arguments.of("registry.foo.com:1234", "/", "repo_here/my-name", ":", null), + Arguments.of("registry.foo.com:1234", "/", "repo_here/my-name", ":", "1.0"), + Arguments.of("1.2.3.4:1234", "/", "repo_here/my-name", ":", null), + Arguments.of("1.2.3.4:1234", "/", "repo_here/my-name", ":", "1.0"), + Arguments.of("1.2.3.4:1234", "/", "my-name", ":", null), + Arguments.of("1.2.3.4:1234", "/", "my-name", ":", "1.0"), + Arguments.of("", "", "myname", "@", "sha256:1234abcd1234abcd1234abcd1234abcd"), + Arguments.of("", "", "repo/myname", "@", "sha256:1234abcd1234abcd1234abcd1234abcd"), + Arguments.of( + "registry.foo.com:1234", + "/", + "repo-here/my-name", + "@", + "sha256:1234abcd1234abcd1234abcd1234abcd" + ), + Arguments.of("registry.foo.com:1234", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd"), + Arguments.of("1.2.3.4", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd"), + Arguments.of("1.2.3.4:1234", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd"), + Arguments.of("1.2.3.4", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd"), + Arguments.of("1.2.3.4:1234", "/", "my-name", "@", "sha256:1234abcd1234abcd1234abcd1234abcd") + ); } - @Parameterized.Parameter(0) - public String registry; - - @Parameterized.Parameter(1) - public String registrySeparator; - - @Parameterized.Parameter(2) - public String repo; - - @Parameterized.Parameter(3) - public String versionSeparator; - - @Parameterized.Parameter(4) - public String version; - - @Test - public void testParsing() { + @ParameterizedTest + @MethodSource("getNames") + void testParsing( + String registry, + String registrySeparator, + String repo, + String versionSeparator, + String version + ) { final String unversionedPart = registry + registrySeparator + repo; String combined; diff --git a/core/src/test/java/org/testcontainers/utility/DockerLoggerFactoryTest.java b/core/src/test/java/org/testcontainers/utility/DockerLoggerFactoryTest.java index 17f0f3d7160..cf3352902ec 100644 --- a/core/src/test/java/org/testcontainers/utility/DockerLoggerFactoryTest.java +++ b/core/src/test/java/org/testcontainers/utility/DockerLoggerFactoryTest.java @@ -4,16 +4,16 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class DockerLoggerFactoryTest { +class DockerLoggerFactoryTest { private static final Logger LOGGER = (Logger) DockerLoggerFactory.getLogger("dockerImageName"); @Test - public void debugIsNotSwallowedForContainerLogs() { + void debugIsNotSwallowedForContainerLogs() { ListAppender listAppender = new ListAppender<>(); listAppender.start(); LOGGER.addAppender(listAppender); diff --git a/core/src/test/java/org/testcontainers/utility/DockerStatusTest.java b/core/src/test/java/org/testcontainers/utility/DockerStatusTest.java index 304bbc4190d..543cbdfeba1 100644 --- a/core/src/test/java/org/testcontainers/utility/DockerStatusTest.java +++ b/core/src/test/java/org/testcontainers/utility/DockerStatusTest.java @@ -1,26 +1,25 @@ package org.testcontainers.utility; import com.github.dockerjava.api.command.InspectContainerResponse; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -/** - * - */ -@RunWith(Parameterized.class) -public class DockerStatusTest { +@ParameterizedClass +@MethodSource("parameters") +class DockerStatusTest { - private final DateTimeFormatter dateTimeFormatter; + private DateTimeFormatter dateTimeFormatter; private static final Instant now = Instant.now(); @@ -52,16 +51,15 @@ public DockerStatusTest(DateTimeFormatter dateTimeFormatter) { paused = buildState(false, true, buildTimestamp(now.minusMillis(100)), DockerStatus.DOCKER_TIMESTAMP_ZERO); } - @Parameterized.Parameters - public static Object[][] parameters() { - return new Object[][] { - { DateTimeFormatter.ISO_INSTANT }, - { DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("America/New_York")) }, - }; + public static Stream parameters() { + return Stream.of( + DateTimeFormatter.ISO_INSTANT, + DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("America/New_York")) + ); } @Test - public void testRunning() throws Exception { + void testRunning() { assertThat(DockerStatus.isContainerRunning(running, minimumDuration, now)).isTrue(); assertThat(DockerStatus.isContainerRunning(runningVariant, minimumDuration, now)).isTrue(); assertThat(DockerStatus.isContainerRunning(shortRunning, minimumDuration, now)).isFalse(); @@ -72,7 +70,7 @@ public void testRunning() throws Exception { } @Test - public void testStopped() throws Exception { + void testStopped() { assertThat(DockerStatus.isContainerStopped(running)).isFalse(); assertThat(DockerStatus.isContainerStopped(runningVariant)).isFalse(); assertThat(DockerStatus.isContainerStopped(shortRunning)).isFalse(); diff --git a/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java b/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java index 2741edb5cee..af71e49664e 100644 --- a/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java +++ b/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java @@ -1,6 +1,6 @@ package org.testcontainers.utility; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.utility.ResourceReaper.FilterRegistry; import java.io.ByteArrayInputStream; @@ -15,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class FilterRegistryTest { +class FilterRegistryTest { private static final List> FILTERS = Arrays.asList( new SimpleEntry<>("key1!", "value2?"), @@ -31,7 +31,7 @@ public class FilterRegistryTest { private static final String NEW_LINE = "\n"; @Test - public void registerReturnsTrueIfAcknowledgementIsReadFromInputStream() throws IOException { + void registerReturnsTrueIfAcknowledgementIsReadFromInputStream() throws IOException { FilterRegistry registry = new FilterRegistry(inputStream(ACKNOWLEDGEMENT), anyOutputStream()); boolean successful = registry.register(FILTERS); @@ -40,7 +40,7 @@ public void registerReturnsTrueIfAcknowledgementIsReadFromInputStream() throws I } @Test - public void registerReturnsFalseIfNoAcknowledgementIsReadFromInputStream() throws IOException { + void registerReturnsFalseIfNoAcknowledgementIsReadFromInputStream() throws IOException { FilterRegistry registry = new FilterRegistry(inputStream(NO_ACKNOWLEDGEMENT), anyOutputStream()); boolean successful = registry.register(FILTERS); @@ -49,7 +49,7 @@ public void registerReturnsFalseIfNoAcknowledgementIsReadFromInputStream() throw } @Test - public void registerWritesUrlEncodedFiltersAndNewlineToOutputStream() throws IOException { + void registerWritesUrlEncodedFiltersAndNewlineToOutputStream() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); FilterRegistry registry = new FilterRegistry(anyInputStream(), outputStream); diff --git a/core/src/test/java/org/testcontainers/utility/ImageNameSubstitutorTest.java b/core/src/test/java/org/testcontainers/utility/ImageNameSubstitutorTest.java index 6c29e26c58f..e6a0c294c77 100644 --- a/core/src/test/java/org/testcontainers/utility/ImageNameSubstitutorTest.java +++ b/core/src/test/java/org/testcontainers/utility/ImageNameSubstitutorTest.java @@ -1,10 +1,10 @@ package org.testcontainers.utility; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; import org.testcontainers.containers.GenericContainer; @@ -20,19 +20,17 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; -public class ImageNameSubstitutorTest { +@ExtendWith(MockTestcontainersConfigurationExtension.class) +class ImageNameSubstitutorTest { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - public MockTestcontainersConfigurationRule config = new MockTestcontainersConfigurationRule(); + @TempDir + public Path tempFolder; private ImageNameSubstitutor originalInstance; private ImageNameSubstitutor originalDefaultImplementation; - @Before + @BeforeEach public void setUp() throws Exception { originalInstance = ImageNameSubstitutor.instance; originalDefaultImplementation = ImageNameSubstitutor.defaultImplementation; @@ -46,14 +44,14 @@ public void setUp() throws Exception { Mockito.doReturn("default implementation").when(ImageNameSubstitutor.defaultImplementation).getDescription(); } - @After + @AfterEach public void tearDown() throws Exception { ImageNameSubstitutor.instance = originalInstance; ImageNameSubstitutor.defaultImplementation = originalDefaultImplementation; } @Test - public void simpleConfigurationTest() { + void simpleConfigurationTest() { Mockito .doReturn(FakeImageSubstitutor.class.getCanonicalName()) .when(TestcontainersConfiguration.getInstance()) @@ -68,7 +66,7 @@ public void simpleConfigurationTest() { } @Test - public void testWorksWithoutConfiguredImplementation() { + void testWorksWithoutConfiguredImplementation() { Mockito.doReturn(null).when(TestcontainersConfiguration.getInstance()).getImageSubstitutorClassName(); final ImageNameSubstitutor imageNameSubstitutor = ImageNameSubstitutor.instance(); @@ -80,7 +78,7 @@ public void testWorksWithoutConfiguredImplementation() { } @Test - public void testImageNameSubstitutorToString() { + void testImageNameSubstitutorToString() { Mockito .doReturn(FakeImageSubstitutor.class.getCanonicalName()) .when(TestcontainersConfiguration.getInstance()) @@ -95,8 +93,8 @@ public void testImageNameSubstitutorToString() { } @Test - public void testImageNameSubstitutorFromServiceLoader() throws IOException { - Path tempDir = this.tempFolder.newFolder("image-name-substitutor-test").toPath(); + void testImageNameSubstitutorFromServiceLoader() throws IOException { + Path tempDir = this.tempFolder.resolve("image-name-substitutor-test"); Path metaInfDir = Paths.get(tempDir.toString(), "META-INF", "services"); Files.createDirectories(metaInfDir); diff --git a/core/src/test/java/org/testcontainers/utility/LazyFutureTest.java b/core/src/test/java/org/testcontainers/utility/LazyFutureTest.java index 822109ff9cd..afc78076b43 100644 --- a/core/src/test/java/org/testcontainers/utility/LazyFutureTest.java +++ b/core/src/test/java/org/testcontainers/utility/LazyFutureTest.java @@ -2,7 +2,8 @@ import com.google.common.util.concurrent.Futures; import lombok.SneakyThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.util.Collections; import java.util.List; @@ -18,10 +19,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; -public class LazyFutureTest { +class LazyFutureTest { @Test - public void testLaziness() throws Exception { + void testLaziness() throws Exception { AtomicInteger counter = new AtomicInteger(); Future lazyFuture = new LazyFuture() { @@ -39,8 +40,9 @@ protected Integer resolve() { assertThat(lazyFuture.get()).as("result of resolve() must be cached").isEqualTo(1); } - @Test(timeout = 5_000) - public void timeoutWorks() { + @Test + @Timeout(5) + void timeoutWorks() { Future lazyFuture = new LazyFuture() { @Override @SneakyThrows(InterruptedException.class) @@ -55,8 +57,9 @@ protected Void resolve() { .isInstanceOf(TimeoutException.class); } - @Test(timeout = 5_000) - public void testThreadSafety() throws Exception { + @Test + @Timeout(5) + void testThreadSafety() throws Exception { final int numOfThreads = 3; CountDownLatch latch = new CountDownLatch(numOfThreads); AtomicInteger counter = new AtomicInteger(); diff --git a/core/src/test/java/org/testcontainers/utility/LicenseAcceptanceTest.java b/core/src/test/java/org/testcontainers/utility/LicenseAcceptanceTest.java index 63da017c88e..c0ca63c06bc 100644 --- a/core/src/test/java/org/testcontainers/utility/LicenseAcceptanceTest.java +++ b/core/src/test/java/org/testcontainers/utility/LicenseAcceptanceTest.java @@ -1,17 +1,20 @@ package org.testcontainers.utility; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LicenseAcceptanceTest { +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class LicenseAcceptanceTest { @Test - public void testForExistingNames() { + void testForExistingNames() { LicenseAcceptance.assertLicenseAccepted("a"); LicenseAcceptance.assertLicenseAccepted("b"); } - @Test(expected = IllegalStateException.class) - public void testForMissingNames() { - LicenseAcceptance.assertLicenseAccepted("c"); + @Test + void testForMissingNames() { + assertThatThrownBy(() -> LicenseAcceptance.assertLicenseAccepted("c")) + .isInstanceOf(IllegalStateException.class); } } diff --git a/core/src/test/java/org/testcontainers/utility/MockTestcontainersConfigurationExtension.java b/core/src/test/java/org/testcontainers/utility/MockTestcontainersConfigurationExtension.java new file mode 100644 index 00000000000..a94e6b7772e --- /dev/null +++ b/core/src/test/java/org/testcontainers/utility/MockTestcontainersConfigurationExtension.java @@ -0,0 +1,39 @@ +package org.testcontainers.utility; + +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.mockito.Mockito; + +import java.util.concurrent.atomic.AtomicReference; + +/** + * This {@link org.junit.jupiter.api.extension.Extension} applies a spy on {@link TestcontainersConfiguration} + * for testing features that depend on the global configuration. + */ +public class MockTestcontainersConfigurationExtension implements BeforeEachCallback, AfterEachCallback { + + private static final ExtensionContext.Namespace NS = ExtensionContext.Namespace.create( + MockTestcontainersConfigurationExtension.class + ); + + static AtomicReference REF = TestcontainersConfiguration.getInstanceField(); + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + TestcontainersConfiguration previous = REF.get(); + if (previous == null) { + previous = TestcontainersConfiguration.getInstance(); + } + REF.set(Mockito.spy(previous)); + context.getStore(NS).put(context.getUniqueId(), previous); + } + + @Override + public void afterEach(ExtensionContext context) throws Exception { + TestcontainersConfiguration previous = context + .getStore(NS) + .remove(context.getUniqueId(), TestcontainersConfiguration.class); + REF.set(previous); + } +} diff --git a/core/src/test/java/org/testcontainers/utility/MockTestcontainersConfigurationRule.java b/core/src/test/java/org/testcontainers/utility/MockTestcontainersConfigurationRule.java deleted file mode 100644 index ba467f13897..00000000000 --- a/core/src/test/java/org/testcontainers/utility/MockTestcontainersConfigurationRule.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.testcontainers.utility; - -import org.jetbrains.annotations.NotNull; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; -import org.mockito.Mockito; - -import java.util.concurrent.atomic.AtomicReference; - -/** - * This {@link TestRule} applies a spy on {@link TestcontainersConfiguration} - * for testing features that depend on the global configuration. - */ -public class MockTestcontainersConfigurationRule implements TestRule { - - static AtomicReference REF = TestcontainersConfiguration.getInstanceField(); - - @NotNull - @Override - public Statement apply(@NotNull Statement base, @NotNull Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - TestcontainersConfiguration previous = REF.get(); - if (previous == null) { - previous = TestcontainersConfiguration.getInstance(); - } - REF.set(Mockito.spy(previous)); - - try { - base.evaluate(); - } finally { - REF.set(previous); - } - } - }; - } -} diff --git a/core/src/test/java/org/testcontainers/utility/MountableFileTest.java b/core/src/test/java/org/testcontainers/utility/MountableFileTest.java index fbfb537ef87..72db429c263 100644 --- a/core/src/test/java/org/testcontainers/utility/MountableFileTest.java +++ b/core/src/test/java/org/testcontainers/utility/MountableFileTest.java @@ -5,7 +5,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.jetbrains.annotations.NotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -17,7 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class MountableFileTest { +class MountableFileTest { private static final int TEST_FILE_MODE = 0532; @@ -26,35 +26,35 @@ public class MountableFileTest { private static final int BASE_DIR_MODE = 0040000; @Test - public void forClasspathResource() throws Exception { + void forClasspathResource() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("mappable-resource/test-resource.txt"); performChecks(mountableFile); } @Test - public void forClasspathResourceWithAbsolutePath() throws Exception { + void forClasspathResourceWithAbsolutePath() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("/mappable-resource/test-resource.txt"); performChecks(mountableFile); } @Test - public void forClasspathResourceFromJar() throws Exception { + void forClasspathResourceFromJar() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("META-INF/dummy_unique_name.txt"); performChecks(mountableFile); } @Test - public void forClasspathResourceFromJarWithAbsolutePath() throws Exception { + void forClasspathResourceFromJarWithAbsolutePath() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("/META-INF/dummy_unique_name.txt"); performChecks(mountableFile); } @Test - public void forHostPath() throws Exception { + void forHostPath() throws Exception { final Path file = createTempFile("somepath"); final MountableFile mountableFile = MountableFile.forHostPath(file.toString()); @@ -62,7 +62,7 @@ public void forHostPath() throws Exception { } @Test - public void forHostPathWithSpaces() throws Exception { + void forHostPathWithSpaces() throws Exception { final Path file = createTempFile("some path"); final MountableFile mountableFile = MountableFile.forHostPath(file.toString()); @@ -75,7 +75,7 @@ public void forHostPathWithSpaces() throws Exception { } @Test - public void forHostPathWithPlus() throws Exception { + void forHostPathWithPlus() throws Exception { final Path file = createTempFile("some+path"); final MountableFile mountableFile = MountableFile.forHostPath(file.toString()); @@ -88,7 +88,7 @@ public void forHostPathWithPlus() throws Exception { } @Test - public void forClasspathResourceWithPermission() throws Exception { + void forClasspathResourceWithPermission() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource( "mappable-resource/test-resource.txt", TEST_FILE_MODE @@ -99,7 +99,7 @@ public void forClasspathResourceWithPermission() throws Exception { } @Test - public void forHostFilePathWithPermission() throws Exception { + void forHostFilePathWithPermission() throws Exception { final Path file = createTempFile("somepath"); final MountableFile mountableFile = MountableFile.forHostPath(file.toString(), TEST_FILE_MODE); performChecks(mountableFile); @@ -107,7 +107,7 @@ public void forHostFilePathWithPermission() throws Exception { } @Test - public void forHostDirPathWithPermission() throws Exception { + void forHostDirPathWithPermission() throws Exception { final Path dir = createTempDir(); final MountableFile mountableFile = MountableFile.forHostPath(dir.toString(), TEST_FILE_MODE); performChecks(mountableFile); @@ -115,7 +115,7 @@ public void forHostDirPathWithPermission() throws Exception { } @Test - public void noTrailingSlashesInTarEntryNames() throws Exception { + void noTrailingSlashesInTarEntryNames() throws Exception { final MountableFile mountableFile = MountableFile.forClasspathResource("mappable-resource/test-resource.txt"); @Cleanup diff --git a/core/src/test/java/org/testcontainers/utility/PrefixingImageNameSubstitutorTest.java b/core/src/test/java/org/testcontainers/utility/PrefixingImageNameSubstitutorTest.java index 04786119e36..6eb6c62905c 100644 --- a/core/src/test/java/org/testcontainers/utility/PrefixingImageNameSubstitutorTest.java +++ b/core/src/test/java/org/testcontainers/utility/PrefixingImageNameSubstitutorTest.java @@ -1,7 +1,7 @@ package org.testcontainers.utility; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -9,20 +9,20 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class PrefixingImageNameSubstitutorTest { +class PrefixingImageNameSubstitutorTest { private TestcontainersConfiguration mockConfiguration; private PrefixingImageNameSubstitutor underTest; - @Before + @BeforeEach public void setUp() { mockConfiguration = mock(TestcontainersConfiguration.class); underTest = new PrefixingImageNameSubstitutor(mockConfiguration); } @Test - public void testHappyPath() { + void testHappyPath() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/our-mirror/"); @@ -34,7 +34,7 @@ public void testHappyPath() { } @Test - public void hubIoRegistryIsNotChanged() { + void hubIoRegistryIsNotChanged() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/our-mirror/"); @@ -44,7 +44,7 @@ public void hubIoRegistryIsNotChanged() { } @Test - public void hubComRegistryIsNotChanged() { + void hubComRegistryIsNotChanged() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/our-mirror/"); @@ -56,7 +56,7 @@ public void hubComRegistryIsNotChanged() { } @Test - public void thirdPartyRegistriesNotAffected() { + void thirdPartyRegistriesNotAffected() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/our-mirror/"); @@ -68,7 +68,7 @@ public void thirdPartyRegistriesNotAffected() { } @Test - public void testNoDoublePrefixing() { + void testNoDoublePrefixing() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/our-mirror/"); @@ -80,7 +80,7 @@ public void testNoDoublePrefixing() { } @Test - public void testHandlesEmptyValue() { + void testHandlesEmptyValue() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn(""); @@ -92,7 +92,7 @@ public void testHandlesEmptyValue() { } @Test - public void testHandlesRegistryOnlyWithTrailingSlash() { + void testHandlesRegistryOnlyWithTrailingSlash() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/"); @@ -104,7 +104,7 @@ public void testHandlesRegistryOnlyWithTrailingSlash() { } @Test - public void testCombinesLiterallyForRegistryOnlyWithoutTrailingSlash() { + void testCombinesLiterallyForRegistryOnlyWithoutTrailingSlash() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com"); @@ -116,7 +116,7 @@ public void testCombinesLiterallyForRegistryOnlyWithoutTrailingSlash() { } @Test - public void testCombinesLiterallyForBothPartsWithoutTrailingSlash() { + void testCombinesLiterallyForBothPartsWithoutTrailingSlash() { when(mockConfiguration.getEnvVarOrProperty(eq(PrefixingImageNameSubstitutor.PREFIX_PROPERTY_KEY), any())) .thenReturn("someregistry.com/our-mirror"); diff --git a/core/src/test/java/org/testcontainers/utility/RegistryAuthLocatorTest.java b/core/src/test/java/org/testcontainers/utility/RegistryAuthLocatorTest.java index ed986b05015..6988cfd86a8 100644 --- a/core/src/test/java/org/testcontainers/utility/RegistryAuthLocatorTest.java +++ b/core/src/test/java/org/testcontainers/utility/RegistryAuthLocatorTest.java @@ -5,7 +5,7 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.jetbrains.annotations.NotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -17,10 +17,10 @@ import static org.assertj.core.api.Assertions.assertThat; -public class RegistryAuthLocatorTest { +class RegistryAuthLocatorTest { @Test - public void lookupAuthConfigWithoutCredentials() throws URISyntaxException, IOException { + void lookupAuthConfigWithoutCredentials() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-empty.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -36,7 +36,7 @@ public void lookupAuthConfigWithoutCredentials() throws URISyntaxException, IOEx } @Test - public void lookupAuthConfigWithBasicAuthCredentials() throws URISyntaxException, IOException { + void lookupAuthConfigWithBasicAuthCredentials() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-basic-auth.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -52,7 +52,7 @@ public void lookupAuthConfigWithBasicAuthCredentials() throws URISyntaxException } @Test - public void lookupAuthConfigWithJsonKeyCredentials() throws URISyntaxException, IOException { + void lookupAuthConfigWithJsonKeyCredentials() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-json-key.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -68,8 +68,7 @@ public void lookupAuthConfigWithJsonKeyCredentials() throws URISyntaxException, } @Test - public void lookupAuthConfigWithJsonKeyCredentialsPartialMatchShouldGiveNoResult() - throws URISyntaxException, IOException { + void lookupAuthConfigWithJsonKeyCredentialsPartialMatchShouldGiveNoResult() throws URISyntaxException, IOException { // contains entry for registry.example.com final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-json-key.json"); @@ -83,7 +82,7 @@ public void lookupAuthConfigWithJsonKeyCredentialsPartialMatchShouldGiveNoResult } @Test - public void lookupAuthConfigUsingStore() throws URISyntaxException, IOException { + void lookupAuthConfigUsingStore() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-store.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -103,7 +102,7 @@ public void lookupAuthConfigUsingStore() throws URISyntaxException, IOException } @Test - public void lookupAuthConfigUsingHelper() throws URISyntaxException, IOException { + void lookupAuthConfigUsingHelper() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-helper.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -123,7 +122,7 @@ public void lookupAuthConfigUsingHelper() throws URISyntaxException, IOException } @Test - public void lookupAuthConfigUsingHelperWithToken() throws URISyntaxException, IOException { + void lookupAuthConfigUsingHelperWithToken() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-helper-using-token.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -140,7 +139,7 @@ public void lookupAuthConfigUsingHelperWithToken() throws URISyntaxException, IO } @Test - public void lookupUsingHelperEmptyAuth() throws URISyntaxException, IOException { + void lookupUsingHelperEmptyAuth() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-empty-auth-with-helper.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -160,7 +159,7 @@ public void lookupUsingHelperEmptyAuth() throws URISyntaxException, IOException } @Test - public void lookupNonEmptyAuthWithHelper() throws URISyntaxException, IOException { + void lookupNonEmptyAuthWithHelper() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-existing-auth-with-helper.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -180,7 +179,7 @@ public void lookupNonEmptyAuthWithHelper() throws URISyntaxException, IOExceptio } @Test - public void lookupAuthConfigUsingHelperNoServerUrl() throws URISyntaxException, IOException { + void lookupAuthConfigUsingHelperNoServerUrl() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-helper-no-server-url.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -200,7 +199,7 @@ public void lookupAuthConfigUsingHelperNoServerUrl() throws URISyntaxException, } @Test - public void lookupAuthConfigUsingHelperNoServerUrlWithToken() throws URISyntaxException, IOException { + void lookupAuthConfigUsingHelperNoServerUrlWithToken() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator( "config-with-helper-no-server-url-using-token.json" ); @@ -219,7 +218,7 @@ public void lookupAuthConfigUsingHelperNoServerUrlWithToken() throws URISyntaxEx } @Test - public void lookupAuthConfigWithCredentialsNotFound() throws URISyntaxException, IOException { + void lookupAuthConfigWithCredentialsNotFound() throws URISyntaxException, IOException { Map notFoundMessagesReference = new HashMap<>(); final RegistryAuthLocator authLocator = createTestAuthLocator( "config-with-store.json", @@ -245,7 +244,7 @@ public void lookupAuthConfigWithCredentialsNotFound() throws URISyntaxException, } @Test - public void lookupAuthConfigWithCredStoreEmpty() throws URISyntaxException, IOException { + void lookupAuthConfigWithCredStoreEmpty() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-with-store-empty.json"); DockerImageName dockerImageName = DockerImageName.parse("registry2.example.com/org/repo"); @@ -255,7 +254,7 @@ public void lookupAuthConfigWithCredStoreEmpty() throws URISyntaxException, IOEx } @Test - public void lookupAuthConfigFromEnvVarWithCredStoreEmpty() throws URISyntaxException, IOException { + void lookupAuthConfigFromEnvVarWithCredStoreEmpty() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator(null, "config-with-store-empty.json"); DockerImageName dockerImageName = DockerImageName.parse("registry2.example.com/org/repo"); @@ -265,7 +264,7 @@ public void lookupAuthConfigFromEnvVarWithCredStoreEmpty() throws URISyntaxExcep } @Test - public void lookupAuthConfigWithoutConfigFile() throws URISyntaxException, IOException { + void lookupAuthConfigWithoutConfigFile() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator(null); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -281,7 +280,7 @@ public void lookupAuthConfigWithoutConfigFile() throws URISyntaxException, IOExc } @Test - public void lookupAuthConfigRespectsCheckOrderPreference() throws URISyntaxException, IOException { + void lookupAuthConfigRespectsCheckOrderPreference() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator("config-empty.json", "config-basic-auth.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( @@ -297,7 +296,7 @@ public void lookupAuthConfigRespectsCheckOrderPreference() throws URISyntaxExcep } @Test - public void lookupAuthConfigFromEnvironmentVariable() throws URISyntaxException, IOException { + void lookupAuthConfigFromEnvironmentVariable() throws URISyntaxException, IOException { final RegistryAuthLocator authLocator = createTestAuthLocator(null, "config-basic-auth.json"); final AuthConfig authConfig = authLocator.lookupAuthConfig( diff --git a/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java b/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java index 77c5d528ba4..7b0c463d056 100644 --- a/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java +++ b/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java @@ -5,7 +5,7 @@ import lombok.SneakyThrows; import org.awaitility.Awaitility; import org.awaitility.core.ConditionFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.GenericContainer; import org.zeroturnaround.exec.ProcessExecutor; @@ -21,17 +21,17 @@ import static org.assertj.core.api.Assertions.assertThat; -public class ResourceReaperTest { +class ResourceReaperTest { @Test - public void shouldCleanupWithRyuk() { + void shouldCleanupWithRyuk() { Map labels = runProcess(processExecutor -> {}); assertCleanup(labels); } @Test - public void shouldCleanupWithJVM() { + void shouldCleanupWithJVM() { Map labels = runProcess(processExecutor -> { processExecutor.environment("TESTCONTAINERS_RYUK_DISABLED", "true"); }); diff --git a/core/src/test/java/org/testcontainers/utility/TestEnvironmentTest.java b/core/src/test/java/org/testcontainers/utility/TestEnvironmentTest.java index 4bd9e1b8edb..874f623cc08 100644 --- a/core/src/test/java/org/testcontainers/utility/TestEnvironmentTest.java +++ b/core/src/test/java/org/testcontainers/utility/TestEnvironmentTest.java @@ -1,37 +1,37 @@ package org.testcontainers.utility; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Created by rnorth on 03/07/2016. */ -public class TestEnvironmentTest { +class TestEnvironmentTest { @Test - public void testCompareVersionGreaterThanSameMajor() { + void testCompareVersionGreaterThanSameMajor() { assertThat(new ComparableVersion("1.22").compareTo(new ComparableVersion("1.20")) > 0) .as("1.22 > 1.20") .isTrue(); } @Test - public void testCompareVersionEqual() { + void testCompareVersionEqual() { assertThat(new ComparableVersion("1.20")) .as("1.20 == 1.20") .isEqualByComparingTo(new ComparableVersion("1.20")); } @Test - public void testCompareVersionGreaterThan() { + void testCompareVersionGreaterThan() { assertThat(new ComparableVersion("2.10").compareTo(new ComparableVersion("1.20")) > 0) .as("2.10 > 1.20") .isTrue(); } @Test - public void testCompareVersionIgnoresExcessLength() { + void testCompareVersionIgnoresExcessLength() { assertThat(new ComparableVersion("1.20")) .as("1.20 == 1.20.3") .isEqualByComparingTo(new ComparableVersion("1.20.3")); diff --git a/core/src/test/java/org/testcontainers/utility/TestcontainersConfigurationTest.java b/core/src/test/java/org/testcontainers/utility/TestcontainersConfigurationTest.java index fcc0a654ef5..4e0520af5ba 100644 --- a/core/src/test/java/org/testcontainers/utility/TestcontainersConfigurationTest.java +++ b/core/src/test/java/org/testcontainers/utility/TestcontainersConfigurationTest.java @@ -1,7 +1,7 @@ package org.testcontainers.utility; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -10,7 +10,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class TestcontainersConfigurationTest { +class TestcontainersConfigurationTest { private Properties userProperties; @@ -18,7 +18,7 @@ public class TestcontainersConfigurationTest { private Map environment; - @Before + @BeforeEach public void setUp() { userProperties = new Properties(); classpathProperties = new Properties(); @@ -26,7 +26,7 @@ public void setUp() { } @Test - public void shouldSubstituteImageNamesFromClasspathProperties() { + void shouldSubstituteImageNamesFromClasspathProperties() { classpathProperties.setProperty("ryuk.container.image", "foo:version"); assertThat(newConfig().getConfiguredSubstituteImage(DockerImageName.parse("testcontainers/ryuk:any"))) .as("an image name can be pulled from classpath properties") @@ -34,7 +34,7 @@ public void shouldSubstituteImageNamesFromClasspathProperties() { } @Test - public void shouldSubstituteImageNamesFromUserProperties() { + void shouldSubstituteImageNamesFromUserProperties() { userProperties.setProperty("ryuk.container.image", "foo:version"); assertThat(newConfig().getConfiguredSubstituteImage(DockerImageName.parse("testcontainers/ryuk:any"))) .as("an image name can be pulled from user properties") @@ -42,7 +42,7 @@ public void shouldSubstituteImageNamesFromUserProperties() { } @Test - public void shouldSubstituteImageNamesFromEnvironmentVariables() { + void shouldSubstituteImageNamesFromEnvironmentVariables() { environment.put("TESTCONTAINERS_RYUK_CONTAINER_IMAGE", "foo:version"); assertThat(newConfig().getConfiguredSubstituteImage(DockerImageName.parse("testcontainers/ryuk:any"))) .as("an image name can be pulled from an environment variable") @@ -50,7 +50,7 @@ public void shouldSubstituteImageNamesFromEnvironmentVariables() { } @Test - public void shouldApplySettingsInOrder() { + void shouldApplySettingsInOrder() { assertThat(newConfig().getEnvVarOrProperty("key", "default")) .as("precedence order for multiple sources of the same value is correct") .isEqualTo("default"); @@ -75,7 +75,7 @@ public void shouldApplySettingsInOrder() { } @Test - public void shouldNotReadChecksFromClasspathProperties() { + void shouldNotReadChecksFromClasspathProperties() { assertThat(newConfig().isDisableChecks()).as("checks enabled by default").isFalse(); classpathProperties.setProperty("checks.disable", "true"); @@ -83,7 +83,7 @@ public void shouldNotReadChecksFromClasspathProperties() { } @Test - public void shouldReadChecksFromUserProperties() { + void shouldReadChecksFromUserProperties() { assertThat(newConfig().isDisableChecks()).as("checks enabled by default").isFalse(); userProperties.setProperty("checks.disable", "true"); @@ -91,7 +91,7 @@ public void shouldReadChecksFromUserProperties() { } @Test - public void shouldReadChecksFromEnvironment() { + void shouldReadChecksFromEnvironment() { assertThat(newConfig().isDisableChecks()).as("checks enabled by default").isFalse(); userProperties.remove("checks.disable"); @@ -100,7 +100,7 @@ public void shouldReadChecksFromEnvironment() { } @Test - public void shouldReadDockerSettingsFromEnvironmentWithoutTestcontainersPrefix() { + void shouldReadDockerSettingsFromEnvironmentWithoutTestcontainersPrefix() { userProperties.remove("docker.foo"); environment.put("DOCKER_FOO", "some value"); assertThat(newConfig().getEnvVarOrUserProperty("docker.foo", "default")) @@ -109,7 +109,7 @@ public void shouldReadDockerSettingsFromEnvironmentWithoutTestcontainersPrefix() } @Test - public void shouldNotReadDockerSettingsFromEnvironmentWithTestcontainersPrefix() { + void shouldNotReadDockerSettingsFromEnvironmentWithTestcontainersPrefix() { userProperties.remove("docker.foo"); environment.put("TESTCONTAINERS_DOCKER_FOO", "some value"); assertThat(newConfig().getEnvVarOrUserProperty("docker.foo", "default")) @@ -118,7 +118,7 @@ public void shouldNotReadDockerSettingsFromEnvironmentWithTestcontainersPrefix() } @Test - public void shouldReadDockerSettingsFromUserProperties() { + void shouldReadDockerSettingsFromUserProperties() { environment.remove("DOCKER_FOO"); userProperties.put("docker.foo", "some value"); assertThat(newConfig().getEnvVarOrUserProperty("docker.foo", "default")) @@ -127,7 +127,7 @@ public void shouldReadDockerSettingsFromUserProperties() { } @Test - public void shouldNotReadSettingIfCorrespondingEnvironmentVarIsEmptyString() { + void shouldNotReadSettingIfCorrespondingEnvironmentVarIsEmptyString() { environment.put("DOCKER_FOO", ""); assertThat(newConfig().getEnvVarOrUserProperty("docker.foo", "default")) .as("reads unprefixed env vars for docker. settings") @@ -135,7 +135,7 @@ public void shouldNotReadSettingIfCorrespondingEnvironmentVarIsEmptyString() { } @Test - public void shouldNotReadDockerClientStrategyFromClasspathProperties() { + void shouldNotReadDockerClientStrategyFromClasspathProperties() { String currentValue = newConfig().getDockerClientStrategyClassName(); classpathProperties.setProperty("docker.client.strategy", UUID.randomUUID().toString()); @@ -145,7 +145,7 @@ public void shouldNotReadDockerClientStrategyFromClasspathProperties() { } @Test - public void shouldReadDockerClientStrategyFromUserProperties() { + void shouldReadDockerClientStrategyFromUserProperties() { userProperties.setProperty("docker.client.strategy", "foo"); assertThat(newConfig().getDockerClientStrategyClassName()) .as("Docker client strategy is changed by user property") @@ -153,7 +153,7 @@ public void shouldReadDockerClientStrategyFromUserProperties() { } @Test - public void shouldReadDockerClientStrategyFromEnvironment() { + void shouldReadDockerClientStrategyFromEnvironment() { userProperties.remove("docker.client.strategy"); environment.put("TESTCONTAINERS_DOCKER_CLIENT_STRATEGY", "foo"); assertThat(newConfig().getDockerClientStrategyClassName()) @@ -162,7 +162,7 @@ public void shouldReadDockerClientStrategyFromEnvironment() { } @Test - public void shouldNotUseImplicitDockerClientStrategyWhenDockerHostAndStrategyAreBothSet() { + void shouldNotUseImplicitDockerClientStrategyWhenDockerHostAndStrategyAreBothSet() { userProperties.put("docker.client.strategy", "foo"); userProperties.put("docker.host", "tcp://1.2.3.4:5678"); assertThat(newConfig().getDockerClientStrategyClassName()) @@ -191,7 +191,7 @@ public void shouldNotUseImplicitDockerClientStrategyWhenDockerHostAndStrategyAre } @Test - public void shouldNotReadReuseFromClasspathProperties() { + void shouldNotReadReuseFromClasspathProperties() { assertThat(newConfig().environmentSupportsReuse()).as("no reuse by default").isFalse(); classpathProperties.setProperty("testcontainers.reuse.enable", "true"); @@ -201,7 +201,7 @@ public void shouldNotReadReuseFromClasspathProperties() { } @Test - public void shouldReadReuseFromUserProperties() { + void shouldReadReuseFromUserProperties() { assertThat(newConfig().environmentSupportsReuse()).as("no reuse by default").isFalse(); userProperties.setProperty("testcontainers.reuse.enable", "true"); @@ -209,7 +209,7 @@ public void shouldReadReuseFromUserProperties() { } @Test - public void shouldReadReuseFromEnvironment() { + void shouldReadReuseFromEnvironment() { assertThat(newConfig().environmentSupportsReuse()).as("no reuse by default").isFalse(); userProperties.remove("testcontainers.reuse.enable"); @@ -218,7 +218,7 @@ public void shouldReadReuseFromEnvironment() { } @Test - public void shouldTrimImageNames() { + void shouldTrimImageNames() { userProperties.setProperty("ryuk.container.image", " testcontainers/ryuk:0.3.2 "); assertThat(newConfig().getRyukImage()) .as("trailing whitespace was not removed from image name property")