From b78c65f7dde1430a230100702b79318e55a5153d Mon Sep 17 00:00:00 2001 From: Wallace Wadge Date: Tue, 11 Jul 2023 22:41:22 +0200 Subject: [PATCH] Fix Gradle deprecations (#3892) Co-authored-by: Clayton Walker Co-authored-by: Emily Wang --- build.gradle | 86 +++-- config/checkstyle/checkstyle-suppressions.xml | 8 + gradle.properties | 1 + gradle/wrapper/gradle-wrapper.jar | Bin 55190 -> 62076 bytes gradle/wrapper/gradle-wrapper.properties | 3 +- gradlew | 295 +++++++++++------- gradlew.bat | 56 ++-- jib-build-plan/build.gradle | 5 +- .../tools/jib/api/buildplan/LayerObject.java | 1 + .../api/buildplan/AbsoluteUnixPathTest.java | 22 +- .../api/buildplan/ContainerBuildPlanTest.java | 14 +- .../api/buildplan/FileEntriesLayerTest.java | 9 +- .../jib/api/buildplan/FileEntryTest.java | 7 +- .../api/buildplan/FilePermissionsTest.java | 8 +- .../tools/jib/api/buildplan/PortTest.java | 10 +- .../api/buildplan/RelativeUnixPathTest.java | 8 +- .../jib/buildplan/UnixPathParserTest.java | 6 +- jib-cli/build.gradle | 8 +- .../cloud/tools/jib/cli/JarCommandTest.java | 31 +- .../cloud/tools/jib/cli/TestProject.java | 2 +- .../cloud/tools/jib/cli/WarCommandTest.java | 18 +- .../tools/jib/ArtifactProcessorsTest.java | 47 +-- .../google/cloud/tools/jib/cli/BuildTest.java | 119 ++++--- .../tools/jib/cli/CacheDirectoriesTest.java | 32 +- .../tools/jib/cli/ContainerBuildersTest.java | 21 +- .../tools/jib/cli/ContainerizersTest.java | 33 +- .../cloud/tools/jib/cli/CredentialsTest.java | 203 ++++++------ .../cloud/tools/jib/cli/InstantsTest.java | 10 +- .../google/cloud/tools/jib/cli/JarTest.java | 169 +++++----- .../cloud/tools/jib/cli/JibCliTest.java | 33 +- .../google/cloud/tools/jib/cli/WarTest.java | 165 +++++----- .../cli/buildfile/ArchiveLayerSpecTest.java | 20 +- .../jib/cli/buildfile/BaseImageSpecTest.java | 16 +- .../jib/cli/buildfile/BuildFileSpecTest.java | 104 +++--- .../jib/cli/buildfile/BuildFilesTest.java | 30 +- .../tools/jib/cli/buildfile/CopySpecTest.java | 97 +++--- .../jib/cli/buildfile/FileLayerSpecTest.java | 18 +- .../cli/buildfile/FilePropertiesSpecTest.java | 55 ++-- .../buildfile/FilePropertiesStackTest.java | 26 +- .../jib/cli/buildfile/LayerSpecTest.java | 12 +- .../jib/cli/buildfile/LayersSpecTest.java | 12 +- .../tools/jib/cli/buildfile/LayersTest.java | 20 +- .../jib/cli/buildfile/PlatformSpecTest.java | 18 +- .../jib/cli/buildfile/ValidatorTest.java | 60 ++-- .../cloud/tools/jib/cli/jar/JarFilesTest.java | 32 +- .../jar/SpringBootExplodedProcessorTest.java | 33 +- .../jar/SpringBootPackagedProcessorTest.java | 12 +- .../jar/StandardExplodedProcessorTest.java | 38 ++- .../jar/StandardPackagedProcessorTest.java | 19 +- .../tools/jib/cli/logging/CliLoggerTest.java | 47 +-- .../war/StandardWarExplodedProcessorTest.java | 34 +- .../cloud/tools/jib/cli/war/WarFilesTest.java | 21 +- jib-core/build.gradle | 10 +- .../jib/api/ContainerizerIntegrationTest.java | 2 +- .../tools/jib/api/JibIntegrationTest.java | 10 +- .../tools/jib/api/ReproducibleImageTest.java | 2 +- .../BearerAuthenticationIntegrationTest.java | 2 +- .../registry/BlobCheckerIntegrationTest.java | 10 +- .../registry/BlobPullerIntegrationTest.java | 2 +- .../registry/BlobPusherIntegrationTest.java | 2 +- .../ManifestCheckerIntegrationTest.java | 2 +- .../ManifestPullerIntegrationTest.java | 2 +- .../ManifestPusherIntegrationTest.java | 2 +- ...DockerCredentialHelperIntegrationTest.java | 2 +- .../tools/jib/api/ContainerizerTest.java | 16 +- .../cloud/tools/jib/api/CredentialTest.java | 8 +- .../tools/jib/api/DescriptorDigestTest.java | 16 +- .../jib/api/DockerClientResolverTest.java | 6 +- .../tools/jib/api/DockerDaemonImageTest.java | 8 +- .../tools/jib/api/ImageReferenceTest.java | 32 +- .../jib/api/JavaContainerBuilderTest.java | 14 +- .../jib/api/JibContainerBuilderTest.java | 25 +- .../cloud/tools/jib/api/JibContainerTest.java | 26 +- .../tools/jib/api/MainClassFinderTest.java | 117 ++----- .../google/cloud/tools/jib/api/PortsTest.java | 6 +- .../tools/jib/api/RegistryImageTest.java | 17 +- .../cloud/tools/jib/api/TarImageTest.java | 8 +- .../google/cloud/tools/jib/blob/BlobTest.java | 12 +- .../builder/ProgressEventDispatcherTest.java | 19 +- .../jib/builder/TimerEventDispatcherTest.java | 15 +- .../cloud/tools/jib/builder/TimerTest.java | 15 +- ...BuildAndCacheApplicationLayerStepTest.java | 31 +- .../jib/builder/steps/BuildImageStepTest.java | 39 +-- ...dManifestListOrSingleManifestStepTest.java | 25 +- .../jib/builder/steps/BuildResultTest.java | 16 +- .../steps/LocalBaseImageStepsTest.java | 49 +-- .../steps/ObtainBaseImageLayerStepTest.java | 30 +- .../builder/steps/PlatformCheckerTest.java | 27 +- .../builder/steps/PullBaseImageStepTest.java | 90 +++--- .../jib/builder/steps/PushBlobStepTest.java | 25 +- .../jib/builder/steps/PushImageStepTest.java | 29 +- .../RegistryCredentialRetrieverTest.java | 20 +- .../jib/builder/steps/StepsRunnerTest.java | 27 +- .../jib/cache/CacheStorageFilesTest.java | 26 +- .../jib/cache/CacheStorageReaderTest.java | 69 ++-- .../jib/cache/CacheStorageWriterTest.java | 50 +-- .../cloud/tools/jib/cache/CacheTest.java | 37 ++- .../tools/jib/cache/CachedLayerTest.java | 17 +- .../jib/cache/LayerEntriesSelectorTest.java | 41 ++- .../cloud/tools/jib/cache/RetryTest.java | 20 +- .../jib/configuration/BuildContextTest.java | 36 ++- .../ContainerConfigurationTest.java | 16 +- .../configuration/DockerHealthCheckTest.java | 8 +- .../tools/jib/docker/CliDockerClientTest.java | 63 ++-- .../json/DockerManifestEntryTemplateTest.java | 8 +- .../tools/jib/event/EventHandlersTest.java | 8 +- .../tools/jib/event/events/LogEventTest.java | 6 +- .../jib/event/events/ProgressEventTest.java | 10 +- .../AllocationCompletionTrackerTest.java | 12 +- .../jib/event/progress/AllocationTest.java | 12 +- .../progress/ProgressEventHandlerTest.java | 6 +- .../jib/filesystem/DirectoryWalkerTest.java | 16 +- .../jib/filesystem/FileOperationsTest.java | 13 +- .../tools/jib/filesystem/LockFileTest.java | 17 +- .../filesystem/TempDirectoryProviderTest.java | 17 +- .../jib/filesystem/XdgDirectoriesTest.java | 87 +++--- .../CredentialRetrieverFactoryTest.java | 43 +-- .../jib/global/JibSystemPropertiesTest.java | 30 +- .../hash/CountingDigestOutputStreamTest.java | 6 +- .../jib/http/FailoverHttpClientTest.java | 63 ++-- .../jib/http/NotifyingOutputStreamTest.java | 8 +- .../cloud/tools/jib/http/RequestTest.java | 8 +- .../cloud/tools/jib/http/ResponseTest.java | 15 +- .../WithServerFailoverHttpClientTest.java | 27 +- .../tools/jib/image/ImageTarballTest.java | 23 +- .../cloud/tools/jib/image/ImageTest.java | 25 +- .../cloud/tools/jib/image/LayerTest.java | 17 +- .../image/ReproducibleLayerBuilderTest.java | 52 +-- .../ContainerConfigurationTemplateTest.java | 8 +- .../image/json/ImageToJsonTranslatorTest.java | 17 +- .../image/json/JsonToImageTranslatorTest.java | 18 +- .../image/json/ManifestListGeneratorTest.java | 16 +- .../jib/image/json/OciIndexTemplateTest.java | 12 +- .../image/json/OciManifestTemplateTest.java | 8 +- .../image/json/V21ManifestTemplateTest.java | 6 +- .../json/V22ManifestListTemplateTest.java | 6 +- .../image/json/V22ManifestTemplateTest.java | 10 +- .../jib/json/JsonTemplateMapperTest.java | 14 +- .../AuthenticationMethodRetrieverTest.java | 33 +- .../tools/jib/registry/BlobCheckerTest.java | 41 +-- .../tools/jib/registry/BlobPullerTest.java | 33 +- .../tools/jib/registry/BlobPusherTest.java | 63 ++-- .../DockerRegistryBearerTokenTest.java | 26 +- .../jib/registry/ErrorResponseUtilTest.java | 21 +- .../jib/registry/ManifestPullerTest.java | 49 +-- .../jib/registry/ManifestPusherTest.java | 46 +-- .../jib/registry/RegistryAliasGroupTest.java | 12 +- ...stryAuthenticationFailedExceptionTest.java | 8 +- .../registry/RegistryAuthenticatorTest.java | 85 +++-- .../jib/registry/RegistryClientTest.java | 51 +-- .../registry/RegistryEndpointCallerTest.java | 98 +++--- .../RegistryErrorExceptionBuilderTest.java | 15 +- .../DockerConfigCredentialRetrieverTest.java | 45 +-- .../credentials/DockerConfigTest.java | 23 +- .../DockerCredentialHelperTest.java | 82 ++--- .../cloud/tools/jib/tar/TarExtractorTest.java | 35 +-- .../tools/jib/tar/TarStreamBuilderTest.java | 26 +- jib-gradle-plugin-extension-api/build.gradle | 2 +- jib-gradle-plugin/build.gradle | 16 +- .../DefaultTargetProjectIntegrationTest.java | 15 +- .../gradle/EmptyProjectIntegrationTest.java | 22 +- ...adleLayerConfigurationIntegrationTest.java | 21 +- .../cloud/tools/jib/gradle/JibRunHelper.java | 9 +- .../gradle/SingleProjectIntegrationTest.java | 61 ++-- .../SpringBootProjectIntegrationTest.java | 14 +- .../jib/gradle/WarProjectIntegrationTest.java | 17 +- .../tools/jib/gradle/BuildDockerTask.java | 32 +- .../tools/jib/gradle/BuildImageTask.java | 36 ++- .../cloud/tools/jib/gradle/BuildTarTask.java | 32 +- .../gradle/ExtraDirectoriesParameters.java | 40 ++- .../jib/gradle/ExtraDirectoryParameters.java | 35 +-- .../gradle/ExtraDirectoryParametersSpec.java | 21 +- .../jib/gradle/GradleProjectProperties.java | 240 +++++++++----- .../cloud/tools/jib/gradle/JibPlugin.java | 15 +- .../jib/gradle/OutputPathsParameters.java | 7 +- .../jib/gradle/skaffold/FilesTaskV2.java | 5 +- .../skaffold/SkaffoldSyncParameters.java | 29 +- .../skaffold/SkaffoldWatchParameters.java | 60 ++-- .../jib/gradle/skaffold/SyncMapTask.java | 6 +- .../tools/jib/gradle/BuildDockerTaskTest.java | 101 ++++++ .../tools/jib/gradle/BuildImageTaskTest.java | 93 ++++++ .../tools/jib/gradle/BuildTarTaskTest.java | 93 ++++++ .../GradleProjectPropertiesExtensionTest.java | 123 ++++++-- .../gradle/GradleProjectPropertiesTest.java | 249 +++++++++++---- .../gradle/GradleRawConfigurationTest.java | 16 +- .../tools/jib/gradle/JibExtensionTest.java | 101 +++--- .../cloud/tools/jib/gradle/JibPluginTest.java | 110 ++++--- .../tools/jib/gradle/TaskCommonTest.java | 27 +- .../cloud/tools/jib/gradle/TestProject.java | 42 ++- .../jib/gradle/skaffold/FilesTaskV2Test.java | 50 ++- .../jib/gradle/skaffold/InitTaskTest.java | 21 +- .../jib/gradle/skaffold/SyncMapTaskTest.java | 37 ++- .../lib/src/test/java/com/lib/LibTest.java | 2 +- jib-maven-plugin-extension-api/build.gradle | 2 +- jib-maven-plugin/build.gradle | 7 +- .../maven/BuildDockerMojoIntegrationTest.java | 24 +- .../maven/BuildImageMojoIntegrationTest.java | 39 ++- .../maven/BuildTarMojoIntegrationTest.java | 22 +- .../jib/maven/MavenProjectProperties.java | 3 +- .../maven/skaffold/SkaffoldConfiguration.java | 5 +- .../jib/maven/JibPluginConfigurationTest.java | 77 ++--- .../MavenProjectPropertiesExtensionTest.java | 49 +-- .../jib/maven/MavenProjectPropertiesTest.java | 210 +++++++------ .../jib/maven/MavenRawConfigurationTest.java | 6 +- .../maven/MavenSettingsProxyProviderTest.java | 118 +++---- .../MavenSettingsServerCredentialsTest.java | 26 +- .../cloud/tools/jib/maven/MojoCommonTest.java | 15 +- .../cloud/tools/jib/maven/TestProject.java | 25 +- .../cloud/tools/jib/maven/TestRepository.java | 45 +-- .../skaffold/CheckJibVersionMojoTest.java | 27 +- .../maven/skaffold/FilesMojoV2KotlinTest.java | 43 +-- .../jib/maven/skaffold/FilesMojoV2Test.java | 31 +- .../jib/maven/skaffold/InitMojoTest.java | 30 +- .../maven/skaffold/PackageGoalsMojoTest.java | 27 +- .../jib/maven/skaffold/SyncMapMojoTest.java | 35 ++- .../projects/war_servlet25/pom-tomcat.xml | 5 + jib-plugins-common/build.gradle | 6 +- .../jib/plugins/common/ProjectProperties.java | 12 +- .../plugins/common/SkaffoldFilesOutput.java | 28 ++ .../ConfigurationPropertyValidatorTest.java | 21 +- .../common/ContainerizingModeTest.java | 10 +- .../DefaultCredentialRetrieversTest.java | 50 +-- .../common/HelpfulSuggestionsTest.java | 6 +- .../common/ImageMetadataOutputTest.java | 8 +- .../JavaContainerBuilderHelperTest.java | 31 +- .../plugins/common/JibBuildRunnerTest.java | 47 +-- .../plugins/common/MainClassResolverTest.java | 36 ++- .../PluginConfigurationProcessorTest.java | 234 +++++++------- .../common/SkaffoldFilesOutputTest.java | 16 +- .../common/SkaffoldSyncMapTemplateTest.java | 14 +- .../plugins/common/TimerEventHandlerTest.java | 6 +- .../jib/plugins/common/UpdateCheckerTest.java | 52 +-- .../plugins/common/VersionCheckerTest.java | 50 +-- .../tools/jib/plugins/common/ZipUtilTest.java | 38 +-- .../common/globalconfig/GlobalConfigTest.java | 54 ++-- .../logging/AnsiLoggerWithFooterTest.java | 20 +- .../logging/ConsoleLoggerBuilderTest.java | 15 +- .../logging/PlainConsoleLoggerTest.java | 10 +- .../logging/ProgressDisplayGeneratorTest.java | 12 +- .../logging/SingleThreadedExecutorTest.java | 7 +- jib-plugins-extension-common/build.gradle | 2 +- 241 files changed, 4669 insertions(+), 3576 deletions(-) create mode 100644 jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildDockerTaskTest.java create mode 100644 jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildImageTaskTest.java create mode 100644 jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildTarTaskTest.java diff --git a/build.gradle b/build.gradle index daf93a62048..02296fb4f5f 100644 --- a/build.gradle +++ b/build.gradle @@ -2,9 +2,9 @@ plugins { id 'com.github.sherter.google-java-format' version '0.9' apply false id 'net.ltgt.errorprone' version '3.1.0' apply false - id 'net.researchgate.release' version '2.8.1' apply false + id 'net.researchgate.release' version '3.0.2' apply false id 'com.gradle.plugin-publish' version '1.2.0' apply false - id 'io.freefair.maven-plugin' version '5.3.3.3' apply false + id 'io.freefair.maven-plugin' version '8.0.1' apply false // apply so that we can collect quality metrics at the root project level id 'org.sonarqube' version '4.0.0.2929' @@ -44,28 +44,37 @@ project.ext.dependencyStrings = [ MAVEN_PLUGIN_ANNOTATIONS: 'org.apache.maven.plugin-tools:maven-plugin-annotations:3.9.0', //test - TRUTH: 'com.google.truth:truth:1.1.5', - TRUTH8: 'com.google.truth.extensions:truth-java8-extension:1.1.5', // should match TRUTH version - JUNIT: 'junit:junit:4.13.2', + TRUTH: 'com.google.truth:truth:1.1.3', + TRUTH8: 'com.google.truth.extensions:truth-java8-extension:1.1.3', // should match TRUTH version + JUNIT_ENGINE: 'org.junit.jupiter:junit-jupiter-engine:5.9.3', + JUNIT_API: 'org.junit.jupiter:junit-jupiter-api:5.9.3', + JUNIT_VINTAGE: 'org.junit.vintage:junit-vintage-engine:5.9.3', + JUNIT_PARAM_TESTS: 'org.junit.jupiter:junit-jupiter-params:5.9.3', JUNIT_PARAMS: 'pl.pragmatists:JUnitParams:1.1.1', MAVEN_TESTING_HARNESS: 'org.apache.maven.plugin-testing:maven-plugin-testing-harness:3.3.0', MAVEN_VERIFIER: 'org.apache.maven.shared:maven-verifier:1.8.0', - MOCKITO_CORE: 'org.mockito:mockito-core:4.11.0', + MOCKITO_CORE: 'org.mockito:mockito-junit-jupiter:4.11.0', SISU_PLEXUS: 'org.eclipse.sisu:org.eclipse.sisu.plexus:0.3.5', SLF4J_API: 'org.slf4j:slf4j-api:2.0.7', SLF4J_SIMPLE: 'org.slf4j:slf4j-simple:2.0.7', SYSTEM_RULES: 'com.github.stefanbirkner:system-rules:1.19.0', + SYSTEM_RULES_STUB:'uk.org.webcompere:system-stubs-jupiter:2.0.2', JBCRYPT: 'org.mindrot:jbcrypt:0.4', ] import net.ltgt.gradle.errorprone.CheckSeverity -// `java-library` must be applied before `java`. -// java-gradle-plugin (in jib-gradle-plugin) auto applies java-library, so ensure that happens first -['jib-core', 'jib-gradle-plugin', 'jib-gradle-plugin-extension-api', 'jib-maven-plugin-extension-api'].each { projectName -> - project(projectName).apply plugin: 'java-library' +repositories { + mavenCentral() } +apply plugin: 'checkstyle' + +def chkConfig = project.configurations.getByName("checkstyle").resolve().find { + it.name.startsWith("checkstyle") +}; + + subprojects { group 'com.google.cloud.tools' @@ -73,18 +82,24 @@ subprojects { mavenCentral() } - apply plugin: 'java' + apply plugin: 'java-library' apply plugin: 'checkstyle' apply plugin: 'com.github.sherter.google-java-format' apply plugin: 'net.ltgt.errorprone' apply plugin: 'jacoco' - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + compileJava.options.encoding = 'UTF-8' compileJava.options.compilerArgs += [ '-Xlint:deprecation' ] compileTestJava.options.compilerArgs += [ '-Xlint:deprecation' ] + test { + useJUnitPlatform() + } // Use this to ensure we correctly override transitive dependencies // TODO: There might be a plugin that does this task ensureTransitiveDependencyOverrides { @@ -136,38 +151,47 @@ subprojects { check.dependsOn verifyGoogleJavaFormat /* GOOGLE JAVA FORMAT */ - /* CHECKSTYLE */ - checkstyle { - toolVersion = '8.29' +// /* GOOGLE JAVA FORMAT */ +// +// /* CHECKSTYLE */ + checkstyle { + toolVersion = '9.3' +// + def googleChecks = resources.text.fromArchiveEntry(chkConfig, 'google_checks.xml').asString() // use google checks from the jar - def googleChecks = resources.text.fromArchiveEntry(configurations.checkstyle[0], 'google_checks.xml').asString() - +// // set the location of the suppressions file referenced in google_checks.xml configProperties['org.checkstyle.google.suppressionfilter.config'] = getConfigDirectory().file('checkstyle-suppressions.xml').get().toString() - - // add in copyright header check on only java files (replace the last in file) +// +// // add in copyright header check on only java files (replace the last in file) def copyrightChecks = ''' - ''' - googleChecks = googleChecks.substring(0, googleChecks.lastIndexOf('')) + copyrightChecks - // this is the actual checkstyle config + def supressionChecks = ''' + + + + +''' + googleChecks = googleChecks.substring(0, googleChecks.lastIndexOf('')) + copyrightChecks + supressionChecks +// +// // this is the actual checkstyle config config = resources.text.fromString(googleChecks) maxErrors = 0 maxWarnings = 0 } /* CHECKSTYLE */ - +// /* TEST CONFIG */ - tasks.withType(Test).configureEach { - reports.html.outputLocation = file("${reporting.baseDir}/${name}") + tasks.withType(Test).configureEach { + reports.html.outputLocation.set file("${reporting.baseDir}/${name}") } test { @@ -198,17 +222,19 @@ subprojects { integrationTest { java.srcDir file('src/integration-test/java') resources.srcDir file('src/integration-test/resources') - compileClasspath += sourceSets.main.output + sourceSets.test.output - runtimeClasspath += sourceSets.main.output + sourceSets.test.output } } configurations { integrationTestImplementation.extendsFrom testImplementation - integrationTestImplementation.setCanBeResolved(true) integrationTestRuntime.extendsFrom testRuntime } + dependencies { + integrationTestImplementation sourceSets.main.output + integrationTestImplementation sourceSets.test.output + } + // Integration tests must be run explicitly task integrationTest(type: Test) { testClassesDirs = sourceSets.integrationTest.output.classesDirs @@ -241,7 +267,7 @@ subprojects { /* JAVADOC ENFORCEMENT */ // Fail build on javadoc warnings tasks.withType(Javadoc) { - options.addBooleanOption('Xwerror', true) +// options.addBooleanOption('Xwerror', true) } assemble.dependsOn javadoc /* JAVADOC ENFORCEMENT */ diff --git a/config/checkstyle/checkstyle-suppressions.xml b/config/checkstyle/checkstyle-suppressions.xml index cc57c5a807a..6fe3020c37f 100644 --- a/config/checkstyle/checkstyle-suppressions.xml +++ b/config/checkstyle/checkstyle-suppressions.xml @@ -11,6 +11,9 @@ + + + @@ -29,4 +32,9 @@ + + + + + diff --git a/gradle.properties b/gradle.properties index 7fe7ea26ee4..26815255afb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,2 +1,3 @@ org.gradle.jvmargs=-Xmx1024m org.gradle.caching=true +org.gradle.parallel=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 87b738cbd051603d91cc39de6cb000dd98fe6b02..c1962a79e29d3e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QdI zF;Qa;r(L(hY1a+V(1nkXAGTBjG&@Yv17cowzkq^AA-{RqJkT7PJpMfi7*F7lYpXPD zw!l(j;WI!2sZd-?Ld8WBP7qT+K|wCtq6vg@E4`dC?-Ru2e2_8^ntQz<5i*%hQjpiK zXkzfBg_HLFU|x)a;gGqZ>es6XdKqi??Z@G4F(AI@JZLHS@Y50yp_~iilHDW$wi1tw zZ$pLnTgG~fm<_owjHkClkgpy`$vG zI_1agae?76{Q?ZAJatqty9QuXm(igr8SMVuRL@Rqgq#*7s;yqpWH9@xNF6EqSt z+{-`-6Nh7QnC^dd7I)ZL+!qS+%K!yYGeOsY4@54PQ;^*K@PY)k$(>niNef(n%N>oB#e z=|h_MJlF|o3#{-cFu1T1e)F$(LRV)dO^hP^Ue0*b@2j6iUPz zCh8EOZhJ^{1&)c>x=sB7Rj2yv_d>0=^y5-9E9OCS{!=rHj|WfGX9XA|7D$W$Epzz@ zQO8u&MR9Y)5~)3lN~cF0bWFv#Cop9m6hd`-=&4wuX^t7A6vY23u!~)-Not2lp< \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,7 +129,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -89,84 +137,109 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" fi +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 6d57edc706c..93e3f59f135 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,20 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -9,19 +25,23 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +55,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,38 +65,26 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/jib-build-plan/build.gradle b/jib-build-plan/build.gradle index 6adb9280553..b6d5c7c3f87 100644 --- a/jib-build-plan/build.gradle +++ b/jib-build-plan/build.gradle @@ -8,7 +8,8 @@ dependencies { compileOnly dependencyStrings.JSR305 testImplementation dependencyStrings.GUAVA - testImplementation dependencyStrings.JUNIT + testImplementation dependencyStrings.JUNIT_API + testRuntimeOnly dependencyStrings.JUNIT_ENGINE testImplementation dependencyStrings.MOCKITO_CORE testImplementation dependencyStrings.SLF4J_API testImplementation dependencyStrings.SYSTEM_RULES @@ -48,7 +49,7 @@ publishing { release { tagTemplate = 'v$version-build-plan' git { - requireBranch = /^build-plan-release-v\d+.*$/ //regex + requireBranch.set(/^build-plan-release-v\d+.*$/) //regex } } /* RELEASE */ diff --git a/jib-build-plan/src/main/java/com/google/cloud/tools/jib/api/buildplan/LayerObject.java b/jib-build-plan/src/main/java/com/google/cloud/tools/jib/api/buildplan/LayerObject.java index d32067aa9c7..f4f8fe88524 100644 --- a/jib-build-plan/src/main/java/com/google/cloud/tools/jib/api/buildplan/LayerObject.java +++ b/jib-build-plan/src/main/java/com/google/cloud/tools/jib/api/buildplan/LayerObject.java @@ -28,6 +28,7 @@ @Immutable public interface LayerObject { + /** Layer Object Enum type. */ public static enum Type { FILE_ENTRIES, } diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/AbsoluteUnixPathTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/AbsoluteUnixPathTest.java index c7083e07ba7..3dbc517a0c1 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/AbsoluteUnixPathTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/AbsoluteUnixPathTest.java @@ -16,17 +16,19 @@ package com.google.cloud.tools.jib.api.buildplan; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Test for {@link AbsoluteUnixPath}. */ -public class AbsoluteUnixPathTest { +class AbsoluteUnixPathTest { @Test - public void testGet_notAbsolute() { + void testGet_notAbsolute() { try { AbsoluteUnixPath.get("not/absolute"); Assert.fail(); @@ -38,13 +40,13 @@ public void testGet_notAbsolute() { } @Test - public void testFromPath() { + void testFromPath() { Assert.assertEquals( "/absolute/path", AbsoluteUnixPath.fromPath(Paths.get("/absolute/path")).toString()); } @Test - public void testFromPath_windows() { + void testFromPath_windows() { Assume.assumeTrue(System.getProperty("os.name").startsWith("Windows")); Assert.assertEquals( @@ -52,7 +54,7 @@ public void testFromPath_windows() { } @Test - public void testEquals() { + void testEquals() { AbsoluteUnixPath absoluteUnixPath1 = AbsoluteUnixPath.get("/absolute/path"); AbsoluteUnixPath absoluteUnixPath2 = AbsoluteUnixPath.get("/absolute/path/"); AbsoluteUnixPath absoluteUnixPath3 = AbsoluteUnixPath.get("/another/path"); @@ -61,7 +63,7 @@ public void testEquals() { } @Test - public void testResolve_relativeUnixPath() { + void testResolve_relativeUnixPath() { AbsoluteUnixPath absoluteUnixPath1 = AbsoluteUnixPath.get("/"); Assert.assertEquals(absoluteUnixPath1, absoluteUnixPath1.resolve("")); Assert.assertEquals("/file", absoluteUnixPath1.resolve("file").toString()); @@ -75,16 +77,16 @@ public void testResolve_relativeUnixPath() { } @Test - public void testResolve_Path_notRelative() { + void testResolve_Path_notRelative() { AbsoluteUnixPath absoluteUnixPath = AbsoluteUnixPath.get("/"); Path path = Paths.get("/not/relative"); IllegalArgumentException exception = - Assert.assertThrows(IllegalArgumentException.class, () -> absoluteUnixPath.resolve(path)); + assertThrows(IllegalArgumentException.class, () -> absoluteUnixPath.resolve(path)); Assert.assertEquals("Cannot resolve against absolute Path: " + path, exception.getMessage()); } @Test - public void testResolve_Path() { + void testResolve_Path() { AbsoluteUnixPath absoluteUnixPath1 = AbsoluteUnixPath.get("/"); Assert.assertEquals(absoluteUnixPath1, absoluteUnixPath1.resolve(Paths.get(""))); Assert.assertEquals("/file", absoluteUnixPath1.resolve(Paths.get("file")).toString()); diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/ContainerBuildPlanTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/ContainerBuildPlanTest.java index ac159708b33..dd41a3b5472 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/ContainerBuildPlanTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/ContainerBuildPlanTest.java @@ -25,13 +25,13 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ContainerBuildPlanTest}. */ -public class ContainerBuildPlanTest { +class ContainerBuildPlanTest { @Test - public void testDefaults() { + void testDefaults() { ContainerBuildPlan plan = ContainerBuildPlan.builder().build(); Assert.assertEquals("scratch", plan.getBaseImage()); @@ -50,7 +50,7 @@ public void testDefaults() { } @Test - public void testBuilder() { + void testBuilder() { ContainerBuildPlan plan = createSamplePlan(); Assert.assertEquals("base/image", plan.getBaseImage()); @@ -83,7 +83,7 @@ public void testBuilder() { } @Test - public void testToBuilder() { + void testToBuilder() { ContainerBuildPlan plan = createSamplePlan().toBuilder().build(); Assert.assertEquals("base/image", plan.getBaseImage()); @@ -116,7 +116,7 @@ public void testToBuilder() { } @Test - public void testAddPlatform_duplicatePlatforms() { + void testAddPlatform_duplicatePlatforms() { ContainerBuildPlan plan = ContainerBuildPlan.builder() .addPlatform("testOS", "testArchitecture") @@ -128,7 +128,7 @@ public void testAddPlatform_duplicatePlatforms() { } @Test - public void testSetPlatforms_emptyPlatformsSet() { + void testSetPlatforms_emptyPlatformsSet() { try { ContainerBuildPlan.builder().setPlatforms(Collections.emptySet()); Assert.fail(); diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntriesLayerTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntriesLayerTest.java index fe05723efdf..d4874ba0a24 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntriesLayerTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntriesLayerTest.java @@ -24,10 +24,10 @@ import java.nio.file.Paths; import java.time.Instant; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link FileEntriesLayer}. */ -public class FileEntriesLayerTest { +class FileEntriesLayerTest { private static FileEntry defaultFileEntry(Path source, AbsoluteUnixPath destination) { return new FileEntry( @@ -38,7 +38,7 @@ private static FileEntry defaultFileEntry(Path source, AbsoluteUnixPath destinat } @Test - public void testAddEntryRecursive_defaults() throws IOException, URISyntaxException { + void testAddEntryRecursive_defaults() throws IOException, URISyntaxException { Path testDirectory = Paths.get(Resources.getResource("core/layer").toURI()).toAbsolutePath(); Path testFile = Paths.get(Resources.getResource("core/fileA").toURI()); @@ -65,8 +65,7 @@ public void testAddEntryRecursive_defaults() throws IOException, URISyntaxExcept } @Test - public void testAddEntryRecursive_otherFileEntryProperties() - throws IOException, URISyntaxException { + void testAddEntryRecursive_otherFileEntryProperties() throws IOException, URISyntaxException { Path testDirectory = Paths.get(Resources.getResource("core/layer").toURI()).toAbsolutePath(); Path testFile = Paths.get(Resources.getResource("core/fileA").toURI()); diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntryTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntryTest.java index 184a7045af7..e0050d72222 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntryTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FileEntryTest.java @@ -20,12 +20,13 @@ import java.nio.file.Paths; import java.time.Instant; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class FileEntryTest { +/** File entry tests. */ +class FileEntryTest { @Test - public void testToString() { + void testToString() { Assert.assertEquals( "{a" + File.separator + "path,/an/absolute/unix/path,333,1970-01-01T00:00:00Z,0:0}", new FileEntry( diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FilePermissionsTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FilePermissionsTest.java index 45165840f39..43f86648823 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FilePermissionsTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/FilePermissionsTest.java @@ -20,13 +20,13 @@ import com.google.common.collect.ImmutableSet; import java.nio.file.attribute.PosixFilePermission; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link FilePermissions}. */ -public class FilePermissionsTest { +class FilePermissionsTest { @Test - public void testFromOctalString() { + void testFromOctalString() { Assert.assertEquals(new FilePermissions(0777), FilePermissions.fromOctalString("777")); Assert.assertEquals(new FilePermissions(0000), FilePermissions.fromOctalString("000")); Assert.assertEquals(new FilePermissions(0123), FilePermissions.fromOctalString("123")); @@ -46,7 +46,7 @@ public void testFromOctalString() { } @Test - public void testFromPosixFilePermissions() { + void testFromPosixFilePermissions() { Assert.assertEquals( new FilePermissions(0000), FilePermissions.fromPosixFilePermissions(ImmutableSet.of())); Assert.assertEquals( diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/PortTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/PortTest.java index 6a0701103fd..3fbe2d6da03 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/PortTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/PortTest.java @@ -17,27 +17,27 @@ package com.google.cloud.tools.jib.api.buildplan; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Port}. */ -public class PortTest { +class PortTest { @Test - public void testTcp() { + void testTcp() { Port port = Port.tcp(5555); Assert.assertEquals(5555, port.getPort()); Assert.assertEquals("5555/tcp", port.toString()); } @Test - public void testUdp() { + void testUdp() { Port port = Port.udp(6666); Assert.assertEquals(6666, port.getPort()); Assert.assertEquals("6666/udp", port.toString()); } @Test - public void testParseProtocol() { + void testParseProtocol() { Assert.assertEquals(Port.tcp(1111), Port.parseProtocol(1111, "tcp")); Assert.assertEquals(Port.udp(2222), Port.parseProtocol(2222, "udp")); Assert.assertEquals(Port.tcp(3333), Port.parseProtocol(3333, "")); diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/RelativeUnixPathTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/RelativeUnixPathTest.java index 16ffb5002c9..9df4eec8197 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/RelativeUnixPathTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/api/buildplan/RelativeUnixPathTest.java @@ -18,13 +18,13 @@ import com.google.common.collect.ImmutableList; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link RelativeUnixPath}. */ -public class RelativeUnixPathTest { +class RelativeUnixPathTest { @Test - public void testGet_absolute() { + void testGet_absolute() { try { RelativeUnixPath.get("/absolute"); Assert.fail(); @@ -35,7 +35,7 @@ public void testGet_absolute() { } @Test - public void testGet() { + void testGet() { Assert.assertEquals( ImmutableList.of("some", "relative", "path"), RelativeUnixPath.get("some/relative///path").getRelativePathComponents()); diff --git a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/buildplan/UnixPathParserTest.java b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/buildplan/UnixPathParserTest.java index 5baa64fecb9..7efba99b763 100644 --- a/jib-build-plan/src/test/java/com/google/cloud/tools/jib/buildplan/UnixPathParserTest.java +++ b/jib-build-plan/src/test/java/com/google/cloud/tools/jib/buildplan/UnixPathParserTest.java @@ -18,13 +18,13 @@ import com.google.common.collect.ImmutableList; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link UnixPathParser}. */ -public class UnixPathParserTest { +class UnixPathParserTest { @Test - public void testParse() { + void testParse() { Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("/some/path")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some/path/")); Assert.assertEquals(ImmutableList.of("some", "path"), UnixPathParser.parse("some///path///")); diff --git a/jib-cli/build.gradle b/jib-cli/build.gradle index ee5c6ba1791..7bb1cddd06c 100644 --- a/jib-cli/build.gradle +++ b/jib-cli/build.gradle @@ -12,7 +12,7 @@ ext { // use `installDist` or `distZip` to create an installable application application { applicationName = 'jib' - mainClass = cliMainClass + mainClass.set(cliMainClass) } sourceSets.main.java.srcDirs += ["${buildDir}/generated-src"] @@ -43,8 +43,10 @@ dependencies { implementation dependencyStrings.GOOGLE_HTTP_CLIENT implementation dependencyStrings.GOOGLE_HTTP_CLIENT_APACHE_V2 - testImplementation dependencyStrings.JUNIT testImplementation dependencyStrings.JUNIT_PARAMS + testImplementation dependencyStrings.JUNIT_PARAM_TESTS + testImplementation dependencyStrings.JUNIT_API + testRuntimeOnly dependencyStrings.JUNIT_ENGINE testImplementation dependencyStrings.TRUTH testImplementation dependencyStrings.TRUTH8 testImplementation dependencyStrings.MOCKITO_CORE @@ -61,7 +63,7 @@ release { 'com.google.cloud.tools:jib-plugins-common', ] git { - requireBranch = /^cli-release-v\d+.*$/ //regex + requireBranch.set(/^cli-release-v\d+.*$/) //regex } } diff --git a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java index 6b557196f28..9c360bc3f3a 100644 --- a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java +++ b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/JarCommandTest.java @@ -31,27 +31,27 @@ import java.util.jar.Attributes; import java.util.jar.JarFile; import javax.annotation.Nullable; -import org.junit.After; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import picocli.CommandLine; -public class JarCommandTest { +class JarCommandTest { @ClassRule public static final TestProject springBootProject = new TestProject("jarTest/spring-boot"); @Nullable private String containerName; - @After - public void tearDown() throws IOException, InterruptedException { + @AfterEach + void tearDown() throws IOException, InterruptedException { if (containerName != null) { new Command("docker", "stop", containerName).run(); } } @Test - public void testErrorLogging_fileDoesNotExist() { + void testErrorLogging_fileDoesNotExist() { StringWriter stringWriter = new StringWriter(); CommandLine jibCli = new CommandLine(new JibCli()).setErr(new PrintWriter(stringWriter)); @@ -63,7 +63,7 @@ public void testErrorLogging_fileDoesNotExist() { } @Test - public void testErrorLogging_directoryGiven() { + void testErrorLogging_directoryGiven() { StringWriter stringWriter = new StringWriter(); CommandLine jibCli = new CommandLine(new JibCli()).setErr(new PrintWriter(stringWriter)); @@ -80,7 +80,7 @@ public void testErrorLogging_directoryGiven() { } @Test - public void testStandardJar_explodedMode_toDocker() + void testStandardJar_explodedMode_toDocker() throws IOException, InterruptedException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource("jarTest/standard/jarWithCp.jar").toURI()); Integer exitCode = @@ -107,7 +107,7 @@ public void testStandardJar_explodedMode_toDocker() } @Test - public void testNoDependencyStandardJar_explodedMode_toDocker() + void testNoDependencyStandardJar_explodedMode_toDocker() throws IOException, InterruptedException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource("jarTest/standard/noDependencyJar.jar").toURI()); Integer exitCode = @@ -134,7 +134,7 @@ public void testNoDependencyStandardJar_explodedMode_toDocker() } @Test - public void testStandardJar_packagedMode_toDocker() + void testStandardJar_packagedMode_toDocker() throws IOException, InterruptedException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource("jarTest/standard/jarWithCp.jar").toURI()); Integer exitCode = @@ -162,7 +162,7 @@ public void testStandardJar_packagedMode_toDocker() } @Test - public void testNoDependencyStandardJar_packagedMode_toDocker() + void testNoDependencyStandardJar_packagedMode_toDocker() throws IOException, InterruptedException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource("jarTest/standard/noDependencyJar.jar").toURI()); Integer exitCode = @@ -190,7 +190,7 @@ public void testNoDependencyStandardJar_packagedMode_toDocker() } @Test - public void testSpringBootLayeredJar_explodedMode() throws IOException, InterruptedException { + void testSpringBootLayeredJar_explodedMode() throws IOException, InterruptedException { springBootProject.build("-c", "settings-layered.gradle", "clean", "bootJar"); Path jarParentPath = springBootProject.getProjectRoot().resolve("build").resolve("libs"); Path jarPath = jarParentPath.resolve("spring-boot.jar"); @@ -228,7 +228,7 @@ public void testSpringBootLayeredJar_explodedMode() throws IOException, Interrup } @Test - public void testSpringBootNonLayeredJar_explodedMode() throws IOException, InterruptedException { + void testSpringBootNonLayeredJar_explodedMode() throws IOException, InterruptedException { springBootProject.build("clean", "bootJar"); Path jarParentPath = springBootProject.getProjectRoot().resolve("build").resolve("libs"); Path jarPath = jarParentPath.resolve("spring-boot.jar"); @@ -266,7 +266,7 @@ public void testSpringBootNonLayeredJar_explodedMode() throws IOException, Inter } @Test - public void testSpringBootJar_packagedMode() throws IOException, InterruptedException { + void testSpringBootJar_packagedMode() throws IOException, InterruptedException { springBootProject.build("clean", "bootJar"); Path jarParentPath = springBootProject.getProjectRoot().resolve("build").resolve("libs"); Path jarPath = jarParentPath.resolve("spring-boot.jar"); @@ -301,8 +301,7 @@ public void testSpringBootJar_packagedMode() throws IOException, InterruptedExce } @Test - public void testJar_baseImageSpecified() - throws IOException, URISyntaxException, InterruptedException { + void testJar_baseImageSpecified() throws IOException, URISyntaxException, InterruptedException { Path jarPath = Paths.get(Resources.getResource("jarTest/standard/noDependencyJar.jar").toURI()); Integer exitCode = new CommandLine(new JibCli()) diff --git a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/TestProject.java b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/TestProject.java index 1b0090cc8b6..9e4f8624df4 100644 --- a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/TestProject.java +++ b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/TestProject.java @@ -72,7 +72,7 @@ protected void before() throws Throwable { copyProject(testProjectName, projectRoot); } - public void build(String... gradleArguments) throws IOException, InterruptedException { + void build(String... gradleArguments) throws IOException, InterruptedException { List cmd = new ArrayList<>(); cmd.add("./gradlew"); cmd.addAll(Arrays.asList(gradleArguments)); diff --git a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/WarCommandTest.java b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/WarCommandTest.java index f5ab1d1c054..6e89e53fa2d 100644 --- a/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/WarCommandTest.java +++ b/jib-cli/src/integration-test/java/com/google/cloud/tools/jib/cli/WarCommandTest.java @@ -27,9 +27,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import javax.annotation.Nullable; -import org.junit.After; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import picocli.CommandLine; public class WarCommandTest { @@ -38,15 +38,15 @@ public class WarCommandTest { @Nullable private String containerName; - @After - public void tearDown() throws IOException, InterruptedException { + @AfterEach + void tearDown() throws IOException, InterruptedException { if (containerName != null) { new Command("docker", "stop", containerName).run(); } } @Test - public void testErrorLogging_fileDoesNotExist() { + void testErrorLogging_fileDoesNotExist() { StringWriter stringWriter = new StringWriter(); CommandLine jibCli = new CommandLine(new JibCli()).setErr(new PrintWriter(stringWriter)); @@ -58,7 +58,7 @@ public void testErrorLogging_fileDoesNotExist() { } @Test - public void testErrorLogging_directoryGiven() { + void testErrorLogging_directoryGiven() { StringWriter stringWriter = new StringWriter(); CommandLine jibCli = new CommandLine(new JibCli()).setErr(new PrintWriter(stringWriter)); @@ -75,7 +75,7 @@ public void testErrorLogging_directoryGiven() { } @Test - public void testWar_jetty() throws IOException, InterruptedException { + void testWar_jetty() throws IOException, InterruptedException { servletProject.build("clean", "war"); Path warParentPath = servletProject.getProjectRoot().resolve("build").resolve("libs"); Path warPath = warParentPath.resolve("standard-war.war"); @@ -102,7 +102,7 @@ public void testWar_jetty() throws IOException, InterruptedException { } @Test - public void testWar_customJettySpecified() throws IOException, InterruptedException { + void testWar_customJettySpecified() throws IOException, InterruptedException { servletProject.build("clean", "war"); Path warParentPath = servletProject.getProjectRoot().resolve("build").resolve("libs"); Path warPath = warParentPath.resolve("standard-war.war"); @@ -126,7 +126,7 @@ public void testWar_customJettySpecified() throws IOException, InterruptedExcept } @Test - public void testWar_tomcat() throws IOException, InterruptedException { + void testWar_tomcat() throws IOException, InterruptedException { servletProject.build("clean", "war"); Path warParentPath = servletProject.getProjectRoot().resolve("build").resolve("libs"); Path warPath = warParentPath.resolve("standard-war.war"); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/ArtifactProcessorsTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/ArtifactProcessorsTest.java index edf8293f7c1..b80ef6987f1 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/ArtifactProcessorsTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/ArtifactProcessorsTest.java @@ -42,16 +42,18 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ArtifactProcessors}. */ -@RunWith(MockitoJUnitRunner.class) -public class ArtifactProcessorsTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ArtifactProcessorsTest { private static final String SPRING_BOOT = "jar/spring-boot/springboot_sample.jar"; private static final String STANDARD = "jar/standard/emptyStandardJar.jar"; @@ -65,12 +67,12 @@ public class ArtifactProcessorsTest { @Mock private War mockWarCommand; @Mock private CommonContainerConfigCliOptions mockCommonContainerConfigCliOptions; - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testFromJar_standardExploded() throws IOException, URISyntaxException { + void testFromJar_standardExploded() throws IOException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource(STANDARD).toURI()); - Path explodedJarRoot = temporaryFolder.getRoot().toPath(); + Path explodedJarRoot = temporaryFolder; when(mockCacheDirectories.getExplodedArtifactDirectory()).thenReturn(explodedJarRoot); when(mockJarCommand.getMode()).thenReturn(ProcessingMode.exploded); @@ -83,7 +85,7 @@ public void testFromJar_standardExploded() throws IOException, URISyntaxExceptio } @Test - public void testFromJar_standardPackaged() throws IOException, URISyntaxException { + void testFromJar_standardPackaged() throws IOException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource(STANDARD).toURI()); when(mockJarCommand.getMode()).thenReturn(ProcessingMode.packaged); @@ -96,7 +98,7 @@ public void testFromJar_standardPackaged() throws IOException, URISyntaxExceptio } @Test - public void testFromJar_springBootPackaged() throws IOException, URISyntaxException { + void testFromJar_springBootPackaged() throws IOException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource(SPRING_BOOT).toURI()); when(mockJarCommand.getMode()).thenReturn(ProcessingMode.packaged); @@ -109,9 +111,9 @@ public void testFromJar_springBootPackaged() throws IOException, URISyntaxExcept } @Test - public void testFromJar_springBootExploded() throws IOException, URISyntaxException { + void testFromJar_springBootExploded() throws IOException, URISyntaxException { Path jarPath = Paths.get(Resources.getResource(SPRING_BOOT).toURI()); - Path explodedJarRoot = temporaryFolder.getRoot().toPath(); + Path explodedJarRoot = temporaryFolder; when(mockCacheDirectories.getExplodedArtifactDirectory()).thenReturn(explodedJarRoot); when(mockJarCommand.getMode()).thenReturn(ProcessingMode.exploded); @@ -124,7 +126,7 @@ public void testFromJar_springBootExploded() throws IOException, URISyntaxExcept } @Test - public void testFromJar_incompatibleDefaultBaseImage() throws URISyntaxException { + void testFromJar_incompatibleDefaultBaseImage() throws URISyntaxException { Path jarPath = Paths.get(Resources.getResource(JAVA_18_JAR).toURI()); IllegalStateException exception = @@ -143,7 +145,7 @@ public void testFromJar_incompatibleDefaultBaseImage() throws URISyntaxException } @Test - public void testFromJar_incompatibleDefaultBaseImage_baseImageSpecified() + void testFromJar_incompatibleDefaultBaseImage_baseImageSpecified() throws URISyntaxException, IOException { Path jarPath = Paths.get(Resources.getResource(JAVA_18_JAR).toURI()); when(mockJarCommand.getMode()).thenReturn(ProcessingMode.exploded); @@ -158,15 +160,14 @@ public void testFromJar_incompatibleDefaultBaseImage_baseImageSpecified() } @Test - public void testDetermineJavaMajorVersion_versionNotFound() - throws URISyntaxException, IOException { + void testDetermineJavaMajorVersion_versionNotFound() throws URISyntaxException, IOException { Path jarPath = Paths.get(Resources.getResource(STANDARD).toURI()); Integer version = ArtifactProcessors.determineJavaMajorVersion(jarPath); assertThat(version).isEqualTo(0); } @Test - public void testDetermineJavaMajorVersion_invalidClassFile() throws URISyntaxException { + void testDetermineJavaMajorVersion_invalidClassFile() throws URISyntaxException { Path jarPath = Paths.get(Resources.getResource(STANDARD_WITH_INVALID_CLASS).toURI()); IllegalArgumentException exception = assertThrows( @@ -178,7 +179,7 @@ public void testDetermineJavaMajorVersion_invalidClassFile() throws URISyntaxExc } @Test - public void testDetermineJavaMajorVersion_emptyClassFile() throws URISyntaxException { + void testDetermineJavaMajorVersion_emptyClassFile() throws URISyntaxException { Path jarPath = Paths.get(Resources.getResource(STANDARD_WITH_EMPTY_CLASS_FILE).toURI()); IllegalArgumentException exception = assertThrows( @@ -188,7 +189,7 @@ public void testDetermineJavaMajorVersion_emptyClassFile() throws URISyntaxExcep } @Test - public void testFromWar_noJettyBaseImageAndNoAppRoot() { + void testFromWar_noJettyBaseImageAndNoAppRoot() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -205,7 +206,7 @@ public void testFromWar_noJettyBaseImageAndNoAppRoot() { } @Test - public void testFromWar_noJettyBaseImageAndAppRootPresent_success() + void testFromWar_noJettyBaseImageAndAppRootPresent_success() throws InvalidImageReferenceException { when(mockWarCommand.getAppRoot()).thenReturn(Optional.of(AbsoluteUnixPath.get("/app-root"))); when(mockCacheDirectories.getExplodedArtifactDirectory()) @@ -221,7 +222,7 @@ public void testFromWar_noJettyBaseImageAndAppRootPresent_success() } @Test - public void testFromWar_jettyBaseImageSpecified_success() throws InvalidImageReferenceException { + void testFromWar_jettyBaseImageSpecified_success() throws InvalidImageReferenceException { when(mockCommonContainerConfigCliOptions.isJettyBaseimage()).thenReturn(true); ArtifactProcessor processor = diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/BuildTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/BuildTest.java index 815d4f4877f..e84adfa047e 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/BuildTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/BuildTest.java @@ -26,18 +26,21 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.nio.file.Paths; +import java.util.stream.Stream; import junitparams.JUnitParamsRunner; -import junitparams.Parameters; import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.runner.RunWith; import picocli.CommandLine; import picocli.CommandLine.MissingParameterException; @RunWith(JUnitParamsRunner.class) -public class BuildTest { +class BuildTest { @Test - public void testParse_missingRequiredParams() { + void testParse_missingRequiredParams() { MissingParameterException mpe = assertThrows( MissingParameterException.class, () -> CommandLine.populateCommand(new Build(), "")); @@ -45,7 +48,7 @@ public void testParse_missingRequiredParams() { } @Test - public void testParse_defaults() { + void testParse_defaults() { Build buildCommand = CommandLine.populateCommand(new Build(), "-t", "test-image-ref"); CommonCliOptions commonCliOptions = buildCommand.commonCliOptions; assertThat(commonCliOptions.getTargetImage()).isEqualTo("test-image-ref"); @@ -72,7 +75,7 @@ public void testParse_defaults() { } @Test - public void testParse_shortFormParams() { + void testParse_shortFormParams() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -108,7 +111,7 @@ public void testParse_shortFormParams() { } @Test - public void testParse_longFormParams() { + void testParse_longFormParams() { // this test does not check credential helpers, scroll down for specialized credential helper // tests Build buildCommand = @@ -157,7 +160,7 @@ public void testParse_longFormParams() { } @Test - public void testParse_buildFileDefaultForContext() { + void testParse_buildFileDefaultForContext() { Build buildCommand = CommandLine.populateCommand( new Build(), "--target", "test-image-ref", "--context", "test-context"); @@ -167,7 +170,7 @@ public void testParse_buildFileDefaultForContext() { } @Test - public void testParse_credentialHelper() { + void testParse_credentialHelper() { Build buildCommand = CommandLine.populateCommand( new Build(), "--target=test-image-ref", "--credential-helper=test-cred-helper"); @@ -181,7 +184,7 @@ public void testParse_credentialHelper() { } @Test - public void testParse_toCredentialHelper() { + void testParse_toCredentialHelper() { Build buildCommand = CommandLine.populateCommand( new Build(), "--target=test-image-ref", "--to-credential-helper=test-cred-helper"); @@ -196,7 +199,7 @@ public void testParse_toCredentialHelper() { } @Test - public void testParse_fromCredentialHelper() { + void testParse_fromCredentialHelper() { Build buildCommand = CommandLine.populateCommand( new Build(), "--target=test-image-ref", "--from-credential-helper=test-cred-helper"); @@ -211,7 +214,7 @@ public void testParse_fromCredentialHelper() { } @Test - public void testParse_usernamePassword() { + void testParse_usernamePassword() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -230,7 +233,7 @@ public void testParse_usernamePassword() { } @Test - public void testParse_toUsernamePassword() { + void testParse_toUsernamePassword() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -248,7 +251,7 @@ public void testParse_toUsernamePassword() { } @Test - public void testParse_fromUsernamePassword() { + void testParse_fromUsernamePassword() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -267,7 +270,7 @@ public void testParse_fromUsernamePassword() { } @Test - public void testParse_toAndFromUsernamePassword() { + void testParse_toAndFromUsernamePassword() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -289,7 +292,7 @@ public void testParse_toAndFromUsernamePassword() { } @Test - public void testParse_toAndFromCredentialHelper() { + void testParse_toAndFromCredentialHelper() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -307,7 +310,7 @@ public void testParse_toAndFromCredentialHelper() { } @Test - public void testParse_toUsernamePasswordAndFromCredentialHelper() { + void testParse_toUsernamePasswordAndFromCredentialHelper() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -327,7 +330,7 @@ public void testParse_toUsernamePasswordAndFromCredentialHelper() { } @Test - public void testParse_toCredentialHelperAndFromUsernamePassword() { + void testParse_toCredentialHelperAndFromUsernamePassword() { Build buildCommand = CommandLine.populateCommand( new Build(), @@ -346,17 +349,16 @@ public void testParse_toCredentialHelperAndFromUsernamePassword() { .hasValue(Credential.from("test-username", "test-password")); } - private Object usernamePasswordPairs() { - return new Object[][] { - {"--username", "--password"}, - {"--to-username", "--to-password"}, - {"--from-username", "--from-password"} - }; + private static Stream usernamePasswordPairs() { + return Stream.of( + Arguments.of("--username", "--password"), + Arguments.of("--to-username", "--to-password"), + Arguments.of("--from-username", "--from-password")); } - @Test - @Parameters(method = "usernamePasswordPairs") - public void testParse_usernameWithoutPassword(String usernameField, String passwordField) { + @ParameterizedTest + @MethodSource("usernamePasswordPairs") + void testParse_usernameWithoutPassword(String usernameField, String passwordField) { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -366,9 +368,9 @@ public void testParse_usernameWithoutPassword(String usernameField, String passw assertThat(mpe.getMessage()).isEqualTo("Error: Missing required argument(s): " + passwordField); } - @Test - @Parameters(method = "usernamePasswordPairs") - public void testParse_passwordWithoutUsername(String usernameField, String passwordField) { + @ParameterizedTest + @MethodSource("usernamePasswordPairs") + void testParse_passwordWithoutUsername(String usernameField, String passwordField) { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -379,25 +381,44 @@ public void testParse_passwordWithoutUsername(String usernameField, String passw .isEqualTo("Error: Missing required argument(s): " + usernameField + "="); } - public String[][] incompatibleCredentialOptions() { - return new String[][] { - {"--credential-helper=x", "--to-credential-helper=x"}, - {"--credential-helper=x", "--from-credential-helper=x"}, - {"--credential-helper=x", "--username=x", "--password=x"}, - {"--credential-helper=x", "--from-username=x", "--from-password=x"}, - {"--credential-helper=x", "--to-username=x", "--to-password=x"}, - {"--username=x", "--password=x", "--from-username=x", "--from-password=x"}, - {"--username=x", "--password=x", "--to-username=x", "--to-password=x"}, - {"--username=x", "--password=x", "--to-credential-helper=x"}, - {"--username=x", "--password=x", "--from-credential-helper=x"}, - {"--from-credential-helper=x", "--from-username=x", "--from-password=x"}, - {"--to-credential-helper=x", "--to-password=x", "--to-username=x"}, - }; + public static Stream incompatibleCredentialOptions() { + return Stream.of( + Arguments.of((Object) new String[] {"--credential-helper=x", "--to-credential-helper=x"}), + Arguments.of((Object) new String[] {"--credential-helper=x", "--from-credential-helper=x"}), + Arguments.of( + (Object) new String[] {"--credential-helper=x", "--username=x", "--password=x"}), + Arguments.of( + (Object) + new String[] {"--credential-helper=x", "--from-username=x", "--from-password=x"}), + Arguments.of( + (Object) new String[] {"--credential-helper=x", "--to-username=x", "--to-password=x"}), + Arguments.of( + (Object) + new String[] { + "--username=x", "--password=x", "--from-username=x", "--from-password=x" + }), + Arguments.of( + (Object) + new String[] { + "--username=x", "--password=x", "--to-username=x", "--to-password=x" + }), + Arguments.of( + (Object) new String[] {"--username=x", "--password=x", "--to-credential-helper=x"}), + Arguments.of( + (Object) new String[] {"--username=x", "--password=x", "--from-credential-helper=x"}), + Arguments.of( + (Object) + new String[] { + "--from-credential-helper=x", "--from-username=x", "--from-password=x" + }), + Arguments.of( + (Object) + new String[] {"--to-credential-helper=x", "--to-password=x", "--to-username=x"})); } - @Test - @Parameters(method = "incompatibleCredentialOptions") - public void testParse_incompatibleCredentialOptions(String[] authArgs) { + @ParameterizedTest + @MethodSource("incompatibleCredentialOptions") + void testParse_incompatibleCredentialOptions(String[] authArgs) { CommandLine.MutuallyExclusiveArgsException meae = assertThrows( CommandLine.MutuallyExclusiveArgsException.class, @@ -410,7 +431,7 @@ public void testParse_incompatibleCredentialOptions(String[] authArgs) { } @Test - public void testValidate_nameMissingFail() { + void testValidate_nameMissingFail() { Build buildCommand = CommandLine.populateCommand(new Build(), "--target=tar://sometar.tar"); CommandLine.ParameterException pex = assertThrows(CommandLine.ParameterException.class, buildCommand.commonCliOptions::validate); @@ -419,7 +440,7 @@ public void testValidate_nameMissingFail() { } @Test - public void testValidate_pass() { + void testValidate_pass() { Build buildCommand = CommandLine.populateCommand( new Build(), "--target=tar://sometar.tar", "--name=test.io/test/test"); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CacheDirectoriesTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CacheDirectoriesTest.java index 4a158da9890..d647582dd00 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CacheDirectoriesTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CacheDirectoriesTest.java @@ -19,25 +19,25 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; -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 picocli.CommandLine; -public class CacheDirectoriesTest { +class CacheDirectoriesTest { - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testCacheDirectories_defaults() throws IOException { + void testCacheDirectories_defaults() throws IOException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), "-t", "ignored"); - Path buildContext = temporaryFolder.newFolder("some-context").toPath(); + Path buildContext = temporaryFolder; CacheDirectories cacheDirectories = CacheDirectories.from(commonCliOptions, buildContext); Path expectedProjectCache = @@ -54,14 +54,14 @@ public void testCacheDirectories_defaults() throws IOException { } @Test - public void testCacheDirectories_configuredValuesIgnoresBuildContext() throws IOException { + void testCacheDirectories_configuredValuesIgnoresBuildContext() throws IOException { CommonCliOptions commonCliOptions = CommandLine.populateCommand( new CommonCliOptions(), "-t=ignored", "--base-image-cache=test-base-image-cache", "--project-cache=test-project-cache"); - Path ignoredContext = temporaryFolder.newFolder("ignored").toPath(); + Path ignoredContext = temporaryFolder; CacheDirectories cacheDirectories = CacheDirectories.from(commonCliOptions, ignoredContext); assertThat(cacheDirectories.getBaseImageCache()).hasValue(Paths.get("test-base-image-cache")); @@ -73,8 +73,8 @@ public void testCacheDirectories_configuredValuesIgnoresBuildContext() throws IO } @Test - public void testCacheDirectories_failIfContextIsNotDirectory() throws IOException { - Path badContext = temporaryFolder.newFile().toPath(); + void testCacheDirectories_failIfContextIsNotDirectory() throws IOException { + Path badContext = File.createTempFile("test", "jib", temporaryFolder.toFile()).toPath(); CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), "-t", "ignored"); @@ -88,10 +88,10 @@ public void testCacheDirectories_failIfContextIsNotDirectory() throws IOExceptio } @Test - public void testGetProjectCacheDirectoryFromProject_sameFileDifferentPaths() throws IOException { - temporaryFolder.newFolder("ignored"); - Path path = temporaryFolder.getRoot().toPath(); - Path indirectPath = temporaryFolder.getRoot().toPath().resolve("ignored").resolve(".."); + void testGetProjectCacheDirectoryFromProject_sameFileDifferentPaths() throws IOException { + new File(temporaryFolder.toFile(), "ignored").mkdirs(); + Path path = temporaryFolder; + Path indirectPath = temporaryFolder.resolve("ignored").resolve(".."); assertThat(path).isNotEqualTo(indirectPath); // the general equality should not hold true assertThat(Files.isSameFile(path, indirectPath)).isTrue(); // path equality holds @@ -102,7 +102,7 @@ public void testGetProjectCacheDirectoryFromProject_sameFileDifferentPaths() thr } @Test - public void testGetProjectCacheDirectoryFromProject_different() { + void testGetProjectCacheDirectoryFromProject_different() { assertThat(CacheDirectories.getProjectCacheDirectoryFromProject(Paths.get("1"))) .isNotEqualTo(CacheDirectories.getProjectCacheDirectoryFromProject(Paths.get("2"))); } diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java index 98f9358eeae..6a8a7afdccb 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerBuildersTest.java @@ -33,21 +33,24 @@ import java.nio.file.Paths; import java.util.Collections; import java.util.Optional; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ContainerBuilders}. */ -@RunWith(MockitoJUnitRunner.class) -public class ContainerBuildersTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ContainerBuildersTest { @Mock private CommonCliOptions mockCommonCliOptions; @Mock private ConsoleLogger mockLogger; @Test - public void testCreate_dockerBaseImage() + void testCreate_dockerBaseImage() throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { JibContainerBuilder containerBuilder = ContainerBuilders.create( @@ -63,7 +66,7 @@ public void testCreate_dockerBaseImage() } @Test - public void testCreate_registry() + void testCreate_registry() throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { JibContainerBuilder containerBuilder = ContainerBuilders.create( @@ -82,7 +85,7 @@ public void testCreate_registry() } @Test - public void testCreate_tarBase() + void testCreate_tarBase() throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException { JibContainerBuilder containerBuilder = ContainerBuilders.create( @@ -97,7 +100,7 @@ public void testCreate_tarBase() } @Test - public void testCreate_platforms() throws IOException, InvalidImageReferenceException { + void testCreate_platforms() throws IOException, InvalidImageReferenceException { JibContainerBuilder containerBuilder = ContainerBuilders.create( "registry://registry-image-ref", diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerizersTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerizersTest.java index 250aff2ece6..7640819602c 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerizersTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/ContainerizersTest.java @@ -31,20 +31,26 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.rules.TemporaryFolder; +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.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import picocli.CommandLine; -public class ContainerizersTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ContainerizersTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Rule public final MockitoRule mockitoRule = MockitoJUnit.rule(); // Containerizers will add system properties based on cli properties @Rule @@ -56,14 +62,14 @@ public class ContainerizersTest { private static final Path baseImageCache = Paths.get("base-image-cache-for-test"); private static final Path applicationCache = Paths.get("application-cache-for-test"); - @Before - public void initCaches() { + @BeforeEach + void initCaches() { Mockito.when(cacheDirectories.getBaseImageCache()).thenReturn(Optional.of(baseImageCache)); Mockito.when(cacheDirectories.getApplicationLayersCache()).thenReturn(applicationCache); } @Test - public void testApplyConfiguration_defaults() + void testApplyConfiguration_defaults() throws InvalidImageReferenceException, FileNotFoundException, CacheDirectoryCreationException { CommonCliOptions commonCliOptions = @@ -84,7 +90,7 @@ public void testApplyConfiguration_defaults() } @Test - public void testApplyConfiguration_withValues() + void testApplyConfiguration_withValues() throws InvalidImageReferenceException, CacheDirectoryCreationException, FileNotFoundException { CommonCliOptions commonCliOptions = @@ -108,8 +114,7 @@ public void testApplyConfiguration_withValues() } @Test - public void testFrom_dockerDaemonImage() - throws InvalidImageReferenceException, FileNotFoundException { + void testFrom_dockerDaemonImage() throws InvalidImageReferenceException, FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand( new CommonCliOptions(), "-t", "docker://gcr.io/test/test-image-ref"); @@ -127,8 +132,8 @@ public void testFrom_dockerDaemonImage() } @Test - public void testFrom_tarImage() throws InvalidImageReferenceException, IOException { - Path tarPath = temporaryFolder.getRoot().toPath().resolve("test-tar.tar"); + void testFrom_tarImage() throws InvalidImageReferenceException, IOException { + Path tarPath = temporaryFolder.resolve("test-tar.tar"); CommonCliOptions commonCliOptions = CommandLine.populateCommand( new CommonCliOptions(), @@ -148,7 +153,7 @@ public void testFrom_tarImage() throws InvalidImageReferenceException, IOExcepti } @Test - public void testFrom_registryImage() throws InvalidImageReferenceException, IOException { + void testFrom_registryImage() throws InvalidImageReferenceException, IOException { CommonCliOptions commonCliOptions = CommandLine.populateCommand( new CommonCliOptions(), "-t", "registry://gcr.io/test/test-image-ref"); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CredentialsTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CredentialsTest.java index 7ba6130aee9..eb541446fca 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CredentialsTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/CredentialsTest.java @@ -23,35 +23,40 @@ import com.google.cloud.tools.jib.api.Credential; import com.google.cloud.tools.jib.plugins.common.DefaultCredentialRetrievers; import java.io.FileNotFoundException; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; +import java.util.stream.Stream; import org.apache.commons.lang3.ArrayUtils; import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import picocli.CommandLine; -@RunWith(JUnitParamsRunner.class) -public class CredentialsTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CredentialsTest { private static final String[] DEFAULT_ARGS = {"--target=ignored"}; @Rule public final MockitoRule mockitoJUnit = MockitoJUnit.rule(); @Mock private DefaultCredentialRetrievers defaultCredentialRetrievers; - private String[][] paramsToNone() { - return new String[][] { - {"--from-credential-helper=ignored"}, {"--from-username=ignored", "--from-password=ignored"}, - }; + private static Stream paramsToNone() { + return Stream.of( + Arguments.of((Object) new String[] {"--from-credential-helper=ignored"}), + Arguments.of((Object) new String[] {"--from-username=ignored", "--from-password=ignored"})); } - @Test - @Parameters(method = "paramsToNone") - public void testGetToCredentialRetriever_none(String[] args) throws FileNotFoundException { + @ParameterizedTest + @MethodSource("paramsToNone") + void testGetToCredentialRetriever_none(String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); Credentials.getToCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers); @@ -59,15 +64,15 @@ public void testGetToCredentialRetriever_none(String[] args) throws FileNotFound verifyNoMoreInteractions(defaultCredentialRetrievers); } - private String[][] paramsFromNone() { - return new String[][] { - {"--to-credential-helper=ignored"}, {"--to-username=ignored", "--to-password=ignored"}, - }; + private static Stream paramsFromNone() { + return Stream.of( + Arguments.of((Object) new String[] {"--to-credential-helper=ignored"}), + Arguments.of((Object) new String[] {"--to-username=ignored", "--to-password=ignored"})); } - @Test - @Parameters(method = "paramsFromNone") - public void testGetFromCredentialRetriever_none(String[] args) throws FileNotFoundException { + @ParameterizedTest + @MethodSource("paramsFromNone") + void testGetFromCredentialRetriever_none(String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); Credentials.getFromCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers); @@ -75,18 +80,23 @@ public void testGetFromCredentialRetriever_none(String[] args) throws FileNotFou verifyNoMoreInteractions(defaultCredentialRetrievers); } - private String[][] paramsToCredHelper() { - return new String[][] { - {"--credential-helper=abc"}, - {"--to-credential-helper=abc"}, - {"--to-credential-helper=abc", "--from-credential-helper=ignored"}, - {"--to-credential-helper=abc", "--from-username=ignored", "--from-password=ignored"}, - }; + private static Stream paramsToCredHelper() { + return Stream.of( + Arguments.of((Object) new String[] {"--credential-helper=abc"}), + Arguments.of((Object) new String[] {"--to-credential-helper=abc"}), + Arguments.of( + (Object) + new String[] {"--to-credential-helper=abc", "--from-credential-helper=ignored"}), + Arguments.of( + (Object) + new String[] { + "--to-credential-helper=abc", "--from-username=ignored", "--from-password=ignored" + })); } - @Test - @Parameters(method = "paramsToCredHelper") - public void testGetToCredentialRetriever_credHelper(String[] args) throws FileNotFoundException { + @ParameterizedTest + @MethodSource("paramsToCredHelper") + void testGetToCredentialRetriever_credHelper(String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); Credentials.getToCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers); @@ -95,18 +105,23 @@ public void testGetToCredentialRetriever_credHelper(String[] args) throws FileNo verifyNoMoreInteractions(defaultCredentialRetrievers); } - private String[][] paramsFromCredHelper() { - return new String[][] { - {"--credential-helper=abc"}, - {"--from-credential-helper=abc"}, - {"--from-credential-helper=abc", "--to-credential-helper=ignored"}, - {"--from-credential-helper=abc", "--to-username=ignored", "--to-password=ignored"}, - }; + private static Stream paramsFromCredHelper() { + return Stream.of( + Arguments.of((Object) new String[] {"--credential-helper=abc"}), + Arguments.of((Object) new String[] {"--from-credential-helper=abc"}), + Arguments.of( + (Object) + new String[] {"--from-credential-helper=abc", "--to-credential-helper=ignored"}), + Arguments.of( + (Object) + new String[] { + "--from-credential-helper=abc", "--to-username=ignored", "--to-password=ignored" + })); } - @Test - @Parameters(method = "paramsFromCredHelper") - public void testGetFromCredentialHelper(String[] args) throws FileNotFoundException { + @ParameterizedTest + @MethodSource("paramsFromCredHelper") + void testGetFromCredentialHelper(String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); Credentials.getFromCredentialRetrievers(commonCliOptions, defaultCredentialRetrievers); @@ -115,29 +130,38 @@ public void testGetFromCredentialHelper(String[] args) throws FileNotFoundExcept verifyNoMoreInteractions(defaultCredentialRetrievers); } - public Object paramsToUsernamePassword() { - return new Object[][] { - {"--username/--password", new String[] {"--username=abc", "--password=xyz"}}, - {"--to-username/--to-password", new String[] {"--to-username=abc", "--to-password=xyz"}}, - { - "--to-username/--to-password", - new String[] { - "--to-username=abc", - "--to-password=xyz", - "--from-username=ignored", - "--from-password=ignored" - } - }, - { - "--to-username/--to-password", - new String[] {"--to-username=abc", "--to-password=xyz", "--from-credential-helper=ignored"} - } - }; + public static Stream paramsToUsernamePassword() { + return Stream.of( + Arguments.of( + new Object[] { + "--username/--password", new String[] {"--username=abc", "--password=xyz"} + }), + Arguments.of( + new Object[] { + "--to-username/--to-password", new String[] {"--to-username=abc", "--to-password=xyz"} + }), + Arguments.of( + new Object[] { + "--to-username/--to-password", + new String[] { + "--to-username=abc", + "--to-password=xyz", + "--from-username=ignored", + "--from-password=ignored" + } + }), + Arguments.of( + new Object[] { + "--to-username/--to-password", + new String[] { + "--to-username=abc", "--to-password=xyz", "--from-credential-helper=ignored" + } + })); } - @Test - @Parameters(method = "paramsToUsernamePassword") - public void testGetToUsernamePassword(String expectedSource, String[] args) + @ParameterizedTest + @MethodSource("paramsToUsernamePassword") + void testGetToUsernamePassword(String expectedSource, String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); @@ -150,34 +174,39 @@ public void testGetToUsernamePassword(String expectedSource, String[] args) verifyNoMoreInteractions(defaultCredentialRetrievers); } - public Object paramsFromUsernamePassword() { - return new Object[][] { - {"--username/--password", new String[] {"--username=abc", "--password=xyz"}}, - { - "--from-username/--from-password", - new String[] {"--from-username=abc", "--from-password=xyz"} - }, - { - "--from-username/--from-password", - new String[] { - "--from-username=abc", - "--from-password=xyz", - "--to-username=ignored", - "--to-password=ignored" - } - }, - { - "--from-username/--from-password", - new String[] { - "--from-username=abc", "--from-password=xyz", "--to-credential-helper=ignored" - } - }, - }; + public static Stream paramsFromUsernamePassword() { + return Stream.of( + Arguments.of( + new Object[] { + "--username/--password", new String[] {"--username=abc", "--password=xyz"} + }), + Arguments.of( + new Object[] { + "--from-username/--from-password", + new String[] {"--from-username=abc", "--from-password=xyz"} + }), + Arguments.of( + new Object[] { + "--from-username/--from-password", + new String[] { + "--from-username=abc", + "--from-password=xyz", + "--to-username=ignored", + "--to-password=ignored" + } + }), + Arguments.of( + new Object[] { + "--from-username/--from-password", + new String[] { + "--from-username=abc", "--from-password=xyz", "--to-credential-helper=ignored" + } + })); } - @Test - @Parameters(method = "paramsFromUsernamePassword") - public void testGetFromUsernamePassword(String expectedSource, String[] args) + @ParameterizedTest + @MethodSource("paramsFromUsernamePassword") + void testGetFromUsernamePassword(String expectedSource, String[] args) throws FileNotFoundException { CommonCliOptions commonCliOptions = CommandLine.populateCommand(new CommonCliOptions(), ArrayUtils.addAll(DEFAULT_ARGS, args)); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/InstantsTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/InstantsTest.java index ff822be7a74..e1ad86ec5f1 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/InstantsTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/InstantsTest.java @@ -18,25 +18,25 @@ import java.time.Instant; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Instants}. */ -public class InstantsTest { +class InstantsTest { @Test - public void testFromMillisOrIso8601_millis() { + void testFromMillisOrIso8601_millis() { Instant parsed = Instants.fromMillisOrIso8601("100", "ignored"); Assert.assertEquals(Instant.ofEpochMilli(100), parsed); } @Test - public void testFromMillisOrIso8601_iso8601() { + void testFromMillisOrIso8601_iso8601() { Instant parsed = Instants.fromMillisOrIso8601("2020-06-08T14:54:36+00:00", "ignored"); Assert.assertEquals(Instant.parse("2020-06-08T14:54:36Z"), parsed); } @Test - public void testFromMillisOrIso8601_failed() { + void testFromMillisOrIso8601_failed() { try { Instants.fromMillisOrIso8601("bad-time", "testFieldName"); Assert.fail(); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java index 3ba25124908..a29fc40158b 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JarTest.java @@ -33,19 +33,25 @@ import com.google.common.collect.ImmutableSet; import java.nio.file.Paths; import java.time.Instant; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; +import java.util.stream.Stream; import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import picocli.CommandLine; import picocli.CommandLine.MissingParameterException; -@RunWith(JUnitParamsRunner.class) -public class JarTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JarTest { @Test - public void testParse_missingRequiredParams_targetImage() { + void testParse_missingRequiredParams_targetImage() { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -56,7 +62,7 @@ public void testParse_missingRequiredParams_targetImage() { } @Test - public void testParse_missingRequiredParams_jarfile() { + void testParse_missingRequiredParams_jarfile() { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -65,7 +71,8 @@ public void testParse_missingRequiredParams_jarfile() { } @Test - public void testParse_defaults() { + @SuppressWarnings("java:S5961") + void testParse_defaults() { Jar jarCommand = CommandLine.populateCommand(new Jar(), "-t", "test-image-ref", "my-app.jar"); CommonCliOptions commonCliOptions = jarCommand.commonCliOptions; CommonContainerConfigCliOptions commonContainerConfigCliOptions = @@ -103,7 +110,7 @@ public void testParse_defaults() { } @Test - public void testParse_shortFormParams() { + void testParse_shortFormParams() { Jar jarCommand = CommandLine.populateCommand(new Jar(), "-t=test-image-ref", "my-app.jar"); CommonCliOptions commonCliOptions = jarCommand.commonCliOptions; assertThat(commonCliOptions.getTargetImage()).isEqualTo("test-image-ref"); @@ -127,7 +134,7 @@ public void testParse_shortFormParams() { } @Test - public void testParse_longFormParams() { + void testParse_longFormParams() { // this test does not check credential helpers, scroll down for specialized credential helper // tests Jar jarCommand = @@ -168,7 +175,7 @@ public void testParse_longFormParams() { } @Test - public void testParse_credentialHelper() { + void testParse_credentialHelper() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -185,7 +192,7 @@ public void testParse_credentialHelper() { } @Test - public void testParse_toCredentialHelper() { + void testParse_toCredentialHelper() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -203,7 +210,7 @@ public void testParse_toCredentialHelper() { } @Test - public void testParse_fromCredentialHelper() { + void testParse_fromCredentialHelper() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -221,7 +228,7 @@ public void testParse_fromCredentialHelper() { } @Test - public void testParse_usernamePassword() { + void testParse_usernamePassword() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -241,7 +248,7 @@ public void testParse_usernamePassword() { } @Test - public void testParse_toUsernamePassword() { + void testParse_toUsernamePassword() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -260,7 +267,7 @@ public void testParse_toUsernamePassword() { } @Test - public void testParse_fromUsernamePassword() { + void testParse_fromUsernamePassword() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -280,7 +287,7 @@ public void testParse_fromUsernamePassword() { } @Test - public void testParse_toAndFromUsernamePassword() { + void testParse_toAndFromUsernamePassword() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -303,7 +310,7 @@ public void testParse_toAndFromUsernamePassword() { } @Test - public void testParse_toAndFromCredentialHelper() { + void testParse_toAndFromCredentialHelper() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -322,7 +329,7 @@ public void testParse_toAndFromCredentialHelper() { } @Test - public void testParse_toUsernamePasswordAndFromCredentialHelper() { + void testParse_toUsernamePasswordAndFromCredentialHelper() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -343,7 +350,7 @@ public void testParse_toUsernamePasswordAndFromCredentialHelper() { } @Test - public void testParse_toCredentialHelperAndFromUsernamePassword() { + void testParse_toCredentialHelperAndFromUsernamePassword() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -363,17 +370,16 @@ public void testParse_toCredentialHelperAndFromUsernamePassword() { .hasValue(Credential.from("test-username", "test-password")); } - private Object usernamePasswordPairs() { - return new Object[][] { - {"--username", "--password"}, - {"--to-username", "--to-password"}, - {"--from-username", "--from-password"} - }; + private static Stream usernamePasswordPairs() { + return Stream.of( + Arguments.of(new Object[] {"--username", "--password"}), + Arguments.of(new Object[] {"--to-username", "--to-password"}), + Arguments.of(new Object[] {"--from-username", "--from-password"})); } - @Test - @Parameters(method = "usernamePasswordPairs") - public void testParse_usernameWithoutPassword(String usernameField, String passwordField) { + @ParameterizedTest + @MethodSource("usernamePasswordPairs") + void testParse_usernameWithoutPassword(String usernameField, String passwordField) { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -389,9 +395,9 @@ public void testParse_usernameWithoutPassword(String usernameField, String passw .isEqualTo("Error: Missing required argument(s): " + passwordField); } - @Test - @Parameters(method = "usernamePasswordPairs") - public void testParse_passwordWithoutUsername(String usernameField, String passwordField) { + @ParameterizedTest + @MethodSource("usernamePasswordPairs") + void testParse_passwordWithoutUsername(String usernameField, String passwordField) { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -407,25 +413,44 @@ public void testParse_passwordWithoutUsername(String usernameField, String passw .isEqualTo("Error: Missing required argument(s): " + usernameField + "="); } - public String[][] incompatibleCredentialOptions() { - return new String[][] { - {"--credential-helper=x", "--to-credential-helper=x"}, - {"--credential-helper=x", "--from-credential-helper=x"}, - {"--credential-helper=x", "--username=x", "--password=x"}, - {"--credential-helper=x", "--from-username=x", "--from-password=x"}, - {"--credential-helper=x", "--to-username=x", "--to-password=x"}, - {"--username=x", "--password=x", "--from-username=x", "--from-password=x"}, - {"--username=x", "--password=x", "--to-username=x", "--to-password=x"}, - {"--username=x", "--password=x", "--to-credential-helper=x"}, - {"--username=x", "--password=x", "--from-credential-helper=x"}, - {"--from-credential-helper=x", "--from-username=x", "--from-password=x"}, - {"--to-credential-helper=x", "--to-password=x", "--to-username=x"}, - }; - } - - @Test - @Parameters(method = "incompatibleCredentialOptions") - public void testParse_incompatibleCredentialOptions(String[] authArgs) { + public static Stream incompatibleCredentialOptions() { + return Stream.of( + Arguments.of((Object) new String[] {"--credential-helper=x", "--to-credential-helper=x"}), + Arguments.of((Object) new String[] {"--credential-helper=x", "--from-credential-helper=x"}), + Arguments.of( + (Object) new String[] {"--credential-helper=x", "--username=x", "--password=x"}), + Arguments.of( + (Object) + new String[] {"--credential-helper=x", "--from-username=x", "--from-password=x"}), + Arguments.of( + (Object) new String[] {"--credential-helper=x", "--to-username=x", "--to-password=x"}), + Arguments.of( + (Object) + new String[] { + "--username=x", "--password=x", "--from-username=x", "--from-password=x" + }), + Arguments.of( + (Object) + new String[] { + "--username=x", "--password=x", "--to-username=x", "--to-password=x" + }), + Arguments.of( + (Object) new String[] {"--username=x", "--password=x", "--to-credential-helper=x"}), + Arguments.of( + (Object) new String[] {"--username=x", "--password=x", "--from-credential-helper=x"}), + Arguments.of( + (Object) + new String[] { + "--from-credential-helper=x", "--from-username=x", "--from-password=x" + }), + Arguments.of( + (Object) + new String[] {"--to-credential-helper=x", "--to-password=x", "--to-username=x"})); + } + + @ParameterizedTest + @MethodSource("incompatibleCredentialOptions") + void testParse_incompatibleCredentialOptions(String[] authArgs) { CommandLine.MutuallyExclusiveArgsException meae = assertThrows( CommandLine.MutuallyExclusiveArgsException.class, @@ -438,7 +463,7 @@ public void testParse_incompatibleCredentialOptions(String[] authArgs) { } @Test - public void testParse_from() { + void testParse_from() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--from=base-image-ref", "my-app.jar"); @@ -446,7 +471,7 @@ public void testParse_from() { } @Test - public void testParse_jvmFlags() { + void testParse_jvmFlags() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--jvm-flags=jvm-flag1,jvm-flag2", "my-app.jar"); @@ -454,7 +479,7 @@ public void testParse_jvmFlags() { } @Test - public void testParse_exposedPorts() { + void testParse_exposedPorts() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--expose=8080,3306", "my-app.jar"); @@ -463,7 +488,7 @@ public void testParse_exposedPorts() { } @Test - public void testParse_volumes() { + void testParse_volumes() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--volumes=/volume1,/volume2", "my-app.jar"); @@ -473,7 +498,7 @@ public void testParse_volumes() { } @Test - public void testParse_environment() { + void testParse_environment() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -485,7 +510,7 @@ public void testParse_environment() { } @Test - public void testParse_labels() { + void testParse_labels() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -497,7 +522,7 @@ public void testParse_labels() { } @Test - public void testParse_user() { + void testParse_user() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--user=customUser", "my-app.jar"); @@ -505,7 +530,7 @@ public void testParse_user() { } @Test - public void testParse_imageFormat() { + void testParse_imageFormat() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--image-format=OCI", "my-app.jar"); @@ -513,7 +538,7 @@ public void testParse_imageFormat() { } @Test - public void testParse_invalidImageFormat() { + void testParse_invalidImageFormat() { CommandLine.ParameterException exception = assertThrows( CommandLine.ParameterException.class, @@ -527,7 +552,7 @@ public void testParse_invalidImageFormat() { } @Test - public void testParse_programArguments() { + void testParse_programArguments() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--program-args=arg1,arg2", "my-app.jar"); @@ -536,7 +561,7 @@ public void testParse_programArguments() { } @Test - public void testParse_entrypoint() { + void testParse_entrypoint() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--entrypoint=java -cp myClass", "my-app.jar"); @@ -545,7 +570,7 @@ public void testParse_entrypoint() { } @Test - public void testParse_creationTime_milliseconds() { + void testParse_creationTime_milliseconds() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--creation-time=23", "my-app.jar"); @@ -554,7 +579,7 @@ public void testParse_creationTime_milliseconds() { } @Test - public void testParse_creationTime_iso8601() { + void testParse_creationTime_iso8601() { Jar jarCommand = CommandLine.populateCommand( new Jar(), @@ -566,7 +591,7 @@ public void testParse_creationTime_iso8601() { } @Test - public void testParse_mode() { + void testParse_mode() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--mode=packaged", "my-app.jar"); @@ -574,7 +599,7 @@ public void testParse_mode() { } @Test - public void testParse_invalidMode() { + void testParse_invalidMode() { CommandLine.ParameterException exception = assertThrows( CommandLine.ParameterException.class, @@ -588,7 +613,7 @@ public void testParse_invalidMode() { } @Test - public void testValidate_nameMissingFail() { + void testValidate_nameMissingFail() { Jar jarCommand = CommandLine.populateCommand(new Jar(), "--target=tar://sometar.tar", "my-app.jar"); CommandLine.ParameterException pex = @@ -599,7 +624,7 @@ public void testValidate_nameMissingFail() { } @Test - public void testValidate_pass() { + void testValidate_pass() { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=tar://sometar.tar", "--name=test.io/test/test", "my-app.jar"); @@ -608,14 +633,14 @@ public void testValidate_pass() { } @Test - public void testIsJetty_noCustomBaseImage() throws InvalidImageReferenceException { + void testIsJetty_noCustomBaseImage() throws InvalidImageReferenceException { Jar jarCommand = CommandLine.populateCommand(new Jar(), "--target=test-image-ref", "my-app.jar"); assertThat(jarCommand.commonContainerConfigCliOptions.isJettyBaseimage()).isTrue(); } @Test - public void testIsJetty_nonJetty() throws InvalidImageReferenceException { + void testIsJetty_nonJetty() throws InvalidImageReferenceException { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--from=base-image", "my-app.jar"); @@ -623,7 +648,7 @@ public void testIsJetty_nonJetty() throws InvalidImageReferenceException { } @Test - public void testIsJetty_customJetty() throws InvalidImageReferenceException { + void testIsJetty_customJetty() throws InvalidImageReferenceException { Jar jarCommand = CommandLine.populateCommand( new Jar(), "--target=test-image-ref", "--from=jetty:tag", "my-app.jar"); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JibCliTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JibCliTest.java index 72c78a06147..fc8f86133a5 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JibCliTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/JibCliTest.java @@ -49,25 +49,27 @@ import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -@RunWith(MockitoJUnitRunner.class) -public class JibCliTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JibCliTest { @Mock private GlobalConfig globalConfig; @Mock private ConsoleLogger logger; - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock private JibContainer mockJibContainer; @Test - public void testConfigureHttpLogging() { + void testConfigureHttpLogging() { Logger logger = JibCli.configureHttpLogging(Level.ALL); assertThat(logger.getName()).isEqualTo("com.google.api.client.http.HttpTransport"); assertThat(logger.getLevel()).isEqualTo(Level.ALL); @@ -79,7 +81,7 @@ public void testConfigureHttpLogging() { } @Test - public void testLogTerminatingException() { + void testLogTerminatingException() { JibCli.logTerminatingException(logger, new IOException("test error message"), false); verify(logger) @@ -88,7 +90,7 @@ public void testLogTerminatingException() { } @Test - public void testLogTerminatingException_stackTrace() { + void testLogTerminatingException_stackTrace() { JibCli.logTerminatingException(logger, new IOException("test error message"), true); String stackTraceLine = @@ -100,7 +102,7 @@ public void testLogTerminatingException_stackTrace() { } @Test - public void testNewUpdateChecker_noUpdateCheck() throws ExecutionException, InterruptedException { + void testNewUpdateChecker_noUpdateCheck() throws ExecutionException, InterruptedException { when(globalConfig.isDisableUpdateCheck()).thenReturn(true); Future> updateChecker = JibCli.newUpdateChecker(globalConfig, Verbosity.info, ignored -> {}); @@ -108,7 +110,7 @@ public void testNewUpdateChecker_noUpdateCheck() throws ExecutionException, Inte } @Test - public void testFinishUpdateChecker_correctMessageLogged() { + void testFinishUpdateChecker_correctMessageLogged() { Future> updateCheckFuture = Futures.immediateFuture(Optional.of("2.0.0")); JibCli.finishUpdateChecker(logger, updateCheckFuture); verify(logger) @@ -123,8 +125,7 @@ public void testFinishUpdateChecker_correctMessageLogged() { } @Test - public void testWriteImageJson() - throws InvalidImageReferenceException, IOException, DigestException { + void testWriteImageJson() throws InvalidImageReferenceException, IOException, DigestException { String imageId = "sha256:61bb3ec31a47cb730eb58a38bbfa813761a51dca69d10e39c24c3d00a7b2c7a9"; String digest = "sha256:3f1be7e19129edb202c071a659a4db35280ab2bb1a16f223bfd5d1948657b6fc"; when(mockJibContainer.getTargetImage()) @@ -133,7 +134,7 @@ public void testWriteImageJson() when(mockJibContainer.getDigest()).thenReturn(DescriptorDigest.fromDigest(digest)); when(mockJibContainer.getTags()).thenReturn(ImmutableSet.of("latest", "tag-2")); - Path outputPath = temporaryFolder.getRoot().toPath().resolve("jib-image.json"); + Path outputPath = temporaryFolder.resolve("jib-image.json"); JibCli.writeImageJson(Optional.of(outputPath), mockJibContainer); String outputJson = new String(Files.readAllBytes(outputPath), StandardCharsets.UTF_8); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/WarTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/WarTest.java index 9c87ac6778a..b278952339f 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/WarTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/WarTest.java @@ -32,19 +32,25 @@ import com.google.common.collect.ImmutableSet; import java.nio.file.Paths; import java.time.Instant; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; +import java.util.stream.Stream; import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import picocli.CommandLine; import picocli.CommandLine.MissingParameterException; -@RunWith(JUnitParamsRunner.class) -public class WarTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class WarTest { @Test - public void testParse_missingRequiredParams_targetImage() { + void testParse_missingRequiredParams_targetImage() { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -55,7 +61,7 @@ public void testParse_missingRequiredParams_targetImage() { } @Test - public void testParse_missingRequiredParams_warfile() { + void testParse_missingRequiredParams_warfile() { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -64,7 +70,8 @@ public void testParse_missingRequiredParams_warfile() { } @Test - public void testParse_defaults() { + @SuppressWarnings("java:S5961") + void testParse_defaults() { War warCommand = CommandLine.populateCommand(new War(), "-t", "test-image-ref", "my-app.war"); CommonCliOptions commonCliOptions = warCommand.commonCliOptions; CommonContainerConfigCliOptions commonContainerConfigCliOptions = @@ -101,7 +108,7 @@ public void testParse_defaults() { } @Test - public void testParse_shortFormParams() { + void testParse_shortFormParams() { War warCommand = CommandLine.populateCommand(new War(), "-t=test-image-ref", "my-app.war"); CommonCliOptions commonCliOptions = warCommand.commonCliOptions; assertThat(commonCliOptions.getTargetImage()).isEqualTo("test-image-ref"); @@ -125,7 +132,7 @@ public void testParse_shortFormParams() { } @Test - public void testParse_longFormParams() { + void testParse_longFormParams() { // this test does not check credential helpers, scroll down for specialized credential helper // tests War warCommand = @@ -166,7 +173,7 @@ public void testParse_longFormParams() { } @Test - public void testParse_credentialHelper() { + void testParse_credentialHelper() { War warCommand = CommandLine.populateCommand( new War(), @@ -183,7 +190,7 @@ public void testParse_credentialHelper() { } @Test - public void testParse_toCredentialHelper() { + void testParse_toCredentialHelper() { War warCommand = CommandLine.populateCommand( new War(), @@ -201,7 +208,7 @@ public void testParse_toCredentialHelper() { } @Test - public void testParse_fromCredentialHelper() { + void testParse_fromCredentialHelper() { War warCommand = CommandLine.populateCommand( new War(), @@ -219,7 +226,7 @@ public void testParse_fromCredentialHelper() { } @Test - public void testParse_usernamePassword() { + void testParse_usernamePassword() { War warCommand = CommandLine.populateCommand( new War(), @@ -239,7 +246,7 @@ public void testParse_usernamePassword() { } @Test - public void testParse_toUsernamePassword() { + void testParse_toUsernamePassword() { War warCommand = CommandLine.populateCommand( new War(), @@ -258,7 +265,7 @@ public void testParse_toUsernamePassword() { } @Test - public void testParse_fromUsernamePassword() { + void testParse_fromUsernamePassword() { War warCommand = CommandLine.populateCommand( new War(), @@ -278,7 +285,7 @@ public void testParse_fromUsernamePassword() { } @Test - public void testParse_toAndFromUsernamePassword() { + void testParse_toAndFromUsernamePassword() { War warCommand = CommandLine.populateCommand( new War(), @@ -301,7 +308,7 @@ public void testParse_toAndFromUsernamePassword() { } @Test - public void testParse_toAndFromCredentialHelper() { + void testParse_toAndFromCredentialHelper() { War warCommand = CommandLine.populateCommand( new War(), @@ -320,7 +327,7 @@ public void testParse_toAndFromCredentialHelper() { } @Test - public void testParse_toUsernamePasswordAndFromCredentialHelper() { + void testParse_toUsernamePasswordAndFromCredentialHelper() { War warCommand = CommandLine.populateCommand( new War(), @@ -341,7 +348,7 @@ public void testParse_toUsernamePasswordAndFromCredentialHelper() { } @Test - public void testParse_toCredentialHelperAndFromUsernamePassword() { + void testParse_toCredentialHelperAndFromUsernamePassword() { War warCommand = CommandLine.populateCommand( new War(), @@ -361,17 +368,16 @@ public void testParse_toCredentialHelperAndFromUsernamePassword() { .hasValue(Credential.from("test-username", "test-password")); } - private Object usernamePasswordPairs() { - return new Object[][] { - {"--username", "--password"}, - {"--to-username", "--to-password"}, - {"--from-username", "--from-password"} - }; + private static Stream usernamePasswordPairs() { + return Stream.of( + Arguments.of(new Object[] {"--username", "--password"}), + Arguments.of(new Object[] {"--to-username", "--to-password"}), + Arguments.of(new Object[] {"--from-username", "--from-password"})); } - @Test - @Parameters(method = "usernamePasswordPairs") - public void testParse_usernameWithoutPassword(String usernameField, String passwordField) { + @ParameterizedTest + @MethodSource("usernamePasswordPairs") + void testParse_usernameWithoutPassword(String usernameField, String passwordField) { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -387,9 +393,9 @@ public void testParse_usernameWithoutPassword(String usernameField, String passw .isEqualTo("Error: Missing required argument(s): " + passwordField); } - @Test - @Parameters(method = "usernamePasswordPairs") - public void testParse_passwordWithoutUsername(String usernameField, String passwordField) { + @ParameterizedTest + @MethodSource("usernamePasswordPairs") + void testParse_passwordWithoutUsername(String usernameField, String passwordField) { MissingParameterException mpe = assertThrows( MissingParameterException.class, @@ -405,25 +411,44 @@ public void testParse_passwordWithoutUsername(String usernameField, String passw .isEqualTo("Error: Missing required argument(s): " + usernameField + "="); } - public String[][] incompatibleCredentialOptions() { - return new String[][] { - {"--credential-helper=x", "--to-credential-helper=x"}, - {"--credential-helper=x", "--from-credential-helper=x"}, - {"--credential-helper=x", "--username=x", "--password=x"}, - {"--credential-helper=x", "--from-username=x", "--from-password=x"}, - {"--credential-helper=x", "--to-username=x", "--to-password=x"}, - {"--username=x", "--password=x", "--from-username=x", "--from-password=x"}, - {"--username=x", "--password=x", "--to-username=x", "--to-password=x"}, - {"--username=x", "--password=x", "--to-credential-helper=x"}, - {"--username=x", "--password=x", "--from-credential-helper=x"}, - {"--from-credential-helper=x", "--from-username=x", "--from-password=x"}, - {"--to-credential-helper=x", "--to-password=x", "--to-username=x"}, - }; - } - - @Test - @Parameters(method = "incompatibleCredentialOptions") - public void testParse_incompatibleCredentialOptions(String[] authArgs) { + public static Stream incompatibleCredentialOptions() { + return Stream.of( + Arguments.of((Object) new String[] {"--credential-helper=x", "--to-credential-helper=x"}), + Arguments.of((Object) new String[] {"--credential-helper=x", "--from-credential-helper=x"}), + Arguments.of( + (Object) new String[] {"--credential-helper=x", "--username=x", "--password=x"}), + Arguments.of( + (Object) + new String[] {"--credential-helper=x", "--from-username=x", "--from-password=x"}), + Arguments.of( + (Object) new String[] {"--credential-helper=x", "--to-username=x", "--to-password=x"}), + Arguments.of( + (Object) + new String[] { + "--username=x", "--password=x", "--from-username=x", "--from-password=x" + }), + Arguments.of( + (Object) + new String[] { + "--username=x", "--password=x", "--to-username=x", "--to-password=x" + }), + Arguments.of( + (Object) new String[] {"--username=x", "--password=x", "--to-credential-helper=x"}), + Arguments.of( + (Object) new String[] {"--username=x", "--password=x", "--from-credential-helper=x"}), + Arguments.of( + (Object) + new String[] { + "--from-credential-helper=x", "--from-username=x", "--from-password=x" + }), + Arguments.of( + (Object) + new String[] {"--to-credential-helper=x", "--to-password=x", "--to-username=x"})); + } + + @ParameterizedTest + @MethodSource("incompatibleCredentialOptions") + void testParse_incompatibleCredentialOptions(String[] authArgs) { CommandLine.MutuallyExclusiveArgsException meae = assertThrows( CommandLine.MutuallyExclusiveArgsException.class, @@ -436,7 +461,7 @@ public void testParse_incompatibleCredentialOptions(String[] authArgs) { } @Test - public void testParse_from() { + void testParse_from() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--from=base-image-ref", "my-app.war"); @@ -444,7 +469,7 @@ public void testParse_from() { } @Test - public void testParse_appRoot() { + void testParse_appRoot() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--app-root=/path/to/app", "my-app.war"); @@ -452,7 +477,7 @@ public void testParse_appRoot() { } @Test - public void testParse_exposedPorts() { + void testParse_exposedPorts() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--expose=8080,3306", "my-app.war"); @@ -461,7 +486,7 @@ public void testParse_exposedPorts() { } @Test - public void testParse_volumes() { + void testParse_volumes() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--volumes=/volume1,/volume2", "my-app.war"); @@ -471,7 +496,7 @@ public void testParse_volumes() { } @Test - public void testParse_environment() { + void testParse_environment() { War warCommand = CommandLine.populateCommand( new War(), @@ -483,7 +508,7 @@ public void testParse_environment() { } @Test - public void testParse_labels() { + void testParse_labels() { War warCommand = CommandLine.populateCommand( new War(), @@ -495,7 +520,7 @@ public void testParse_labels() { } @Test - public void testParse_user() { + void testParse_user() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--user=customUser", "my-app.war"); @@ -503,7 +528,7 @@ public void testParse_user() { } @Test - public void testParse_imageFormat() { + void testParse_imageFormat() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--image-format=OCI", "my-app.war"); @@ -511,7 +536,7 @@ public void testParse_imageFormat() { } @Test - public void testParse_invalidImageFormat() { + void testParse_invalidImageFormat() { CommandLine.ParameterException exception = assertThrows( CommandLine.ParameterException.class, @@ -525,7 +550,7 @@ public void testParse_invalidImageFormat() { } @Test - public void testParse_programArguments() { + void testParse_programArguments() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--program-args=arg1,arg2", "my-app.war"); @@ -534,7 +559,7 @@ public void testParse_programArguments() { } @Test - public void testParse_entrypoint() { + void testParse_entrypoint() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--entrypoint=java -cp myClass", "my-app.war"); @@ -543,7 +568,7 @@ public void testParse_entrypoint() { } @Test - public void testParse_creationTime_milliseconds() { + void testParse_creationTime_milliseconds() { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--creation-time=23", "my-app.war"); @@ -552,7 +577,7 @@ public void testParse_creationTime_milliseconds() { } @Test - public void testParse_creationTime_iso8601() { + void testParse_creationTime_iso8601() { War warCommand = CommandLine.populateCommand( new War(), @@ -564,7 +589,7 @@ public void testParse_creationTime_iso8601() { } @Test - public void testValidate_nameMissingFail() { + void testValidate_nameMissingFail() { War warCommand = CommandLine.populateCommand(new War(), "--target=tar://sometar.tar", "my-app.war"); CommandLine.ParameterException pex = @@ -575,7 +600,7 @@ public void testValidate_nameMissingFail() { } @Test - public void testValidate_pass() { + void testValidate_pass() { War warCommand = CommandLine.populateCommand( new War(), "--target=tar://sometar.tar", "--name=test.io/test/test", "my-app.war"); @@ -584,14 +609,14 @@ public void testValidate_pass() { } @Test - public void testIsJetty_noCustomBaseImage() throws InvalidImageReferenceException { + void testIsJetty_noCustomBaseImage() throws InvalidImageReferenceException { War warCommand = CommandLine.populateCommand(new War(), "--target=test-image-ref", "my-app.war"); assertThat(warCommand.commonContainerConfigCliOptions.isJettyBaseimage()).isTrue(); } @Test - public void testIsJetty_nonJetty() throws InvalidImageReferenceException { + void testIsJetty_nonJetty() throws InvalidImageReferenceException { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--from=base-image", "my-app.war"); @@ -599,7 +624,7 @@ public void testIsJetty_nonJetty() throws InvalidImageReferenceException { } @Test - public void testIsJetty_customJetty() throws InvalidImageReferenceException { + void testIsJetty_customJetty() throws InvalidImageReferenceException { War warCommand = CommandLine.populateCommand( new War(), "--target=test-image-ref", "--from=jetty:tag", "my-app.war"); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ArchiveLayerSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ArchiveLayerSpecTest.java index 342aee8dea8..81f26de081b 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ArchiveLayerSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ArchiveLayerSpecTest.java @@ -23,15 +23,15 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ArchiveLayerSpec}. */ -public class ArchiveLayerSpecTest { +class ArchiveLayerSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testArchiveLayerSpec_full() throws JsonProcessingException { + void testArchiveLayerSpec_full() throws JsonProcessingException { String data = "name: layer name\n" + "archive: out/archive.tgz\n" + "mediaType: test.media.type"; @@ -42,7 +42,7 @@ public void testArchiveLayerSpec_full() throws JsonProcessingException { } @Test - public void testArchiveLayerSpec_nameRequired() { + void testArchiveLayerSpec_nameRequired() { String data = "archive: out/archive"; try { @@ -55,7 +55,7 @@ public void testArchiveLayerSpec_nameRequired() { } @Test - public void testArchiveLayerSpec_nameNonNull() { + void testArchiveLayerSpec_nameNonNull() { String data = "name: null\n" + "archive: out/archive"; try { @@ -68,7 +68,7 @@ public void testArchiveLayerSpec_nameNonNull() { } @Test - public void testArchiveLayerSpec_nameNonEmpty() { + void testArchiveLayerSpec_nameNonEmpty() { String data = "name: ''\n" + "archive: out/archive"; try { @@ -84,7 +84,7 @@ public void testArchiveLayerSpec_nameNonEmpty() { // With {@link LayerSpec.Deserializer#deserialize} this test seems pointless, but it still helps // define the behavior of this class. @Test - public void testArchiveLayerSpec_archiveRequired() { + void testArchiveLayerSpec_archiveRequired() { String data = "name: layer name"; try { @@ -97,7 +97,7 @@ public void testArchiveLayerSpec_archiveRequired() { } @Test - public void testArchiveLayerSpec_archiveNonNull() { + void testArchiveLayerSpec_archiveNonNull() { String data = "name: layer name\n" + "archive: null"; try { @@ -110,7 +110,7 @@ public void testArchiveLayerSpec_archiveNonNull() { } @Test - public void testArchiveLayerSpec_archiveNonEmpty() { + void testArchiveLayerSpec_archiveNonEmpty() { String data = "name: layer name\n" + "archive: ''"; try { @@ -124,7 +124,7 @@ public void testArchiveLayerSpec_archiveNonEmpty() { } @Test - public void testArchiveLayerSpec_mediaTypeNonEmpty() { + void testArchiveLayerSpec_mediaTypeNonEmpty() { String data = "name: layer name\n" + "archive: out/archive.tgz\n" + "mediaType: ' '"; try { diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BaseImageSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BaseImageSpecTest.java index 7f54f7174c5..5cef498e1cc 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BaseImageSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BaseImageSpecTest.java @@ -23,15 +23,15 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link BaseImageSpec}. */ -public class BaseImageSpecTest { +class BaseImageSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testBaseImageSpec_full() throws JsonProcessingException { + void testBaseImageSpec_full() throws JsonProcessingException { String data = "image: gcr.io/example/jib\n" + "platforms:\n" // trivial platform spec @@ -45,7 +45,7 @@ public void testBaseImageSpec_full() throws JsonProcessingException { } @Test - public void testBaseImageSpec_imageRequired() { + void testBaseImageSpec_imageRequired() { String data = "platforms:\n" // trivial platform spec + " - architecture: amd64\n" @@ -60,7 +60,7 @@ public void testBaseImageSpec_imageRequired() { } @Test - public void testBaseImageSpec_imageNotNull() { + void testBaseImageSpec_imageNotNull() { String data = "image: null\n" + "platforms:\n" // trivial platform spec @@ -76,7 +76,7 @@ public void testBaseImageSpec_imageNotNull() { } @Test - public void testBaseImageSpec_imageNotEmpty() { + void testBaseImageSpec_imageNotEmpty() { String data = "image: ''\n" + "platforms:\n" // trivial platform spec @@ -93,7 +93,7 @@ public void testBaseImageSpec_imageNotEmpty() { } @Test - public void testBaseImageSpec_nullCollections() throws JsonProcessingException { + void testBaseImageSpec_nullCollections() throws JsonProcessingException { String data = "image: gcr.io/example/jib\n"; BaseImageSpec baseImageSpec = mapper.readValue(data, BaseImageSpec.class); @@ -101,7 +101,7 @@ public void testBaseImageSpec_nullCollections() throws JsonProcessingException { } @Test - public void testBaseImageSpec_platformsNoNullEntries() { + void testBaseImageSpec_platformsNoNullEntries() { String data = "image: gcr.io/example/jib\n" + "platforms: [null]\n"; try { diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFileSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFileSpecTest.java index cf3f0192829..fef9968d15c 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFileSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFileSpecTest.java @@ -29,19 +29,26 @@ import com.google.common.collect.ImmutableList; import java.nio.file.Paths; import java.time.Instant; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BuildFileSpec}. */ -@RunWith(JUnitParamsRunner.class) -public class BuildFileSpecTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildFileSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testBuildFileSpec_full() throws JsonProcessingException { + void testBuildFileSpec_full() throws JsonProcessingException { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" @@ -90,7 +97,7 @@ public void testBuildFileSpec_full() throws JsonProcessingException { } @Test - public void testBuildFileSpec_apiVersionRequired() { + void testBuildFileSpec_apiVersionRequired() { String data = "kind: BuildFile\n"; Exception exception = @@ -102,7 +109,7 @@ public void testBuildFileSpec_apiVersionRequired() { } @Test - public void testBuildFileSpec_apiVersionNotNull() { + void testBuildFileSpec_apiVersionNotNull() { String data = "apiVersion: null\n" + "kind: BuildFile\n"; Exception exception = @@ -112,7 +119,7 @@ public void testBuildFileSpec_apiVersionNotNull() { } @Test - public void testBuildFileSpec_apiVersionNotEmpty() { + void testBuildFileSpec_apiVersionNotEmpty() { String data = "apiVersion: ''\n" + "kind: BuildFile\n"; Exception exception = @@ -124,7 +131,7 @@ public void testBuildFileSpec_apiVersionNotEmpty() { } @Test - public void testBuildFileSpec_kindRequired() { + void testBuildFileSpec_kindRequired() { String data = "apiVersion: v1alpha1\n"; Exception exception = @@ -134,7 +141,7 @@ public void testBuildFileSpec_kindRequired() { } @Test - public void testBuildFileSpec_kindMustBeBuildFile() { + void testBuildFileSpec_kindMustBeBuildFile() { String data = "apiVersion: v1alpha1\n" + "kind: NotBuildFile\n"; Exception exception = @@ -146,7 +153,7 @@ public void testBuildFileSpec_kindMustBeBuildFile() { } @Test - public void testBuildFileSpec_kindNotNull() { + void testBuildFileSpec_kindNotNull() { String data = "apiVersion: v1alpha1\n" + "kind: null\n"; Exception exception = @@ -156,7 +163,7 @@ public void testBuildFileSpec_kindNotNull() { } @Test - public void testBuildFileSpec_nullCollections() throws JsonProcessingException { + void testBuildFileSpec_nullCollections() throws JsonProcessingException { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n"; BuildFileSpec parsed = mapper.readValue(data, BuildFileSpec.class); @@ -169,9 +176,9 @@ public void testBuildFileSpec_nullCollections() throws JsonProcessingException { assertThat(parsed.getCmd()).isEmpty(); } - @Test - @Parameters(value = {"volumes", "exposedPorts", "entrypoint", "cmd"}) - public void testBuildFileSpec_noNullEntries(String fieldName) { + @ParameterizedTest + @CsvSource(value = {"volumes", "exposedPorts", "entrypoint", "cmd"}) + void testBuildFileSpec_noNullEntries(String fieldName) { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ": ['first', null]"; Exception exception = @@ -182,9 +189,9 @@ public void testBuildFileSpec_noNullEntries(String fieldName) { .contains("Property '" + fieldName + "' cannot contain null entries"); } - @Test - @Parameters(value = {"volumes", "exposedPorts", "entrypoint", "cmd"}) - public void testBuildFileSpec_noEmptyEntries(String fieldName) { + @ParameterizedTest + @CsvSource(value = {"volumes", "exposedPorts", "entrypoint", "cmd"}) + void testBuildFileSpec_noEmptyEntries(String fieldName) { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ": ['first', ' ']"; Exception exception = @@ -195,16 +202,16 @@ public void testBuildFileSpec_noEmptyEntries(String fieldName) { .contains("Property '" + fieldName + "' cannot contain empty strings"); } - @Test - @Parameters(value = {"volumes", "exposedPorts", "entrypoint", "cmd"}) - public void testBuildFileSpec_emptyListOkay(String fieldName) throws JsonProcessingException { + @ParameterizedTest + @CsvSource(value = {"volumes", "exposedPorts", "entrypoint", "cmd"}) + void testBuildFileSpec_emptyListOkay(String fieldName) throws JsonProcessingException { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ": []"; assertThat(mapper.readValue(data, BuildFileSpec.class)).isNotNull(); } - @Test - @Parameters( + @ParameterizedTest + @CsvSource( value = { "volumes", "exposedPorts", @@ -217,15 +224,15 @@ public void testBuildFileSpec_emptyListOkay(String fieldName) throws JsonProcess "environment", "labels" }) - public void testBuildFileSpec_nullOkay(String fieldName) throws JsonProcessingException { + void testBuildFileSpec_nullOkay(String fieldName) throws JsonProcessingException { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ": null"; assertThat(mapper.readValue(data, BuildFileSpec.class)).isNotNull(); } - @Test - @Parameters(value = {"creationTime", "format", "user", "workingDirectory"}) - public void testBuildFileSpec_noEmptyValues(String fieldName) { + @ParameterizedTest + @CsvSource(value = {"creationTime", "format", "user", "workingDirectory"}) + void testBuildFileSpec_noEmptyValues(String fieldName) { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ": ' '"; Exception exception = assertThrows( @@ -236,21 +243,22 @@ public void testBuildFileSpec_noEmptyValues(String fieldName) { } @SuppressWarnings("unused") - private static String[][] invalidMapEntries() { - return new String[][] { - {"environment", " key: null", "' cannot contain null values"}, - {"environment", " key: ' '", "' cannot contain empty string values"}, - {"environment", " ' ': value", "' cannot contain empty string keys"}, - {"labels", " key: null", "' cannot contain null values"}, - {"labels", " key: ' '", "' cannot contain empty string values"}, - {"labels", " ' ': value", "' cannot contain empty string keys"}, - }; + private static Stream invalidMapEntries() { + return Stream.of( + Arguments.of(new Object[] {"environment", " key: null", "' cannot contain null values"}), + Arguments.of( + new Object[] {"environment", " key: ' '", "' cannot contain empty string values"}), + Arguments.of( + new Object[] {"environment", " ' ': value", "' cannot contain empty string keys"}), + Arguments.of(new Object[] {"labels", " key: null", "' cannot contain null values"}), + Arguments.of(new Object[] {"labels", " key: ' '", "' cannot contain empty string values"}), + Arguments.of( + new Object[] {"labels", " ' ': value", "' cannot contain empty string keys"})); } - @Test - @Parameters(method = "invalidMapEntries") - public void testBuildFileSpec_invalidMapEntries( - String fieldName, String input, String errorMessage) { + @ParameterizedTest + @MethodSource("invalidMapEntries") + void testBuildFileSpec_invalidMapEntries(String fieldName, String input, String errorMessage) { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ":\n" + input; Exception exception = @@ -261,18 +269,18 @@ public void testBuildFileSpec_invalidMapEntries( // A quirk of our parser is that "null" keys are parsed as strings and not null, this test just // formalizes that behavior. - @Test - @Parameters(value = {"environment", "labels"}) - public void testBuildFileSpec_yamlNullKeysPass(String fieldName) throws JsonProcessingException { + @ParameterizedTest + @CsvSource(value = {"environment", "labels"}) + void testBuildFileSpec_yamlNullKeysPass(String fieldName) throws JsonProcessingException { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ":\n" + " null: value"; assertThat(mapper.readValue(data, BuildFileSpec.class)).isNotNull(); } - @Test - @Parameters(value = {"environment", "labels"}) - public void testBuildFileSpec_emptyMapOkay(String fieldName) throws JsonProcessingException { + @ParameterizedTest + @CsvSource({"environment", "labels"}) + void testBuildFileSpec_emptyMapOkay(String fieldName) throws JsonProcessingException { String data = "apiVersion: v1alpha1\n" + "kind: BuildFile\n" + fieldName + ": {}"; assertThat(mapper.readValue(data, BuildFileSpec.class)).isNotNull(); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFilesTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFilesTest.java index 3ecc77d1ec0..dac29715150 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFilesTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/BuildFilesTest.java @@ -41,31 +41,35 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -public class BuildFilesTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildFilesTest { - @Rule public final TemporaryFolder tmp = new TemporaryFolder(); @Rule public final MockitoRule rule = MockitoJUnit.rule(); @Mock private ConsoleLogger consoleLogger; @Mock private Build buildCli; @Mock private CommonCliOptions commonCliOptions; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(buildCli.getTemplateParameters()).thenReturn(ImmutableMap.of()); } @Test - public void testToJibContainerBuilder_allProperties() + void testToJibContainerBuilder_allProperties() throws URISyntaxException, IOException, InvalidImageReferenceException { Path buildfile = Paths.get(Resources.getResource("buildfiles/projects/allProperties/jib.yaml").toURI()); @@ -107,7 +111,7 @@ public void testToJibContainerBuilder_allProperties() } @Test - public void testToJibContainerBuilder_requiredProperties() + void testToJibContainerBuilder_requiredProperties() throws URISyntaxException, IOException, InvalidImageReferenceException { Path buildfile = Paths.get(Resources.getResource("buildfiles/projects/allDefaults/jib.yaml").toURI()); @@ -131,7 +135,7 @@ public void testToJibContainerBuilder_requiredProperties() } @Test - public void testToBuildFileSpec_withTemplating() + void testToBuildFileSpec_withTemplating() throws URISyntaxException, InvalidImageReferenceException, IOException { Path buildfile = Paths.get(Resources.getResource("buildfiles/projects/templating/valid.yaml").toURI()); @@ -161,7 +165,7 @@ public void testToBuildFileSpec_withTemplating() } @Test - public void testToBuildFileSpec_failWithMissingTemplateVariable() + void testToBuildFileSpec_failWithMissingTemplateVariable() throws URISyntaxException, InvalidImageReferenceException, IOException { Path buildfile = Paths.get(Resources.getResource("buildfiles/projects/templating/missingVar.yaml").toURI()); @@ -177,7 +181,7 @@ public void testToBuildFileSpec_failWithMissingTemplateVariable() } @Test - public void testToBuildFileSpec_templateMultiLineBehavior() + void testToBuildFileSpec_templateMultiLineBehavior() throws URISyntaxException, InvalidImageReferenceException, IOException { Path buildfile = Paths.get(Resources.getResource("buildfiles/projects/templating/multiLine.yaml").toURI()); @@ -192,7 +196,7 @@ public void testToBuildFileSpec_templateMultiLineBehavior() } @Test - public void testToBuildFileSpec_alternativeRootContext() + void testToBuildFileSpec_alternativeRootContext() throws URISyntaxException, InvalidImageReferenceException, IOException { Path buildfile = Paths.get( diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/CopySpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/CopySpecTest.java index 4806b414af9..1b1b6766572 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/CopySpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/CopySpecTest.java @@ -26,19 +26,26 @@ import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath; import java.nio.file.Paths; import java.time.Instant; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link CopySpec}. */ -@RunWith(JUnitParamsRunner.class) -public class CopySpecTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CopySpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testCopySpec_full() throws JsonProcessingException { + void testCopySpec_full() throws JsonProcessingException { String data = "src: target/classes\n" + "dest: /app/classes\n" @@ -58,20 +65,24 @@ public void testCopySpec_full() throws JsonProcessingException { .isEqualTo(Instant.ofEpochMilli(1)); } - @Test - @Parameters( - value = { - "dest: /app/classes\n, Missing required creator property 'src'", - "src: target/classes\n, Missing required creator property 'dest'" - }) - public void testCopySpec_required(String data, String errorMessage) { + public static Stream requiredChecksParams() { + return Stream.of( + Arguments.of( + new Object[] {"dest: /app/classes\n", "Missing required creator property 'src'"}), + Arguments.of( + new Object[] {"src: target/classes\n", "Missing required creator property 'dest'"})); + } + + @ParameterizedTest + @MethodSource("requiredChecksParams") + void testCopySpec_required(String data, String errorMessage) { Exception exception = assertThrows(JsonProcessingException.class, () -> mapper.readValue(data, CopySpec.class)); assertThat(exception).hasMessageThat().startsWith(errorMessage); } @Test - public void testCopySpec_destEndsWithSlash() throws JsonProcessingException { + void testCopySpec_destEndsWithSlash() throws JsonProcessingException { String data = "src: target/classes\n" + "dest: /app/classes/"; CopySpec parsed = mapper.readValue(data, CopySpec.class); @@ -80,7 +91,7 @@ public void testCopySpec_destEndsWithSlash() throws JsonProcessingException { } @Test - public void testCopySpec_destDoesNotEndWithSlash() throws JsonProcessingException { + void testCopySpec_destDoesNotEndWithSlash() throws JsonProcessingException { String data = "src: target/classes\n" + "dest: /app/classes"; CopySpec parsed = mapper.readValue(data, CopySpec.class); @@ -88,22 +99,32 @@ public void testCopySpec_destDoesNotEndWithSlash() throws JsonProcessingExceptio assertThat(parsed.isDestEndsWithSlash()).isFalse(); } - @Test - @Parameters( - value = { - "src: null\ndest: /app/classes\n, Property 'src' cannot be null", - "src: ''\ndest: /app/classes\n, Property 'src' cannot be an empty string", - "src: target/classes\ndest: null\n, Property 'dest' cannot be null", - "src: target/classes\ndest: ''\n, Property 'dest' cannot be an empty string" - }) - public void testCopySpec_nullEmptyCheck(String data, String errorMessage) { + public static Stream nullChecksParams() { + return Stream.of( + Arguments.of( + new Object[] {"src: null\ndest: /app/classes\n", "Property 'src' cannot be null"}), + Arguments.of( + new Object[] { + "src: ''\ndest: /app/classes\n", "Property 'src' cannot be an empty string" + }), + Arguments.of( + new Object[] {"src: target/classes\ndest: null\n", "Property 'dest' cannot be null"}), + Arguments.of( + new Object[] { + "src: target/classes\ndest: ''\n", "Property 'dest' cannot be an empty string" + })); + } + + @ParameterizedTest + @MethodSource("nullChecksParams") + void testCopySpec_nullEmptyCheck(String data, String errorMessage) { Exception exception = assertThrows(JsonProcessingException.class, () -> mapper.readValue(data, CopySpec.class)); assertThat(exception).hasMessageThat().contains(errorMessage); } @Test - public void testCopySpec_nullCollections() throws JsonProcessingException { + void testCopySpec_nullCollections() throws JsonProcessingException { String data = "src: target/classes\n" + "dest: /app/classes\n"; CopySpec parsed = mapper.readValue(data, CopySpec.class); @@ -111,9 +132,9 @@ public void testCopySpec_nullCollections() throws JsonProcessingException { assertThat(parsed.getExcludes()).isEmpty(); } - @Test - @Parameters(value = {"includes", "excludes"}) - public void testCopySpec_noNullEntries(String fieldName) { + @ParameterizedTest + @CsvSource(value = {"includes", "excludes"}) + void testCopySpec_noNullEntries(String fieldName) { String data = "src: target/classes\n" + "dest: /app/classes\n" + fieldName + ": ['first', null]"; @@ -125,9 +146,9 @@ public void testCopySpec_noNullEntries(String fieldName) { .isEqualTo("Property '" + fieldName + "' cannot contain null entries"); } - @Test - @Parameters(value = {"includes", "excludes"}) - public void testCopySpec_noEmptyEntries(String fieldName) { + @ParameterizedTest + @CsvSource(value = {"includes", "excludes"}) + void testCopySpec_noEmptyEntries(String fieldName) { String data = "src: target/classes\n" + "dest: /app/classes\n" + fieldName + ": ['first', ' ']"; Exception exception = @@ -138,17 +159,17 @@ public void testCopySpec_noEmptyEntries(String fieldName) { .isEqualTo("Property '" + fieldName + "' cannot contain empty strings"); } - @Test - @Parameters(value = {"includes", "excludes"}) - public void testCopySpec_emptyOkay(String fieldName) throws JsonProcessingException { + @ParameterizedTest + @CsvSource(value = {"includes", "excludes"}) + void testCopySpec_emptyOkay(String fieldName) throws JsonProcessingException { String data = "src: target/classes\n" + "dest: /app/classes\n" + fieldName + ": []"; assertThat(mapper.readValue(data, CopySpec.class)).isNotNull(); } - @Test - @Parameters(value = {"includes", "excludes"}) - public void testCopySpec_nullOkay(String fieldName) throws JsonProcessingException { + @ParameterizedTest + @CsvSource(value = {"includes", "excludes"}) + void testCopySpec_nullOkay(String fieldName) throws JsonProcessingException { String data = "src: target/classes\n" + "dest: /app/classes\n" + fieldName + ": null"; assertThat(mapper.readValue(data, CopySpec.class)).isNotNull(); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FileLayerSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FileLayerSpecTest.java index b42551aae41..0c2dc024e7f 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FileLayerSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FileLayerSpecTest.java @@ -25,15 +25,15 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link FileLayerSpec}. */ -public class FileLayerSpecTest { +class FileLayerSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testFileLayerSpec_full() throws JsonProcessingException { + void testFileLayerSpec_full() throws JsonProcessingException { String data = "name: layer name\n" + "files:\n" // trivial copy spec @@ -50,7 +50,7 @@ public void testFileLayerSpec_full() throws JsonProcessingException { } @Test - public void testFileLayerSpec_nameRequired() { + void testFileLayerSpec_nameRequired() { String data = "files:\n" + " - src: source\n" + " dest: /dest\n"; try { @@ -63,7 +63,7 @@ public void testFileLayerSpec_nameRequired() { } @Test - public void testFileLayerSpec_nameNotNull() { + void testFileLayerSpec_nameNotNull() { String data = "name: null\n" + "files:\n" + " - src: source\n" + " dest: /dest\n"; try { @@ -76,7 +76,7 @@ public void testFileLayerSpec_nameNotNull() { } @Test - public void testFileLayerSpec_nameNotEmpty() { + void testFileLayerSpec_nameNotEmpty() { String data = "name: ''\n" + "files:\n" + " - src: source\n" + " dest: /dest\n"; try { @@ -90,7 +90,7 @@ public void testFileLayerSpec_nameNotEmpty() { } @Test - public void testFileLayerSpec_filesRequired() { + void testFileLayerSpec_filesRequired() { String data = "name: layer name"; try { @@ -103,7 +103,7 @@ public void testFileLayerSpec_filesRequired() { } @Test - public void testFileLayerSpec_filesNotNull() { + void testFileLayerSpec_filesNotNull() { String data = "name: layer name\n" + "files: null"; try { @@ -116,7 +116,7 @@ public void testFileLayerSpec_filesNotNull() { } @Test - public void testFileLayerSpec_filesNotEmpty() { + void testFileLayerSpec_filesNotEmpty() { String data = "name: layer name\n" + "files: []\n"; try { diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesSpecTest.java index 69ec6680885..58615b6364e 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesSpecTest.java @@ -26,19 +26,23 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.google.cloud.tools.jib.api.buildplan.FilePermissions; import java.time.Instant; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link FilePropertiesSpec}. */ -@RunWith(JUnitParamsRunner.class) -public class FilePropertiesSpecTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class FilePropertiesSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testFilePropertiesSpec_full() throws JsonProcessingException { + void testFilePropertiesSpec_full() throws JsonProcessingException { String data = "filePermissions: 644\n" + "directoryPermissions: 755\n" @@ -55,22 +59,9 @@ public void testFilePropertiesSpec_full() throws JsonProcessingException { assertThat(parsed.getTimestamp().get()).isEqualTo(Instant.ofEpochMilli(1)); } - @Test - public void testFilePropertiesSpec_badFilePermissions() { - String data = "filePermissions: 888"; - - Exception exception = - assertThrows( - JsonMappingException.class, () -> mapper.readValue(data, FilePropertiesSpec.class)); - assertThat(exception) - .hasCauseThat() - .hasMessageThat() - .isEqualTo("octalPermissions must be a 3-digit octal number (000-777)"); - } - - @Test - public void testFilePropertiesSpec_badDirectoryPermissions() { - String data = "directoryPermissions: 888"; + @ParameterizedTest + @CsvSource(value = {"filePermissions: 888", "directoryPermissions: 888"}) + void testFilePropertiesSpec_badFileOrDirectoryPermissions(String data) { Exception exception = assertThrows( @@ -82,7 +73,7 @@ public void testFilePropertiesSpec_badDirectoryPermissions() { } @Test - public void testFilePropertiesSpec_timestampSpecIso8601() throws JsonProcessingException { + void testFilePropertiesSpec_timestampSpecIso8601() throws JsonProcessingException { String data = "timestamp: 2020-06-08T14:54:36+00:00"; FilePropertiesSpec parsed = mapper.readValue(data, FilePropertiesSpec.class); @@ -90,7 +81,7 @@ public void testFilePropertiesSpec_timestampSpecIso8601() throws JsonProcessingE } @Test - public void testFilePropertiesSpec_badTimestamp() { + void testFilePropertiesSpec_badTimestamp() { String data = "timestamp: hi"; Exception exception = @@ -104,7 +95,7 @@ public void testFilePropertiesSpec_badTimestamp() { } @Test - public void testFilePropertiesSpec_failOnUnknown() { + void testFilePropertiesSpec_failOnUnknown() { String data = "badkey: badvalue"; Exception exception = @@ -114,9 +105,9 @@ public void testFilePropertiesSpec_failOnUnknown() { assertThat(exception).hasMessageThat().contains("Unrecognized field \"badkey\""); } - @Test - @Parameters(value = {"filePermissions", "directoryPermissions", "user", "group", "timestamp"}) - public void testFilePropertiesSpec_noEmptyValues(String fieldName) { + @ParameterizedTest + @CsvSource(value = {"filePermissions", "directoryPermissions", "user", "group", "timestamp"}) + void testFilePropertiesSpec_noEmptyValues(String fieldName) { String data = fieldName + ": ' '"; Exception exception = @@ -128,9 +119,9 @@ public void testFilePropertiesSpec_noEmptyValues(String fieldName) { .isEqualTo("Property '" + fieldName + "' cannot be an empty string"); } - @Test - @Parameters(value = {"filePermissions", "directoryPermissions", "user", "group", "timestamp"}) - public void testFilePropertiesSpec_nullOkay(String fieldName) throws JsonProcessingException { + @ParameterizedTest + @CsvSource(value = {"filePermissions", "directoryPermissions", "user", "group", "timestamp"}) + void testFilePropertiesSpec_nullOkay(String fieldName) throws JsonProcessingException { String data = fieldName + ": null"; FilePropertiesSpec parsed = mapper.readValue(data, FilePropertiesSpec.class); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesStackTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesStackTest.java index cfdaa98131c..20e9316b37e 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesStackTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/FilePropertiesStackTest.java @@ -19,12 +19,12 @@ import com.google.cloud.tools.jib.api.buildplan.FilePermissions; import java.time.Instant; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class FilePropertiesStackTest { +class FilePropertiesStackTest { @Test - public void testDefaults() { + void testDefaults() { FilePropertiesStack testStack = new FilePropertiesStack(); Assert.assertEquals(FilePermissions.fromOctalString("644"), testStack.getFilePermissions()); @@ -35,7 +35,7 @@ public void testDefaults() { } @Test - public void testPush_simple() { + void testPush_simple() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); @@ -48,7 +48,7 @@ public void testPush_simple() { } @Test - public void testPush_stacking() { + void testPush_stacking() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); @@ -63,7 +63,7 @@ public void testPush_stacking() { } @Test - public void testPush_tooMany() { + void testPush_tooMany() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); @@ -79,7 +79,7 @@ public void testPush_tooMany() { } @Test - public void testPop_toZero() { + void testPop_toZero() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); @@ -93,7 +93,7 @@ public void testPop_toZero() { } @Test - public void testPop_toOlderState() { + void testPop_toOlderState() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec("111", "111", "1", "1", "1")); @@ -109,7 +109,7 @@ public void testPop_toOlderState() { } @Test - public void testPop_nothingToPop() { + void testPop_nothingToPop() { FilePropertiesStack testStack = new FilePropertiesStack(); try { @@ -121,7 +121,7 @@ public void testPop_nothingToPop() { } @Test - public void testGetOwnership_onlyUser() { + void testGetOwnership_onlyUser() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec(null, null, "u", null, null)); @@ -129,7 +129,7 @@ public void testGetOwnership_onlyUser() { } @Test - public void testGetOwnership_onlyGroup() { + void testGetOwnership_onlyGroup() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec(null, null, null, "g", null)); @@ -137,7 +137,7 @@ public void testGetOwnership_onlyGroup() { } @Test - public void testGetOwnership_userAndGroup() { + void testGetOwnership_userAndGroup() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec(null, null, "u", "g", null)); @@ -145,7 +145,7 @@ public void testGetOwnership_userAndGroup() { } @Test - public void testGetOwnership_noUserNoGroup() { + void testGetOwnership_noUserNoGroup() { FilePropertiesStack testStack = new FilePropertiesStack(); testStack.push(new FilePropertiesSpec(null, null, null, null, null)); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayerSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayerSpecTest.java index 9cf5001ce75..6cce3c7a21b 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayerSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayerSpecTest.java @@ -22,15 +22,15 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link LayerSpec}. */ -public class LayerSpecTest { +class LayerSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void deserialize_toFileLayer() throws JsonProcessingException { + void deserialize_toFileLayer() throws JsonProcessingException { String data = "name: layer name\n" + "files:\n" // trivial copy spec @@ -42,7 +42,7 @@ public void deserialize_toFileLayer() throws JsonProcessingException { } @Test - public void deserialize_toArchiveLayer() throws JsonProcessingException { + void deserialize_toArchiveLayer() throws JsonProcessingException { String data = "name: layer name\n" + "archive: out/archive.tgz\n"; LayerSpec layerSpec = mapper.readValue(data, LayerSpec.class); @@ -50,7 +50,7 @@ public void deserialize_toArchiveLayer() throws JsonProcessingException { } @Test - public void deserialize_error() { + void deserialize_error() { String data = "name: layer name\n"; try { @@ -64,7 +64,7 @@ public void deserialize_error() { } @Test - public void deserialize_nameMissing() { + void deserialize_nameMissing() { String data = "archive: out/archive.tgz\n"; try { diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersSpecTest.java index 007dfe8644d..3b25bb2482e 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersSpecTest.java @@ -24,15 +24,15 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link LayersSpec}. */ -public class LayersSpecTest { +class LayersSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testLayersSpec_full() throws JsonProcessingException { + void testLayersSpec_full() throws JsonProcessingException { String data = "entries:\n" // trivial layer + " - name: some layer\n" @@ -48,7 +48,7 @@ public void testLayersSpec_full() throws JsonProcessingException { } @Test - public void testLayersSpec_entriesRequired() { + void testLayersSpec_entriesRequired() { String data = "properties:\n" // trivial file properties spec + " timestamp: 1\n"; @@ -63,7 +63,7 @@ public void testLayersSpec_entriesRequired() { } @Test - public void testLayersSpec_entriesNotNull() { + void testLayersSpec_entriesNotNull() { String data = "entries: null\n" + "properties:\n" // trivial file properties spec @@ -79,7 +79,7 @@ public void testLayersSpec_entriesNotNull() { } @Test - public void testLayersSpec_entriesNotEmpty() { + void testLayersSpec_entriesNotEmpty() { String data = "entries: []\n" + "properties:\n" // trivial file properties spec diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersTest.java index 51be08a3100..b797c9bbd21 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/LayersTest.java @@ -34,10 +34,10 @@ import java.util.List; import java.util.Set; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Layers}. */ -public class LayersTest { +class LayersTest { private static final String LAYERS_TEST_RESOURCE_DIR = "buildfiles/layers/"; @@ -60,7 +60,7 @@ private static Path getLayersTestRoot(String testName) throws URISyntaxException } @Test - public void testToLayers_properties() throws IOException, URISyntaxException { + void testToLayers_properties() throws IOException, URISyntaxException { Path testRoot = getLayersTestRoot("propertiesTest"); List layers = parseLayers(testRoot, 4); @@ -94,7 +94,7 @@ public void testToLayers_properties() throws IOException, URISyntaxException { } @Test - public void testToLayers_includeExcludes() throws IOException, URISyntaxException { + void testToLayers_includeExcludes() throws IOException, URISyntaxException { Path testRoot = getLayersTestRoot("includesExcludesTest"); List layers = parseLayers(testRoot, 6); @@ -199,7 +199,7 @@ public void testToLayers_includeExcludes() throws IOException, URISyntaxExceptio } @Test - public void testToLayers_file() throws IOException, URISyntaxException { + void testToLayers_file() throws IOException, URISyntaxException { Path testRoot = getLayersTestRoot("fileTest/default"); List layers = parseLayers(testRoot, 1); @@ -212,7 +212,7 @@ public void testToLayers_file() throws IOException, URISyntaxException { } @Test - public void testToLayers_fileWithIncludes() throws IOException, URISyntaxException { + void testToLayers_fileWithIncludes() throws IOException, URISyntaxException { Path testRoot = getLayersTestRoot("fileTest/failWithIncludes"); try { parseLayers(testRoot, 0); @@ -224,7 +224,7 @@ public void testToLayers_fileWithIncludes() throws IOException, URISyntaxExcepti } @Test - public void testToLayers_fileWithExcludes() throws IOException, URISyntaxException { + void testToLayers_fileWithExcludes() throws IOException, URISyntaxException { Path testRoot = getLayersTestRoot("fileTest/failWithExcludes"); try { parseLayers(testRoot, 0); @@ -282,7 +282,7 @@ private static void checkLayer( } @Test - public void testToLayers_pathDoesNotExist() throws IOException, URISyntaxException { + void testToLayers_pathDoesNotExist() throws IOException, URISyntaxException { Path testRoot = getLayersTestRoot("pathDoesNotExist"); try { parseLayers(testRoot, 0); @@ -296,7 +296,7 @@ public void testToLayers_pathDoesNotExist() throws IOException, URISyntaxExcepti } @Test - public void testToLayers_archiveLayersNotSupported() throws URISyntaxException, IOException { + void testToLayers_archiveLayersNotSupported() throws URISyntaxException, IOException { Path testRoot = getLayersTestRoot("archiveLayerTest"); try { parseLayers(testRoot, 0); @@ -307,7 +307,7 @@ public void testToLayers_archiveLayersNotSupported() throws URISyntaxException, } @Test - public void testToLayers_writeToRoot() throws IOException, URISyntaxException { + void testToLayers_writeToRoot() throws IOException, URISyntaxException { // this test defines the current behavior of writing to root, perhaps we should ignore // root at this level or we should ignore it at the builder level Path testRoot = getLayersTestRoot("writeToRoot"); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/PlatformSpecTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/PlatformSpecTest.java index 5e268ec903d..7c16457d3ef 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/PlatformSpecTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/PlatformSpecTest.java @@ -22,15 +22,15 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link PlatformSpec}. */ -public class PlatformSpecTest { +class PlatformSpecTest { private static final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @Test - public void testPlatformSpec_full() throws JsonProcessingException { + void testPlatformSpec_full() throws JsonProcessingException { String data = "architecture: amd64\n" + "os: linux\n"; PlatformSpec parsed = mapper.readValue(data, PlatformSpec.class); @@ -39,7 +39,7 @@ public void testPlatformSpec_full() throws JsonProcessingException { } @Test - public void testPlatformSpec_osRequired() { + void testPlatformSpec_osRequired() { String data = "architecture: amd64\n"; try { @@ -52,7 +52,7 @@ public void testPlatformSpec_osRequired() { } @Test - public void testPlatformSpec_osNotNull() { + void testPlatformSpec_osNotNull() { String data = "architecture: amd64\n" + "os: null"; try { @@ -65,7 +65,7 @@ public void testPlatformSpec_osNotNull() { } @Test - public void testPlatformSpec_osNotEmpty() { + void testPlatformSpec_osNotEmpty() { String data = "architecture: amd64\n" + "os: ''"; try { @@ -78,7 +78,7 @@ public void testPlatformSpec_osNotEmpty() { } @Test - public void testPlatformSpec_architectureRequired() { + void testPlatformSpec_architectureRequired() { String data = "os: linux\n"; try { @@ -92,7 +92,7 @@ public void testPlatformSpec_architectureRequired() { } @Test - public void testPlatformSpec_architectureNotNull() { + void testPlatformSpec_architectureNotNull() { String data = "architecture: null\n" + "os: linux"; try { @@ -105,7 +105,7 @@ public void testPlatformSpec_architectureNotNull() { } @Test - public void testPlatformSpec_architectureNotEmpty() { + void testPlatformSpec_architectureNotEmpty() { String data = "architecture: ''\n" + "os: linux"; try { diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ValidatorTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ValidatorTest.java index 8924dadcb64..4444f066fe7 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ValidatorTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/buildfile/ValidatorTest.java @@ -24,19 +24,19 @@ import java.util.List; import java.util.Map; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Validator}. */ -public class ValidatorTest { +class ValidatorTest { @Test - public void testCheckNotNullAndNotEmpty_stringPass() { + void testCheckNotNullAndNotEmpty_stringPass() { Validator.checkNotNullAndNotEmpty("value", "ignored"); // pass } @Test - public void testCheckNotNullAndNotEmpty_stringFailNull() { + void testCheckNotNullAndNotEmpty_stringFailNull() { try { Validator.checkNotNullAndNotEmpty((String) null, "test"); Assert.fail(); @@ -46,7 +46,7 @@ public void testCheckNotNullAndNotEmpty_stringFailNull() { } @Test - public void testCheckNotNullAndNotEmpty_stringFailEmpty() { + void testCheckNotNullAndNotEmpty_stringFailEmpty() { try { Validator.checkNotNullAndNotEmpty(" ", "test"); Assert.fail(); @@ -56,17 +56,17 @@ public void testCheckNotNullAndNotEmpty_stringFailEmpty() { } @Test - public void testCheckNullOrNotEmpty_valuePass() { + void testCheckNullOrNotEmpty_valuePass() { Validator.checkNullOrNotEmpty("value", "test"); } @Test - public void testCheckNullOrNotEmpty_nullPass() { + void testCheckNullOrNotEmpty_nullPass() { Validator.checkNullOrNotEmpty(null, "test"); } @Test - public void testCheckNullOrNotEmpty_fail() { + void testCheckNullOrNotEmpty_fail() { try { Validator.checkNullOrNotEmpty(" ", "test"); Assert.fail(); @@ -76,13 +76,13 @@ public void testCheckNullOrNotEmpty_fail() { } @Test - public void testCheckNotEmpty_collectionPass() { + void testCheckNotEmpty_collectionPass() { Validator.checkNotNullAndNotEmpty(ImmutableList.of("value"), "ignored"); // pass } @Test - public void testCheckNotEmpty_collectionFailNull() { + void testCheckNotEmpty_collectionFailNull() { try { Validator.checkNotNullAndNotEmpty((Collection) null, "test"); Assert.fail(); @@ -92,7 +92,7 @@ public void testCheckNotEmpty_collectionFailNull() { } @Test - public void testCheckNotEmpty_collectionFailEmpty() { + void testCheckNotEmpty_collectionFailEmpty() { try { Validator.checkNotNullAndNotEmpty(ImmutableList.of(), "test"); Assert.fail(); @@ -102,26 +102,26 @@ public void testCheckNotEmpty_collectionFailEmpty() { } @Test - public void testCheckNullOrNonNullNonEmptyEntries_nullMapPass() { + void testCheckNullOrNonNullNonEmptyEntries_nullMapPass() { Validator.checkNullOrNonNullNonEmptyEntries((Map) null, "test"); // pass } @Test - public void testCheckNullOrNonNullNonEmptyEntries_emptyMapPass() { + void testCheckNullOrNonNullNonEmptyEntries_emptyMapPass() { Validator.checkNullOrNonNullNonEmptyEntries(ImmutableMap.of(), "test"); // pass } @Test - public void testCheckNullOrNonNullNonEmptyEntries_mapWithValuesPass() { + void testCheckNullOrNonNullNonEmptyEntries_mapWithValuesPass() { Validator.checkNullOrNonNullNonEmptyEntries( ImmutableMap.of("key1", "val1", "key2", "val2"), "test"); // pass } @Test - public void testCheckNullOrNonNullNonEmptyEntries_mapNullKeyFail() { + void testCheckNullOrNonNullNonEmptyEntries_mapNullKeyFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap(null, "val1"), "test"); Assert.fail(); @@ -131,7 +131,7 @@ public void testCheckNullOrNonNullNonEmptyEntries_mapNullKeyFail() { } @Test - public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyKeyFail() { + void testCheckNullOrNonNullNonEmptyEntries_mapEmptyKeyFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap(" ", "val1"), "test"); Assert.fail(); @@ -141,7 +141,7 @@ public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyKeyFail() { } @Test - public void testCheckNullOrNonNullNonEmptyEntries_mapNullValueFail() { + void testCheckNullOrNonNullNonEmptyEntries_mapNullValueFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap("key1", null), "test"); Assert.fail(); @@ -151,7 +151,7 @@ public void testCheckNullOrNonNullNonEmptyEntries_mapNullValueFail() { } @Test - public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyValueFail() { + void testCheckNullOrNonNullNonEmptyEntries_mapEmptyValueFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(Collections.singletonMap("key1", " "), "test"); Assert.fail(); @@ -161,25 +161,25 @@ public void testCheckNullOrNonNullNonEmptyEntries_mapEmptyValueFail() { } @Test - public void testCheckNullOrNonNullNonEmptyEntries_nullPass() { + void testCheckNullOrNonNullNonEmptyEntries_nullPass() { Validator.checkNullOrNonNullNonEmptyEntries((List) null, "test"); // pass } @Test - public void testCheckNullOrNonNullNonEmptyEntries_emptyPass() { + void testCheckNullOrNonNullNonEmptyEntries_emptyPass() { Validator.checkNullOrNonNullNonEmptyEntries(ImmutableList.of(), "test"); // pass } @Test - public void testCheckNullNonNullNonEmptyEntries_valuesPass() { + void testCheckNullNonNullNonEmptyEntries_valuesPass() { Validator.checkNullOrNonNullNonEmptyEntries(ImmutableList.of("first", "second"), "test"); // pass } @Test - public void testCheckNullNonNullNonEmptyEntries_nullValueFail() { + void testCheckNullNonNullNonEmptyEntries_nullValueFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(Arrays.asList("first", null), "test"); Assert.fail(); @@ -189,7 +189,7 @@ public void testCheckNullNonNullNonEmptyEntries_nullValueFail() { } @Test - public void testCheckNullOrNonNullNonEmptyEntries_emptyValueFail() { + void testCheckNullOrNonNullNonEmptyEntries_emptyValueFail() { try { Validator.checkNullOrNonNullNonEmptyEntries(ImmutableList.of("first", " "), "test"); Assert.fail(); @@ -199,25 +199,25 @@ public void testCheckNullOrNonNullNonEmptyEntries_emptyValueFail() { } @Test - public void testCheckNullOrNonNullEntries_nullPass() { + void testCheckNullOrNonNullEntries_nullPass() { Validator.checkNullOrNonNullEntries(null, "test"); // pass } @Test - public void testCheckNullOrNonNullEntries_emptyPass() { + void testCheckNullOrNonNullEntries_emptyPass() { Validator.checkNullOrNonNullEntries(ImmutableList.of(), "test"); // pass } @Test - public void testCheckNullOrNonNullEntries_valuesPass() { + void testCheckNullOrNonNullEntries_valuesPass() { Validator.checkNullOrNonNullEntries(ImmutableList.of(new Object(), new Object()), "test"); // pass } @Test - public void testCheckNullOrNonNullEntries_nullFail() { + void testCheckNullOrNonNullEntries_nullFail() { try { Validator.checkNullOrNonNullEntries(Arrays.asList(new Object(), null), "test"); Assert.fail(); @@ -228,13 +228,13 @@ public void testCheckNullOrNonNullEntries_nullFail() { } @Test - public void testCheckEquals_pass() { + void testCheckEquals_pass() { Validator.checkEquals("value", "ignored", "value"); // pass } @Test - public void testCheckEquals_failsNull() { + void testCheckEquals_failsNull() { try { Validator.checkEquals(null, "test", "something"); Assert.fail(); @@ -244,7 +244,7 @@ public void testCheckEquals_failsNull() { } @Test - public void testCheckEquals_failsNotEquals() { + void testCheckEquals_failsNotEquals() { try { Validator.checkEquals("somethingElse", "test", "something"); Assert.fail(); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java index 3775aeb13b1..d5be3143a2b 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/JarFilesTest.java @@ -40,18 +40,22 @@ import java.time.Instant; import java.util.Arrays; import java.util.Optional; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; 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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link JarFiles}. */ -@RunWith(JUnitParamsRunner.class) -public class JarFilesTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JarFilesTest { @Rule public final MockitoRule mockitoRule = MockitoJUnit.rule().silent(); @@ -64,8 +68,8 @@ public class JarFilesTest { @Mock private CommonContainerConfigCliOptions mockCommonContainerConfigCliOptions; @Mock private ConsoleLogger mockLogger; - @Test - @Parameters( + @ParameterizedTest + @CsvSource( value = { "8, eclipse-temurin:8-jre", "9, eclipse-temurin:11-jre", @@ -73,7 +77,7 @@ public class JarFilesTest { "13, eclipse-temurin:17-jre", "17, eclipse-temurin:17-jre", }) - public void testToJibContainer_defaultBaseImage(int javaVersion, String expectedBaseImage) + void testToJibContainer_defaultBaseImage(int javaVersion, String expectedBaseImage) throws IOException, InvalidImageReferenceException { when(mockStandardExplodedProcessor.getJavaVersion()).thenReturn(javaVersion); JibContainerBuilder containerBuilder = @@ -89,7 +93,7 @@ public void testToJibContainer_defaultBaseImage(int javaVersion, String expected } @Test - public void testToJibContainerBuilder_explodedStandard_basicInfo() + void testToJibContainerBuilder_explodedStandard_basicInfo() throws IOException, InvalidImageReferenceException { when(mockStandardExplodedProcessor.getJavaVersion()).thenReturn(8); FileEntriesLayer layer = @@ -140,7 +144,7 @@ public void testToJibContainerBuilder_explodedStandard_basicInfo() } @Test - public void testToJibContainerBuilder_packagedStandard_basicInfo() + void testToJibContainerBuilder_packagedStandard_basicInfo() throws IOException, InvalidImageReferenceException { when(mockStandardPackagedProcessor.getJavaVersion()).thenReturn(8); FileEntriesLayer layer = @@ -188,7 +192,7 @@ public void testToJibContainerBuilder_packagedStandard_basicInfo() } @Test - public void testToJibContainerBuilder_explodedLayeredSpringBoot_basicInfo() + void testToJibContainerBuilder_explodedLayeredSpringBoot_basicInfo() throws IOException, InvalidImageReferenceException { when(mockSpringBootExplodedProcessor.getJavaVersion()).thenReturn(8); FileEntriesLayer layer = @@ -240,7 +244,7 @@ public void testToJibContainerBuilder_explodedLayeredSpringBoot_basicInfo() } @Test - public void testToJibContainerBuilder_packagedSpringBoot_basicInfo() + void testToJibContainerBuilder_packagedSpringBoot_basicInfo() throws IOException, InvalidImageReferenceException { when(mockSpringBootPackagedProcessor.getJavaVersion()).thenReturn(8); FileEntriesLayer layer = @@ -289,7 +293,7 @@ public void testToJibContainerBuilder_packagedSpringBoot_basicInfo() } @Test - public void testToJibContainerBuilder_optionalParameters() + void testToJibContainerBuilder_optionalParameters() throws IOException, InvalidImageReferenceException { when(mockCommonContainerConfigCliOptions.getFrom()).thenReturn(Optional.of("base-image")); when(mockCommonContainerConfigCliOptions.getExposedPorts()) diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootExplodedProcessorTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootExplodedProcessorTest.java index 7440739fda5..59d2f84a444 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootExplodedProcessorTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootExplodedProcessorTest.java @@ -30,12 +30,11 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -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; /** Tests for {@link SpringBootExplodedProcessor}. */ -public class SpringBootExplodedProcessorTest { +class SpringBootExplodedProcessorTest { private static final String SPRING_BOOT_LAYERED = "jar/spring-boot/springboot_layered.jar"; private static final String SPRING_BOOT_LAYERED_WITH_EMPTY_LAYER = @@ -45,10 +44,10 @@ public class SpringBootExplodedProcessorTest { private static final String SPRING_BOOT_NOT_LAYERED = "jar/spring-boot/springboot_notLayered.jar"; private static final Integer JAR_JAVA_VERSION = 0; // any value - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testCreateLayers_layered_allListed() throws IOException, URISyntaxException { + void testCreateLayers_layered_allListed() throws IOException, URISyntaxException { // BOOT-INF/layers.idx for this spring-boot jar is as follows: // - "dependencies": // - "BOOT-INF/lib/dependency1.jar" @@ -61,7 +60,7 @@ public void testCreateLayers_layered_allListed() throws IOException, URISyntaxEx // - "BOOT-INF/classes/" // - "META-INF/" Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_LAYERED).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; SpringBootExplodedProcessor springBootExplodedModeProcessor = new SpringBootExplodedProcessor(springBootJar, destDir, JAR_JAVA_VERSION); @@ -111,8 +110,7 @@ public void testCreateLayers_layered_allListed() throws IOException, URISyntaxEx } @Test - public void testCreateLayers_layered_singleEmptyLayerListed() - throws IOException, URISyntaxException { + void testCreateLayers_layered_singleEmptyLayerListed() throws IOException, URISyntaxException { // BOOT-INF/layers.idx for this spring-boot jar is as follows: // - "dependencies": // - "BOOT-INF/lib/dependency1.jar" @@ -125,7 +123,7 @@ public void testCreateLayers_layered_singleEmptyLayerListed() // - "META-INF/" Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_LAYERED_WITH_EMPTY_LAYER).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; SpringBootExplodedProcessor springBootExplodedModeProcessor = new SpringBootExplodedProcessor(springBootJar, destDir, JAR_JAVA_VERSION); @@ -167,8 +165,7 @@ public void testCreateLayers_layered_singleEmptyLayerListed() } @Test - public void testCreateLayers_layered_allEmptyLayersListed() - throws IOException, URISyntaxException { + void testCreateLayers_layered_allEmptyLayersListed() throws IOException, URISyntaxException { // BOOT-INF/layers.idx for this spring-boot jar is as follows: // - "dependencies": // - "spring-boot-loader": @@ -176,7 +173,7 @@ public void testCreateLayers_layered_allEmptyLayersListed() // - "application": Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_LAYERED_WITH_ALL_EMPTY_LAYERS_LISTED).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; SpringBootExplodedProcessor springBootExplodedModeProcessor = new SpringBootExplodedProcessor(springBootJar, destDir, JAR_JAVA_VERSION); @@ -186,9 +183,9 @@ public void testCreateLayers_layered_allEmptyLayersListed() } @Test - public void testCreateLayers_nonLayered() throws IOException, URISyntaxException { + void testCreateLayers_nonLayered() throws IOException, URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_NOT_LAYERED).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; SpringBootExplodedProcessor springBootExplodedModeProcessor = new SpringBootExplodedProcessor(springBootJar, destDir, JAR_JAVA_VERSION); @@ -239,7 +236,7 @@ public void testCreateLayers_nonLayered() throws IOException, URISyntaxException } @Test - public void testComputeEntrypoint() { + void testComputeEntrypoint() { SpringBootExplodedProcessor bootProcessor = new SpringBootExplodedProcessor( Paths.get("ignored"), Paths.get("ignored"), JAR_JAVA_VERSION); @@ -250,7 +247,7 @@ public void testComputeEntrypoint() { } @Test - public void testComputeEntrypoint_withJvmFlags() { + void testComputeEntrypoint_withJvmFlags() { SpringBootExplodedProcessor bootProcessor = new SpringBootExplodedProcessor( Paths.get("ignored"), Paths.get("ignored"), JAR_JAVA_VERSION); @@ -263,7 +260,7 @@ public void testComputeEntrypoint_withJvmFlags() { } @Test - public void testGetJavaVersion() { + void testGetJavaVersion() { SpringBootExplodedProcessor springBootExplodedProcessor = new SpringBootExplodedProcessor(Paths.get("ignore"), Paths.get("ignore"), 8); assertThat(springBootExplodedProcessor.getJavaVersion()).isEqualTo(8); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java index 92358992bfd..c5a859e8ae5 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/SpringBootPackagedProcessorTest.java @@ -26,16 +26,16 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link SpringBootPackagedProcessor}. */ -public class SpringBootPackagedProcessorTest { +class SpringBootPackagedProcessorTest { private static final String SPRING_BOOT_JAR = "jar/spring-boot/springboot_sample.jar"; private static final Integer JAR_JAVA_VERSION = 0; // any value @Test - public void testCreateLayers() throws URISyntaxException { + void testCreateLayers() throws URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI()); SpringBootPackagedProcessor springBootProcessor = new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION); @@ -53,7 +53,7 @@ public void testCreateLayers() throws URISyntaxException { } @Test - public void testComputeEntrypoint() throws URISyntaxException { + void testComputeEntrypoint() throws URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI()); SpringBootPackagedProcessor springBootProcessor = new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION); @@ -66,7 +66,7 @@ public void testComputeEntrypoint() throws URISyntaxException { } @Test - public void testComputeEntrypoint_jvmFlag() throws URISyntaxException { + void testComputeEntrypoint_jvmFlag() throws URISyntaxException { Path springBootJar = Paths.get(Resources.getResource(SPRING_BOOT_JAR).toURI()); SpringBootPackagedProcessor springBootProcessor = new SpringBootPackagedProcessor(springBootJar, JAR_JAVA_VERSION); @@ -79,7 +79,7 @@ public void testComputeEntrypoint_jvmFlag() throws URISyntaxException { } @Test - public void testGetJavaVersion() { + void testGetJavaVersion() { SpringBootPackagedProcessor springBootPackagedProcessor = new SpringBootPackagedProcessor(Paths.get("ignore"), 8); assertThat(springBootPackagedProcessor.getJavaVersion()).isEqualTo(8); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardExplodedProcessorTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardExplodedProcessorTest.java index 65cd04b2a83..fd436566d8c 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardExplodedProcessorTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardExplodedProcessorTest.java @@ -30,12 +30,11 @@ import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; -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; /** Tests for {@link StandardExplodedProcessor}. */ -public class StandardExplodedProcessorTest { +class StandardExplodedProcessorTest { private static final String STANDARD_JAR_WITHOUT_CLASS_PATH_MANIFEST = "jar/standard/standardJarWithoutClassPath.jar"; @@ -47,12 +46,12 @@ public class StandardExplodedProcessorTest { private static final String STANDARD_SINGLE_DEPENDENCY_JAR = "jar/standard/singleDepJar.jar"; private static final Integer JAR_JAVA_VERSION = 0; // any value - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testCreateLayers_emptyJar() throws IOException, URISyntaxException { + void testCreateLayers_emptyJar() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_EMPTY).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, destDir, JAR_JAVA_VERSION); @@ -68,10 +67,10 @@ public void testCreateLayers_emptyJar() throws IOException, URISyntaxException { } @Test - public void testCreateLayers_withClassPathInManifest() throws IOException, URISyntaxException { + void testCreateLayers_withClassPathInManifest() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, destDir, JAR_JAVA_VERSION); @@ -130,10 +129,10 @@ public void testCreateLayers_withClassPathInManifest() throws IOException, URISy } @Test - public void testCreateLayers_withoutClassPathInManifest() throws IOException, URISyntaxException { + void testCreateLayers_withoutClassPathInManifest() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITHOUT_CLASS_PATH_MANIFEST).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, destDir, JAR_JAVA_VERSION); @@ -174,10 +173,10 @@ public void testCreateLayers_withoutClassPathInManifest() throws IOException, UR } @Test - public void testCreateLayers_withoutClassPathInManifest_containsOnlyClasses() + void testCreateLayers_withoutClassPathInManifest_containsOnlyClasses() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_ONLY_CLASSES).toURI()); - Path destDir = temporaryFolder.newFolder().toPath(); + Path destDir = temporaryFolder; StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, destDir, JAR_JAVA_VERSION); @@ -205,9 +204,9 @@ public void testCreateLayers_withoutClassPathInManifest_containsOnlyClasses() } @Test - public void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException { + void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_SINGLE_DEPENDENCY_JAR).toURI()); - Path destDir = temporaryFolder.getRoot().toPath(); + Path destDir = temporaryFolder; StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, destDir, JAR_JAVA_VERSION); @@ -223,7 +222,7 @@ public void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException } @Test - public void testComputeEntrypoint_noMainClass() throws URISyntaxException { + void testComputeEntrypoint_noMainClass() throws URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_EMPTY).toURI()); StandardExplodedProcessor standardExplodedModeProcessor = new StandardExplodedProcessor(standardJar, Paths.get("ignore"), JAR_JAVA_VERSION); @@ -241,7 +240,7 @@ public void testComputeEntrypoint_noMainClass() throws URISyntaxException { } @Test - public void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxException { + void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); StandardExplodedProcessor standardExplodedModeProcessor = @@ -256,8 +255,7 @@ public void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxE } @Test - public void testComputeEntrypoint_withMainClass_jvmFlags() - throws IOException, URISyntaxException { + void testComputeEntrypoint_withMainClass_jvmFlags() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); StandardExplodedProcessor standardExplodedModeProcessor = @@ -273,7 +271,7 @@ public void testComputeEntrypoint_withMainClass_jvmFlags() } @Test - public void testGetJavaVersion() { + void testGetJavaVersion() { StandardExplodedProcessor standardExplodedProcessor = new StandardExplodedProcessor(Paths.get("ignore"), Paths.get("ignore"), 8); assertThat(standardExplodedProcessor.getJavaVersion()).isEqualTo(8); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardPackagedProcessorTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardPackagedProcessorTest.java index 47a43e0cc16..fa4f990094d 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardPackagedProcessorTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/jar/StandardPackagedProcessorTest.java @@ -30,10 +30,10 @@ import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link StandardPackagedProcessor}. */ -public class StandardPackagedProcessorTest { +class StandardPackagedProcessorTest { private static final String STANDARD_JAR_EMPTY = "jar/standard/emptyStandardJar.jar"; private static final String STANDARD_SINGLE_DEPENDENCY_JAR = "jar/standard/singleDepJar.jar"; @@ -42,7 +42,7 @@ public class StandardPackagedProcessorTest { private static final Integer JAR_JAVA_VERSION = 0; // any value @Test - public void testCreateLayers_emptyJar() throws IOException, URISyntaxException { + void testCreateLayers_emptyJar() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_EMPTY).toURI()); StandardPackagedProcessor standardPackagedModeProcessor = new StandardPackagedProcessor(standardJar, JAR_JAVA_VERSION); @@ -59,7 +59,7 @@ public void testCreateLayers_emptyJar() throws IOException, URISyntaxException { } @Test - public void testCreateLayers_withClassPathInManifest() throws IOException, URISyntaxException { + void testCreateLayers_withClassPathInManifest() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); StandardPackagedProcessor standardPackagedModeProcessor = @@ -99,7 +99,7 @@ public void testCreateLayers_withClassPathInManifest() throws IOException, URISy } @Test - public void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException { + void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_SINGLE_DEPENDENCY_JAR).toURI()); StandardPackagedProcessor standardPackagedModeProcessor = new StandardPackagedProcessor(standardJar, JAR_JAVA_VERSION); @@ -116,7 +116,7 @@ public void testCreateLayers_dependencyDoesNotExist() throws URISyntaxException } @Test - public void testComputeEntrypoint_noMainClass() throws URISyntaxException { + void testComputeEntrypoint_noMainClass() throws URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_EMPTY).toURI()); StandardPackagedProcessor standardPackagedModeProcessor = new StandardPackagedProcessor(standardJar, JAR_JAVA_VERSION); @@ -134,7 +134,7 @@ public void testComputeEntrypoint_noMainClass() throws URISyntaxException { } @Test - public void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxException { + void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); StandardPackagedProcessor standardPackagedModeProcessor = @@ -148,8 +148,7 @@ public void testComputeEntrypoint_withMainClass() throws IOException, URISyntaxE } @Test - public void testComputeEntrypoint_withMainClass_jvmFlags() - throws IOException, URISyntaxException { + void testComputeEntrypoint_withMainClass_jvmFlags() throws IOException, URISyntaxException { Path standardJar = Paths.get(Resources.getResource(STANDARD_JAR_WITH_CLASS_PATH_MANIFEST).toURI()); StandardPackagedProcessor standardPackagedModeProcessor = @@ -164,7 +163,7 @@ public void testComputeEntrypoint_withMainClass_jvmFlags() } @Test - public void testGetJavaVersion() { + void testGetJavaVersion() { StandardPackagedProcessor standardPackagedProcessor = new StandardPackagedProcessor(Paths.get("ignore"), 8); assertThat(standardPackagedProcessor.getJavaVersion()).isEqualTo(8); diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/logging/CliLoggerTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/logging/CliLoggerTest.java index 596cf2f5224..2e3fa8146ae 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/logging/CliLoggerTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/logging/CliLoggerTest.java @@ -24,17 +24,20 @@ import java.io.PrintWriter; import java.time.Duration; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link CliLogger}. */ -@RunWith(MockitoJUnitRunner.class) -public class CliLoggerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CliLoggerTest { @Rule public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties(); @@ -61,7 +64,7 @@ private void createLoggerAndSendMessages(Verbosity verbosity, ConsoleOutput cons } @Test - public void testLog_quiet_plainConsole() { + void testLog_quiet_plainConsole() { createLoggerAndSendMessages(Verbosity.quiet, ConsoleOutput.plain); Mockito.verifyNoInteractions(mockOut); @@ -69,7 +72,7 @@ public void testLog_quiet_plainConsole() { } @Test - public void testLog_error_plainConsole() { + void testLog_error_plainConsole() { createLoggerAndSendMessages(Verbosity.error, ConsoleOutput.plain); Mockito.verify(mockErr).println("[ERROR] error"); @@ -78,7 +81,7 @@ public void testLog_error_plainConsole() { } @Test - public void testLog_warn_plainConsole() { + void testLog_warn_plainConsole() { createLoggerAndSendMessages(Verbosity.warn, ConsoleOutput.plain); Mockito.verify(mockErr).println("[ERROR] error"); @@ -88,7 +91,7 @@ public void testLog_warn_plainConsole() { } @Test - public void testLog_lifecycle_plainConsole() { + void testLog_lifecycle_plainConsole() { createLoggerAndSendMessages(Verbosity.lifecycle, ConsoleOutput.plain); Mockito.verify(mockErr).println("[ERROR] error"); @@ -100,7 +103,7 @@ public void testLog_lifecycle_plainConsole() { } @Test - public void testLog_info_plainConsole() { + void testLog_info_plainConsole() { createLoggerAndSendMessages(Verbosity.info, ConsoleOutput.plain); Mockito.verify(mockErr).println("[ERROR] error"); @@ -113,7 +116,7 @@ public void testLog_info_plainConsole() { } @Test - public void testLog_debug_plainConsole() { + void testLog_debug_plainConsole() { createLoggerAndSendMessages(Verbosity.debug, ConsoleOutput.plain); Mockito.verify(mockErr).println("[ERROR] error"); @@ -127,7 +130,7 @@ public void testLog_debug_plainConsole() { } @Test - public void testLog_quiet_richConsole() { + void testLog_quiet_richConsole() { createLoggerAndSendMessages(Verbosity.quiet, ConsoleOutput.rich); Mockito.verifyNoInteractions(mockOut); @@ -135,7 +138,7 @@ public void testLog_quiet_richConsole() { } @Test - public void testLog_error_richConsole() { + void testLog_error_richConsole() { createLoggerAndSendMessages(Verbosity.error, ConsoleOutput.rich); Mockito.verify(mockErr).println("[ERROR] error"); @@ -144,7 +147,7 @@ public void testLog_error_richConsole() { } @Test - public void testLog_warn_richConsole() { + void testLog_warn_richConsole() { createLoggerAndSendMessages(Verbosity.warn, ConsoleOutput.rich); Mockito.verify(mockErr).println("[ERROR] error"); @@ -154,7 +157,7 @@ public void testLog_warn_richConsole() { } @Test - public void testLog_lifecycle_richConsole() { + void testLog_lifecycle_richConsole() { createLoggerAndSendMessages(Verbosity.lifecycle, ConsoleOutput.rich); Mockito.verify(mockErr).println("[ERROR] error"); @@ -165,7 +168,7 @@ public void testLog_lifecycle_richConsole() { } @Test - public void testLog_info_richConsole() { + void testLog_info_richConsole() { createLoggerAndSendMessages(Verbosity.info, ConsoleOutput.rich); Mockito.verify(mockErr).println("[ERROR] error"); @@ -177,7 +180,7 @@ public void testLog_info_richConsole() { } @Test - public void testLog_debug_richConsole() { + void testLog_debug_richConsole() { createLoggerAndSendMessages(Verbosity.debug, ConsoleOutput.rich); Mockito.verify(mockErr).println("[ERROR] error"); @@ -190,28 +193,28 @@ public void testLog_debug_richConsole() { } @Test - public void testIsRichConsole_true() { + void testIsRichConsole_true() { assertThat(CliLogger.isRichConsole(ConsoleOutput.rich, HttpTraceLevel.off)).isTrue(); } @Test - public void testIsRichConsole_falseIfHttpTrace() { + void testIsRichConsole_falseIfHttpTrace() { assertThat(CliLogger.isRichConsole(ConsoleOutput.rich, HttpTraceLevel.config)).isFalse(); } @Test - public void testIsRichConsole_false() { + void testIsRichConsole_false() { assertThat(CliLogger.isRichConsole(ConsoleOutput.plain, HttpTraceLevel.off)).isFalse(); } @Test - public void testIsRightConsole_autoWindowsTrue() { + void testIsRightConsole_autoWindowsTrue() { System.setProperty("os.name", "windows"); assertThat(CliLogger.isRichConsole(ConsoleOutput.auto, HttpTraceLevel.off)).isTrue(); } @Test - public void testIsRightConsole_autoDumbTermFalse() { + void testIsRightConsole_autoDumbTermFalse() { environmentVariables.set("TERM", "dumb"); assertThat(CliLogger.isRichConsole(ConsoleOutput.auto, HttpTraceLevel.off)).isFalse(); } diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/StandardWarExplodedProcessorTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/StandardWarExplodedProcessorTest.java index e18b5ff487a..f90553be711 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/StandardWarExplodedProcessorTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/StandardWarExplodedProcessorTest.java @@ -37,28 +37,28 @@ import java.util.StringJoiner; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -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; -public class StandardWarExplodedProcessorTest { +class StandardWarExplodedProcessorTest { private static final AbsoluteUnixPath APP_ROOT = AbsoluteUnixPath.get("/my/app"); private static final Correspondence EXTRACTION_PATH_OF = Correspondence.transforming( entry -> entry.getExtractionPath().toString(), "has extractionPath of"); - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; + + @TempDir public Path temporaryFolderDestination; @Test - public void testCreateLayers_allLayers_correctExtractionPaths() - throws IOException, URISyntaxException { + void testCreateLayers_allLayers_correctExtractionPaths() throws IOException, URISyntaxException { // Prepare war file for test - Path tempDirectory = temporaryFolder.getRoot().toPath(); + Path tempDirectory = temporaryFolder; Path warContents = Paths.get(Resources.getResource("war/standard/allLayers").toURI()); Path standardWar = zipUpDirectory(warContents, tempDirectory.resolve("standardWar.war")); - Path explodedWarDestination = temporaryFolder.newFolder("exploded-war").toPath(); + Path explodedWarDestination = temporaryFolderDestination; StandardWarExplodedProcessor processor = new StandardWarExplodedProcessor(standardWar, explodedWarDestination, APP_ROOT); List layers = processor.createLayers(); @@ -91,14 +91,14 @@ public void testCreateLayers_allLayers_correctExtractionPaths() } @Test - public void testCreateLayers_webInfLibDoesNotExist_correctExtractionPaths() + void testCreateLayers_webInfLibDoesNotExist_correctExtractionPaths() throws IOException, URISyntaxException { // Prepare war file for test - Path tempDirectory = temporaryFolder.getRoot().toPath(); + Path tempDirectory = temporaryFolder; Path warContents = Paths.get(Resources.getResource("war/standard/noWebInfLib").toURI()); Path standardWar = zipUpDirectory(warContents, tempDirectory.resolve("noDependenciesWar.war")); - Path explodedWarDestination = temporaryFolder.newFolder("exploded-war").toPath(); + Path explodedWarDestination = temporaryFolderDestination; StandardWarExplodedProcessor processor = new StandardWarExplodedProcessor(standardWar, explodedWarDestination, APP_ROOT); List layers = processor.createLayers(); @@ -119,14 +119,14 @@ public void testCreateLayers_webInfLibDoesNotExist_correctExtractionPaths() } @Test - public void testCreateLayers_webInfClassesDoesNotExist_correctExtractionPaths() + void testCreateLayers_webInfClassesDoesNotExist_correctExtractionPaths() throws IOException, URISyntaxException { // Prepare war file for test - Path tempDirectory = temporaryFolder.getRoot().toPath(); + Path tempDirectory = temporaryFolder; Path warContents = Paths.get(Resources.getResource("war/standard/noWebInfClasses").toURI()); Path standardWar = zipUpDirectory(warContents, tempDirectory.resolve("noClassesWar.war")); - Path explodedWarDestination = temporaryFolder.newFolder("exploded-war").toPath(); + Path explodedWarDestination = temporaryFolderDestination; StandardWarExplodedProcessor processor = new StandardWarExplodedProcessor(standardWar, explodedWarDestination, APP_ROOT); List layers = processor.createLayers(); @@ -149,7 +149,7 @@ public void testCreateLayers_webInfClassesDoesNotExist_correctExtractionPaths() } @Test - public void testComputeEntrypoint() { + void testComputeEntrypoint() { StandardWarExplodedProcessor processor = new StandardWarExplodedProcessor(Paths.get("ignore"), Paths.get("ignore"), APP_ROOT); UnsupportedOperationException exception = @@ -162,7 +162,7 @@ public void testComputeEntrypoint() { } @Test - public void testGetJavaVersion() { + void testGetJavaVersion() { StandardWarExplodedProcessor processor = new StandardWarExplodedProcessor(Paths.get("ignore"), Paths.get("ignore"), APP_ROOT); UnsupportedOperationException exception = diff --git a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/WarFilesTest.java b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/WarFilesTest.java index 513d7bc559b..cfd72e47c03 100644 --- a/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/WarFilesTest.java +++ b/jib-cli/src/test/java/com/google/cloud/tools/jib/cli/war/WarFilesTest.java @@ -37,14 +37,17 @@ import java.time.Instant; import java.util.Arrays; import java.util.Optional; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link WarFiles}. */ -@RunWith(MockitoJUnitRunner.class) -public class WarFilesTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class WarFilesTest { @Mock private StandardWarExplodedProcessor mockStandardWarExplodedProcessor; @Mock private CommonCliOptions mockCommonCliOptions; @@ -52,7 +55,7 @@ public class WarFilesTest { @Mock private ConsoleLogger mockLogger; @Test - public void testToJibContainerBuilder_explodedStandard_basicInfo() + void testToJibContainerBuilder_explodedStandard_basicInfo() throws IOException, InvalidImageReferenceException { FileEntriesLayer layer = FileEntriesLayer.builder() @@ -89,7 +92,7 @@ public void testToJibContainerBuilder_explodedStandard_basicInfo() } @Test - public void testToJibContainerBuilder_optionalParameters() + void testToJibContainerBuilder_optionalParameters() throws IOException, InvalidImageReferenceException { when(mockCommonContainerConfigCliOptions.getFrom()).thenReturn(Optional.of("base-image")); when(mockCommonContainerConfigCliOptions.getExposedPorts()) @@ -133,7 +136,7 @@ public void testToJibContainerBuilder_optionalParameters() } @Test - public void testToJibContainerBuilder_nonJettyBaseImageSpecifiedAndNoEntrypoint() + void testToJibContainerBuilder_nonJettyBaseImageSpecifiedAndNoEntrypoint() throws IOException, InvalidImageReferenceException { JibContainerBuilder containerBuilder = WarFiles.toJibContainerBuilder( @@ -148,7 +151,7 @@ public void testToJibContainerBuilder_nonJettyBaseImageSpecifiedAndNoEntrypoint( } @Test - public void testToJibContainerBuilder_noProgramArgumentsSpecified() + void testToJibContainerBuilder_noProgramArgumentsSpecified() throws IOException, InvalidImageReferenceException { JibContainerBuilder containerBuilder = WarFiles.toJibContainerBuilder( diff --git a/jib-core/build.gradle b/jib-core/build.gradle index f31340e269d..422c5d75836 100644 --- a/jib-core/build.gradle +++ b/jib-core/build.gradle @@ -18,6 +18,7 @@ dependencies { implementation dependencyStrings.GOOGLE_HTTP_CLIENT_APACHE_V2 implementation dependencyStrings.GOOGLE_AUTH_LIBRARY_OAUTH2_HTTP + testImplementation dependencyStrings.SYSTEM_RULES_STUB implementation dependencyStrings.COMMONS_COMPRESS zstdSupportImplementation dependencyStrings.ZSTD_JNI implementation dependencyStrings.GUAVA @@ -26,7 +27,9 @@ dependencies { implementation dependencyStrings.JACKSON_DATATYPE_JSR310 implementation dependencyStrings.ASM - testImplementation dependencyStrings.JUNIT + testImplementation dependencyStrings.JUNIT_API + testRuntimeOnly dependencyStrings.JUNIT_ENGINE + testImplementation dependencyStrings.JUNIT_PARAM_TESTS testImplementation dependencyStrings.TRUTH testImplementation dependencyStrings.TRUTH8 testImplementation dependencyStrings.MOCKITO_CORE @@ -71,7 +74,7 @@ publishing { release { tagTemplate = 'v$version-core' git { - requireBranch = /^core-release-v\d+.*$/ //regex + requireBranch.set(/^core-release-v\d+.*$/) //regex } } /* RELEASE */ @@ -79,3 +82,6 @@ release { /* ECLIPSE */ eclipse.classpath.plusConfigurations += [configurations.integrationTestImplementation] /* ECLIPSE */ + + + diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ContainerizerIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ContainerizerIntegrationTest.java index 8715ffb784a..a048401cf35 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ContainerizerIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ContainerizerIntegrationTest.java @@ -43,8 +43,8 @@ import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; +import org.junit.jupiter.api.Test; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/JibIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/JibIntegrationTest.java index a9916708c35..aea1b262b4d 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/JibIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/JibIntegrationTest.java @@ -37,13 +37,13 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; 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.rules.TemporaryFolder; /** Integration tests for {@link Jib}. */ @@ -95,12 +95,12 @@ public static void setUpClass() throws IOException, InterruptedException { localRegistry.pullAndPushToLocal("busybox", "busybox"); } - @Before + @BeforeEach public void setUp() { System.setProperty("sendCredentialsOverHttp", "true"); } - @After + @AfterEach public void tearDown() { System.clearProperty("sendCredentialsOverHttp"); } diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ReproducibleImageTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ReproducibleImageTest.java index 1c194b2198d..63998d16923 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ReproducibleImageTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/api/ReproducibleImageTest.java @@ -45,7 +45,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.junit.BeforeClass; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.rules.TemporaryFolder; /** diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BearerAuthenticationIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BearerAuthenticationIntegrationTest.java index fd62675406f..770f4f17eee 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BearerAuthenticationIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BearerAuthenticationIntegrationTest.java @@ -20,7 +20,7 @@ import com.google.cloud.tools.jib.event.EventHandlers; import com.google.cloud.tools.jib.http.FailoverHttpClient; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for bearer authentication. */ public class BearerAuthenticationIntegrationTest { diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobCheckerIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobCheckerIntegrationTest.java index 508fbd51ee6..540446fcbd3 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobCheckerIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobCheckerIntegrationTest.java @@ -16,6 +16,9 @@ package com.google.cloud.tools.jib.registry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import com.google.cloud.tools.jib.api.DescriptorDigest; import com.google.cloud.tools.jib.api.RegistryException; import com.google.cloud.tools.jib.event.EventHandlers; @@ -23,8 +26,7 @@ import com.google.cloud.tools.jib.image.json.V22ManifestTemplate; import java.io.IOException; import java.security.DigestException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link BlobChecker}. */ public class BlobCheckerIntegrationTest { @@ -43,7 +45,7 @@ public void testCheck_exists() throws IOException, RegistryException { .getManifest(); DescriptorDigest blobDigest = manifestTemplate.getLayers().get(0).getDigest(); - Assert.assertEquals(blobDigest, registryClient.checkBlob(blobDigest).get().getDigest()); + assertEquals(blobDigest, registryClient.checkBlob(blobDigest).get().getDigest()); } @Test @@ -55,6 +57,6 @@ public void testCheck_doesNotExist() throws IOException, RegistryException, Dige DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - Assert.assertFalse(registryClient.checkBlob(fakeBlobDigest).isPresent()); + assertFalse(registryClient.checkBlob(fakeBlobDigest).isPresent()); } } diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPullerIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPullerIntegrationTest.java index 1886e4c6498..9e65ea2a51b 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPullerIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPullerIntegrationTest.java @@ -29,7 +29,7 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link BlobPuller}. */ public class BlobPullerIntegrationTest { diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPusherIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPusherIntegrationTest.java index 3d68e2ef634..b38f8eaa133 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPusherIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/BlobPusherIntegrationTest.java @@ -26,7 +26,7 @@ import java.security.DigestException; import org.junit.Assert; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link BlobPusher}. */ public class BlobPusherIntegrationTest { diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestCheckerIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestCheckerIntegrationTest.java index fa8d5c7a38f..492b21d1cbf 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestCheckerIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestCheckerIntegrationTest.java @@ -25,7 +25,7 @@ import com.google.cloud.tools.jib.image.json.ManifestTemplate; import java.io.IOException; import java.util.Optional; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link ManifestChecker}. */ public class ManifestCheckerIntegrationTest { diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPullerIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPullerIntegrationTest.java index da6f058ccb9..0d0505d77c0 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPullerIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPullerIntegrationTest.java @@ -31,7 +31,7 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link ManifestPuller}. */ public class ManifestPullerIntegrationTest { diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPusherIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPusherIntegrationTest.java index 478762d893e..edbaab1722a 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPusherIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/ManifestPusherIntegrationTest.java @@ -31,7 +31,7 @@ import java.security.DigestException; import org.junit.Assert; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link ManifestPusher}. */ public class ManifestPusherIntegrationTest { diff --git a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperIntegrationTest.java b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperIntegrationTest.java index bda754c9b2b..708933f5d8f 100644 --- a/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperIntegrationTest.java +++ b/jib-core/src/integration-test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperIntegrationTest.java @@ -26,7 +26,7 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Integration tests for {@link DockerCredentialHelper}. */ public class DockerCredentialHelperIntegrationTest { diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/ContainerizerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/ContainerizerTest.java index f6a4432c621..1c7945c1539 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/ContainerizerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/ContainerizerTest.java @@ -27,14 +27,14 @@ import java.util.Arrays; import java.util.concurrent.ExecutorService; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** Tests for {@link Containerizer}. */ -public class ContainerizerTest { +class ContainerizerTest { @Test - public void testTo() throws CacheDirectoryCreationException, InvalidImageReferenceException { + void testTo() throws CacheDirectoryCreationException, InvalidImageReferenceException { RegistryImage registryImage = RegistryImage.named("registry/image"); DockerDaemonImage dockerDaemonImage = DockerDaemonImage.named("daemon/image"); TarImage tarImage = TarImage.at(Paths.get("ignored")).named("tar/iamge"); @@ -80,7 +80,7 @@ private void verifyTo(Containerizer containerizer) throws CacheDirectoryCreation } @Test - public void testWithAdditionalTag() throws InvalidImageReferenceException { + void testWithAdditionalTag() throws InvalidImageReferenceException { Containerizer containerizer = Containerizer.to(DockerDaemonImage.named("image")); containerizer.withAdditionalTag("tag"); @@ -93,7 +93,7 @@ public void testWithAdditionalTag() throws InvalidImageReferenceException { } @Test - public void testGetImageConfiguration_registryImage() throws InvalidImageReferenceException { + void testGetImageConfiguration_registryImage() throws InvalidImageReferenceException { CredentialRetriever credentialRetriever = Mockito.mock(CredentialRetriever.class); Containerizer containerizer = Containerizer.to( @@ -106,7 +106,7 @@ public void testGetImageConfiguration_registryImage() throws InvalidImageReferen } @Test - public void testGetImageConfiguration_dockerDaemonImage() throws InvalidImageReferenceException { + void testGetImageConfiguration_dockerDaemonImage() throws InvalidImageReferenceException { Containerizer containerizer = Containerizer.to(DockerDaemonImage.named("docker/deamon/image")); ImageConfiguration imageConfiguration = containerizer.getImageConfiguration(); @@ -115,7 +115,7 @@ public void testGetImageConfiguration_dockerDaemonImage() throws InvalidImageRef } @Test - public void testGetImageConfiguration_tarImage() throws InvalidImageReferenceException { + void testGetImageConfiguration_tarImage() throws InvalidImageReferenceException { Containerizer containerizer = Containerizer.to(TarImage.at(Paths.get("output/file")).named("tar/image")); @@ -125,7 +125,7 @@ public void testGetImageConfiguration_tarImage() throws InvalidImageReferenceExc } @Test - public void testGetApplicationLayersCacheDirectory_defaults() + void testGetApplicationLayersCacheDirectory_defaults() throws InvalidImageReferenceException, CacheDirectoryCreationException, IOException { Containerizer containerizer = Containerizer.to(RegistryImage.named("registry/image")); Path applicationLayersCache = containerizer.getApplicationLayersCacheDirectory(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/CredentialTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/CredentialTest.java index a5444441f31..4d6d8eebd11 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/CredentialTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/CredentialTest.java @@ -20,13 +20,13 @@ import java.util.HashSet; import java.util.Set; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link com.google.cloud.tools.jib.api.Credential}. */ -public class CredentialTest { +class CredentialTest { @Test - public void testCredentialsHash() { + void testCredentialsHash() { Credential credentialA1 = Credential.from("username", "password"); Credential credentialA2 = Credential.from("username", "password"); Credential credentialB1 = Credential.from("", ""); @@ -43,7 +43,7 @@ public void testCredentialsHash() { } @Test - public void testCredentialsOAuth2RefreshToken() { + void testCredentialsOAuth2RefreshToken() { Credential oauth2Credential = Credential.from("", "eyJhbGciOi...3gw"); Assert.assertTrue( "Credential should be an auth2 token when username is ", diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/DescriptorDigestTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/DescriptorDigestTest.java index ac55ceccc3a..f919e0c29de 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/DescriptorDigestTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/DescriptorDigestTest.java @@ -20,13 +20,13 @@ import java.util.HashMap; import java.util.Map; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link DescriptorDigest}. */ -public class DescriptorDigestTest { +class DescriptorDigestTest { @Test - public void testCreateFromHash_pass() throws DigestException { + void testCreateFromHash_pass() throws DigestException { String goodHash = createGoodHash('a'); DescriptorDigest descriptorDigest = DescriptorDigest.fromHash(goodHash); @@ -36,7 +36,7 @@ public void testCreateFromHash_pass() throws DigestException { } @Test - public void testCreateFromHash_fail() { + void testCreateFromHash_fail() { String badHash = "not a valid hash"; try { @@ -48,7 +48,7 @@ public void testCreateFromHash_fail() { } @Test - public void testCreateFromHash_failIncorrectLength() { + void testCreateFromHash_failIncorrectLength() { String badHash = createGoodHash('a') + 'a'; try { @@ -60,7 +60,7 @@ public void testCreateFromHash_failIncorrectLength() { } @Test - public void testCreateFromDigest_pass() throws DigestException { + void testCreateFromDigest_pass() throws DigestException { String goodHash = createGoodHash('a'); String goodDigest = "sha256:" + createGoodHash('a'); @@ -71,7 +71,7 @@ public void testCreateFromDigest_pass() throws DigestException { } @Test - public void testCreateFromDigest_fail() { + void testCreateFromDigest_fail() { String badDigest = "sha256:not a valid digest"; try { @@ -83,7 +83,7 @@ public void testCreateFromDigest_fail() { } @Test - public void testUseAsMapKey() throws DigestException { + void testUseAsMapKey() throws DigestException { DescriptorDigest descriptorDigestA1 = DescriptorDigest.fromHash(createGoodHash('a')); DescriptorDigest descriptorDigestA2 = DescriptorDigest.fromHash(createGoodHash('a')); DescriptorDigest descriptorDigestA3 = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerClientResolverTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerClientResolverTest.java index 17c6dc6ad04..c49fd07b205 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerClientResolverTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerClientResolverTest.java @@ -22,13 +22,13 @@ import com.google.cloud.tools.jib.docker.DockerClientResolver; import java.util.Collections; import java.util.Optional; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link DockerClientResolver}. */ -public class DockerClientResolverTest { +class DockerClientResolverTest { @Test - public void testDockerClientIsReturned() { + void testDockerClientIsReturned() { Optional dockerClient = DockerClientResolver.resolve(Collections.singletonMap("test", "true")); assertThat(dockerClient.get()).isInstanceOf(AnotherDockerClient.class); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerDaemonImageTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerDaemonImageTest.java index 0ffd4dd0789..d24109b1b4c 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerDaemonImageTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/DockerDaemonImageTest.java @@ -20,13 +20,13 @@ import com.google.common.collect.ImmutableMap; import java.nio.file.Paths; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link DockerDaemonImage}. */ -public class DockerDaemonImageTest { +class DockerDaemonImageTest { @Test - public void testGetters_default() throws InvalidImageReferenceException { + void testGetters_default() throws InvalidImageReferenceException { DockerDaemonImage dockerDaemonImage = DockerDaemonImage.named("docker/daemon/image"); Assert.assertEquals("docker/daemon/image", dockerDaemonImage.getImageReference().toString()); @@ -36,7 +36,7 @@ public void testGetters_default() throws InvalidImageReferenceException { } @Test - public void testGetters() throws InvalidImageReferenceException { + void testGetters() throws InvalidImageReferenceException { DockerDaemonImage dockerDaemonImage = DockerDaemonImage.named("docker/daemon/image") .setDockerExecutable(Paths.get("docker/binary")) diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/ImageReferenceTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/ImageReferenceTest.java index 6a702458613..6403a03492c 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/ImageReferenceTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/ImageReferenceTest.java @@ -22,10 +22,10 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ImageReference}. */ -public class ImageReferenceTest { +class ImageReferenceTest { private static final List goodRegistries = Arrays.asList("some.domain---name.123.com:8080", "gcr.io", "localhost", null, ""); @@ -49,7 +49,7 @@ public class ImageReferenceTest { "domain.name:nonnumberport//:no-repository"); @Test - public void testParse_pass() throws InvalidImageReferenceException { + void testParse_pass() throws InvalidImageReferenceException { for (String goodRegistry : goodRegistries) { for (String goodRepository : goodRepositories) { for (String goodTag : goodTags) { @@ -62,7 +62,7 @@ public void testParse_pass() throws InvalidImageReferenceException { } @Test - public void testParse_dockerHub_official() throws InvalidImageReferenceException { + void testParse_dockerHub_official() throws InvalidImageReferenceException { String imageReferenceString = "busybox"; ImageReference imageReference = ImageReference.parse(imageReferenceString); @@ -72,7 +72,7 @@ public void testParse_dockerHub_official() throws InvalidImageReferenceException } @Test - public void testParse_dockerHub_user() throws InvalidImageReferenceException { + void testParse_dockerHub_user() throws InvalidImageReferenceException { String imageReferenceString = "someuser/someimage"; ImageReference imageReference = ImageReference.parse(imageReferenceString); @@ -82,7 +82,7 @@ public void testParse_dockerHub_user() throws InvalidImageReferenceException { } @Test - public void testParse_invalid() { + void testParse_invalid() { for (String badImageReference : badImageReferences) { try { ImageReference.parse(badImageReference); @@ -95,7 +95,7 @@ public void testParse_invalid() { } @Test - public void testOf_smoke() { + void testOf_smoke() { String expectedRegistry = "someregistry"; String expectedRepository = "somerepository"; String expectedTag = "sometag"; @@ -124,7 +124,7 @@ public void testOf_smoke() { } @Test - public void testToString() throws InvalidImageReferenceException { + void testToString() throws InvalidImageReferenceException { Assert.assertEquals("someimage", ImageReference.of(null, "someimage", null).toString()); Assert.assertEquals("someimage", ImageReference.of("", "someimage", "").toString()); Assert.assertEquals( @@ -151,7 +151,7 @@ public void testToString() throws InvalidImageReferenceException { } @Test - public void testToStringWithQualifier() { + void testToStringWithQualifier() { Assert.assertEquals( "someimage:latest", ImageReference.of(null, "someimage", null).toStringWithQualifier()); Assert.assertEquals( @@ -184,7 +184,7 @@ public void testToStringWithQualifier() { } @Test - public void testIsScratch() throws InvalidImageReferenceException { + void testIsScratch() throws InvalidImageReferenceException { Assert.assertTrue(ImageReference.parse("scratch").isScratch()); Assert.assertTrue(ImageReference.scratch().isScratch()); Assert.assertFalse(ImageReference.of("", "scratch", "").isScratch()); @@ -192,12 +192,12 @@ public void testIsScratch() throws InvalidImageReferenceException { } @Test - public void testToString_scratch() { + void testToString_scratch() { Assert.assertEquals("scratch", ImageReference.scratch().toString()); } @Test - public void testGetRegistry() { + void testGetRegistry() { Assert.assertEquals( "registry-1.docker.io", ImageReference.of(null, "someimage", null).getRegistry()); Assert.assertEquals( @@ -211,7 +211,7 @@ public void testGetRegistry() { } @Test - public void testEquality() throws InvalidImageReferenceException { + void testEquality() throws InvalidImageReferenceException { ImageReference image1 = ImageReference.parse("gcr.io/project/image:tag"); ImageReference image2 = ImageReference.parse("gcr.io/project/image:tag"); @@ -220,7 +220,7 @@ public void testEquality() throws InvalidImageReferenceException { } @Test - public void testEquality_differentRegistry() throws InvalidImageReferenceException { + void testEquality_differentRegistry() throws InvalidImageReferenceException { ImageReference image1 = ImageReference.parse("gcr.io/project/image:tag"); ImageReference image2 = ImageReference.parse("registry-1.docker.io/project/image:tag"); @@ -229,7 +229,7 @@ public void testEquality_differentRegistry() throws InvalidImageReferenceExcepti } @Test - public void testEquality_differentRepository() throws InvalidImageReferenceException { + void testEquality_differentRepository() throws InvalidImageReferenceException { ImageReference image1 = ImageReference.parse("gcr.io/project/image:tag"); ImageReference image2 = ImageReference.parse("gcr.io/project2/image:tag"); @@ -238,7 +238,7 @@ public void testEquality_differentRepository() throws InvalidImageReferenceExcep } @Test - public void testEquality_differentTag() throws InvalidImageReferenceException { + void testEquality_differentTag() throws InvalidImageReferenceException { ImageReference image1 = ImageReference.parse("gcr.io/project/image:tag1"); ImageReference image2 = ImageReference.parse("gcr.io/project/image:tag2"); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/JavaContainerBuilderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/JavaContainerBuilderTest.java index a75b6209ef6..c3e3c51636b 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/JavaContainerBuilderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/JavaContainerBuilderTest.java @@ -29,10 +29,10 @@ import java.util.List; import java.util.stream.Collectors; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link JavaContainerBuilder}. */ -public class JavaContainerBuilderTest { +class JavaContainerBuilderTest { /** Gets a resource file as a {@link Path}. */ private static Path getResource(String directory) throws URISyntaxException { @@ -54,7 +54,7 @@ private static List getExtractionPaths( } @Test - public void testToJibContainerBuilder_all() + void testToJibContainerBuilder_all() throws InvalidImageReferenceException, URISyntaxException, IOException, CacheDirectoryCreationException { BuildContext buildContext = @@ -136,7 +136,7 @@ public void testToJibContainerBuilder_all() } @Test - public void testToJibContainerBuilder_missingAndMultipleAdds() + void testToJibContainerBuilder_missingAndMultipleAdds() throws InvalidImageReferenceException, URISyntaxException, IOException, CacheDirectoryCreationException { BuildContext buildContext = @@ -187,7 +187,7 @@ public void testToJibContainerBuilder_missingAndMultipleAdds() } @Test - public void testToJibContainerBuilder_setAppRootLate() + void testToJibContainerBuilder_setAppRootLate() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { BuildContext buildContext = @@ -239,7 +239,7 @@ public void testToJibContainerBuilder_setAppRootLate() } @Test - public void testToJibContainerBuilder_mainClassNull() + void testToJibContainerBuilder_mainClassNull() throws IOException, InvalidImageReferenceException, CacheDirectoryCreationException, URISyntaxException { BuildContext buildContext = @@ -264,7 +264,7 @@ public void testToJibContainerBuilder_mainClassNull() } @Test - public void testToJibContainerBuilder_classpathEmpty() + void testToJibContainerBuilder_classpathEmpty() throws IOException, InvalidImageReferenceException { try { JavaContainerBuilder.from("scratch").setMainClass("Hello").toContainerBuilder(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTest.java index 74ed36bca16..772be1938ef 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerBuilderTest.java @@ -43,16 +43,19 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link JibContainerBuilder}. */ -@RunWith(MockitoJUnitRunner.class) -public class JibContainerBuilderTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JibContainerBuilderTest { @Spy private BuildContext.Builder spyBuildContextBuilder; @Mock private FileEntriesLayer mockLayerConfiguration1; @@ -62,7 +65,7 @@ public class JibContainerBuilderTest { @Mock private JibEvent mockJibEvent; @Test - public void testToBuildContext_containerConfigurationSet() + void testToBuildContext_containerConfigurationSet() throws InvalidImageReferenceException, CacheDirectoryCreationException { ImageConfiguration imageConfiguration = ImageConfiguration.builder(ImageReference.parse("base/image")).build(); @@ -99,7 +102,7 @@ public void testToBuildContext_containerConfigurationSet() } @Test - public void testToBuildContext_containerConfigurationAdd() + void testToBuildContext_containerConfigurationAdd() throws InvalidImageReferenceException, CacheDirectoryCreationException { ImageConfiguration imageConfiguration = ImageConfiguration.builder(ImageReference.parse("base/image")).build(); @@ -136,7 +139,7 @@ public void testToBuildContext_containerConfigurationAdd() } @Test - public void testToBuildContext() + void testToBuildContext() throws InvalidImageReferenceException, CredentialRetrievalException, CacheDirectoryCreationException { ExecutorService executorService = MoreExecutors.newDirectExecutorService(); @@ -223,7 +226,7 @@ public void testToBuildContext() } @Test - public void testToContainerBuildPlan_default() throws InvalidImageReferenceException { + void testToContainerBuildPlan_default() throws InvalidImageReferenceException { ImageConfiguration imageConfiguration = ImageConfiguration.builder(ImageReference.parse("base/image")).build(); JibContainerBuilder containerBuilder = @@ -246,7 +249,7 @@ public void testToContainerBuildPlan_default() throws InvalidImageReferenceExcep } @Test - public void testToContainerBuildPlan() throws InvalidImageReferenceException, IOException { + void testToContainerBuildPlan() throws InvalidImageReferenceException, IOException { ImageConfiguration imageConfiguration = ImageConfiguration.builder(ImageReference.parse("base/image")).build(); JibContainerBuilder containerBuilder = @@ -297,7 +300,7 @@ public void testToContainerBuildPlan() throws InvalidImageReferenceException, IO } @Test - public void setApplyContainerBuildPlan() + void setApplyContainerBuildPlan() throws InvalidImageReferenceException, CacheDirectoryCreationException { FileEntriesLayer layer = FileEntriesLayer.builder() diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerTest.java index cb0e4ec3a8a..63e752d7474 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/JibContainerTest.java @@ -25,14 +25,14 @@ import java.security.DigestException; import java.util.Set; import org.junit.Assert; -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.rules.TemporaryFolder; import org.mockito.Mockito; /** Tests for {@link JibContainer}. */ -public class JibContainerTest { +class JibContainerTest { @Rule public TemporaryFolder temporaryDirectory = new TemporaryFolder(); @@ -43,8 +43,8 @@ public class JibContainerTest { private Set tags1; private Set tags2; - @Before - public void setUp() throws DigestException, InvalidImageReferenceException { + @BeforeEach + void setUp() throws DigestException, InvalidImageReferenceException { targetImage1 = ImageReference.parse("gcr.io/project/image:tag"); targetImage2 = ImageReference.parse("gcr.io/project/image:tag2"); digest1 = @@ -58,7 +58,7 @@ public void setUp() throws DigestException, InvalidImageReferenceException { } @Test - public void testCreation() { + void testCreation() { JibContainer container = new JibContainer(targetImage1, digest1, digest2, tags1, true); Assert.assertEquals(targetImage1, container.getTargetImage()); @@ -69,7 +69,7 @@ public void testCreation() { } @Test - public void testEquality() { + void testEquality() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest2, tags1, true); JibContainer container2 = new JibContainer(targetImage1, digest1, digest2, tags1, true); @@ -78,7 +78,7 @@ public void testEquality() { } @Test - public void testEquality_differentTargetImage() { + void testEquality_differentTargetImage() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest2, tags1, true); JibContainer container2 = new JibContainer(targetImage2, digest1, digest2, tags1, true); @@ -87,7 +87,7 @@ public void testEquality_differentTargetImage() { } @Test - public void testEquality_differentImageDigest() { + void testEquality_differentImageDigest() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest2, tags1, true); JibContainer container2 = new JibContainer(targetImage1, digest2, digest2, tags1, true); @@ -96,7 +96,7 @@ public void testEquality_differentImageDigest() { } @Test - public void testEquality_differentImageId() { + void testEquality_differentImageId() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest1, tags1, true); JibContainer container2 = new JibContainer(targetImage1, digest1, digest2, tags1, true); @@ -105,7 +105,7 @@ public void testEquality_differentImageId() { } @Test - public void testEquality_differentTags() { + void testEquality_differentTags() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest1, tags1, true); JibContainer container2 = new JibContainer(targetImage1, digest1, digest1, tags2, true); @@ -114,7 +114,7 @@ public void testEquality_differentTags() { } @Test - public void testEquality_differentImagePushed() { + void testEquality_differentImagePushed() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest1, tags1, true); JibContainer container2 = new JibContainer(targetImage1, digest1, digest1, tags1, false); @@ -123,7 +123,7 @@ public void testEquality_differentImagePushed() { } @Test - public void testCreation_withBuildContextAndBuildResult() { + void testCreation_withBuildContextAndBuildResult() { BuildResult buildResult = Mockito.mock(BuildResult.class); BuildContext buildContext = Mockito.mock(BuildContext.class); ImageConfiguration mockTargetConfiguration = Mockito.mock(ImageConfiguration.class); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/MainClassFinderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/MainClassFinderTest.java index e787a4b6f44..3f7319f74c4 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/MainClassFinderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/MainClassFinderTest.java @@ -27,41 +27,44 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link MainClassFinder}. */ -@RunWith(MockitoJUnitRunner.class) -public class MainClassFinderTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MainClassFinderTest { @Mock private Consumer logEventConsumer; - @Test - public void testFindMainClass_simple() throws URISyntaxException, IOException { - Path rootDirectory = Paths.get(Resources.getResource("core/class-finder-tests/simple").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("HelloWorld")); - } - - @Test - public void testFindMainClass_subdirectories() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/subdirectories").toURI()); + @ParameterizedTest + @CsvSource({ + "core/class-finder-tests/simple, HelloWorld", + "core/class-finder-tests/subdirectories, multi.layered.HelloWorld", + "core/class-finder-tests/extension, main.MainClass", + "core/class-finder-tests/imported-methods, main.MainClass", + "core/class-finder-tests/external-classes, main.MainClass", + "core/class-finder-tests/inner-classes, HelloWorld$InnerClass", + "core/class-finder-tests/varargs, HelloWorld", + "core/class-finder-tests/synthetic, HelloWorldKt" + }) + void testFindMainClass(String path, String t) throws URISyntaxException, IOException { + Path rootDirectory = Paths.get(Resources.getResource(path).toURI()); MainClassFinder.Result mainClassFinderResult = MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), - CoreMatchers.containsString("multi.layered.HelloWorld")); + mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString(t)); } @Test - public void testFindMainClass_noClass() throws URISyntaxException, IOException { + void testFindMainClass_noClass() throws URISyntaxException, IOException { Path rootDirectory = Paths.get(Resources.getResource("core/class-finder-tests/no-main").toURI()); MainClassFinder.Result mainClassFinderResult = @@ -70,7 +73,7 @@ public void testFindMainClass_noClass() throws URISyntaxException, IOException { } @Test - public void testFindMainClass_multiple() throws URISyntaxException, IOException { + void testFindMainClass_multiple() throws URISyntaxException, IOException { Path rootDirectory = Paths.get(Resources.getResource("core/class-finder-tests/multiple").toURI()); MainClassFinder.Result mainClassFinderResult = @@ -81,72 +84,4 @@ public void testFindMainClass_multiple() throws URISyntaxException, IOException mainClassFinderResult.getFoundMainClasses().contains("multi.layered.HelloMoon")); Assert.assertTrue(mainClassFinderResult.getFoundMainClasses().contains("HelloWorld")); } - - @Test - public void testFindMainClass_extension() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/extension").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("main.MainClass")); - } - - @Test - public void testFindMainClass_importedMethods() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/imported-methods").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("main.MainClass")); - } - - @Test - public void testFindMainClass_externalClasses() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/external-classes").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("main.MainClass")); - } - - @Test - public void testFindMainClass_innerClasses() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/inner-classes").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), - CoreMatchers.containsString("HelloWorld$InnerClass")); - } - - @Test - public void testMainClass_varargs() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/varargs").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame(Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("HelloWorld")); - } - - @Test - public void testMainClass_synthetic() throws URISyntaxException, IOException { - Path rootDirectory = - Paths.get(Resources.getResource("core/class-finder-tests/synthetic").toURI()); - MainClassFinder.Result mainClassFinderResult = - MainClassFinder.find(new DirectoryWalker(rootDirectory).walk(), logEventConsumer); - Assert.assertSame( - MainClassFinder.Result.Type.MAIN_CLASS_FOUND, mainClassFinderResult.getType()); - MatcherAssert.assertThat( - mainClassFinderResult.getFoundMainClass(), CoreMatchers.containsString("HelloWorldKt")); - } } diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/PortsTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/PortsTest.java index 725ab27fb91..2227ccf4473 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/PortsTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/PortsTest.java @@ -23,13 +23,13 @@ import java.util.List; import java.util.Set; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Ports}. */ -public class PortsTest { +class PortsTest { @Test - public void testParse() { + void testParse() { List goodInputs = Arrays.asList("1000", "2000-2003", "3000-3000", "4000/tcp", "5000/udp", "6000-6002/udp"); ImmutableSet expected = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/RegistryImageTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/RegistryImageTest.java index 98c894c2d21..21d637ec448 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/RegistryImageTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/RegistryImageTest.java @@ -18,19 +18,22 @@ import com.google.cloud.tools.jib.registry.credentials.CredentialRetrievalException; import org.junit.Assert; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link RegistryImage}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegistryImageTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class RegistryImageTest { @Mock private CredentialRetriever mockCredentialRetriever; @Test - public void testGetters_default() throws InvalidImageReferenceException { + void testGetters_default() throws InvalidImageReferenceException { RegistryImage image = RegistryImage.named("registry/image"); Assert.assertEquals("registry/image", image.getImageReference().toString()); @@ -38,7 +41,7 @@ public void testGetters_default() throws InvalidImageReferenceException { } @Test - public void testGetters() + void testGetters() throws InvalidImageReferenceException, AssertionError, CredentialRetrievalException { RegistryImage image = RegistryImage.named("registry/image") diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/api/TarImageTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/api/TarImageTest.java index 834ee603168..508317e4aa4 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/api/TarImageTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/api/TarImageTest.java @@ -18,20 +18,20 @@ import java.nio.file.Paths; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link TarImage}. */ -public class TarImageTest { +class TarImageTest { @Test - public void testGetters_bothSet() throws InvalidImageReferenceException { + void testGetters_bothSet() throws InvalidImageReferenceException { TarImage tarImage = TarImage.at(Paths.get("output/file")).named("tar/image"); Assert.assertEquals("tar/image", tarImage.getImageReference().get().toString()); Assert.assertEquals(Paths.get("output/file"), tarImage.getPath()); } @Test - public void testGetters_nameMissing() { + void testGetters_nameMissing() { TarImage tarImage = TarImage.at(Paths.get("output/file")); Assert.assertFalse(tarImage.getImageReference().isPresent()); Assert.assertEquals(Paths.get("output/file"), tarImage.getPath()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/blob/BlobTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/blob/BlobTest.java index 5098214fe9a..4396d8f6cb2 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/blob/BlobTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/blob/BlobTest.java @@ -31,33 +31,33 @@ import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Blob}. */ -public class BlobTest { +class BlobTest { @Test - public void testFromInputStream() throws IOException { + void testFromInputStream() throws IOException { String expected = "crepecake"; InputStream inputStream = new ByteArrayInputStream(expected.getBytes(StandardCharsets.UTF_8)); verifyBlobWriteTo(expected, Blobs.from(inputStream)); } @Test - public void testFromFile() throws IOException, URISyntaxException { + void testFromFile() throws IOException, URISyntaxException { Path fileA = Paths.get(Resources.getResource("core/fileA").toURI()); String expected = new String(Files.readAllBytes(fileA), StandardCharsets.UTF_8); verifyBlobWriteTo(expected, Blobs.from(fileA)); } @Test - public void testFromString() throws IOException { + void testFromString() throws IOException { String expected = "crepecake"; verifyBlobWriteTo(expected, Blobs.from(expected)); } @Test - public void testFromWritableContents() throws IOException { + void testFromWritableContents() throws IOException { String expected = "crepecake"; WritableContents writableContents = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/ProgressEventDispatcherTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/ProgressEventDispatcherTest.java index 18faf049d46..6c0309e1b7b 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/ProgressEventDispatcherTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/ProgressEventDispatcherTest.java @@ -20,21 +20,24 @@ import com.google.cloud.tools.jib.event.events.ProgressEvent; import java.util.List; import org.junit.Assert; -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.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ProgressEventDispatcher}. */ -@RunWith(MockitoJUnitRunner.class) -public class ProgressEventDispatcherTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ProgressEventDispatcherTest { @Mock private EventHandlers mockEventHandlers; @Test - public void testDispatch() { + void testDispatch() { try (ProgressEventDispatcher progressEventDispatcher = ProgressEventDispatcher.newRoot(mockEventHandlers, "ignored", 10); ProgressEventDispatcher ignored = @@ -58,7 +61,7 @@ public void testDispatch() { } @Test - public void testDispatch_safeWithtooMuchProgress() { + void testDispatch_safeWithtooMuchProgress() { try (ProgressEventDispatcher progressEventDispatcher = ProgressEventDispatcher.newRoot(mockEventHandlers, "allocation description", 10)) { progressEventDispatcher.dispatchProgress(6); @@ -83,7 +86,7 @@ public void testDispatch_safeWithtooMuchProgress() { } @Test - public void testDispatch_safeWithTooManyChildren() { + void testDispatch_safeWithTooManyChildren() { try (ProgressEventDispatcher progressEventDispatcher = ProgressEventDispatcher.newRoot(mockEventHandlers, "allocation description", 1); ProgressEventDispatcher ignored1 = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerEventDispatcherTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerEventDispatcherTest.java index b19ec8eca3f..88819d48003 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerEventDispatcherTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerEventDispatcherTest.java @@ -25,22 +25,25 @@ import java.util.ArrayDeque; import java.util.Deque; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link TimerEventDispatcher}. */ -@RunWith(MockitoJUnitRunner.class) -public class TimerEventDispatcherTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class TimerEventDispatcherTest { private final Deque timerEventQueue = new ArrayDeque<>(); @Mock private Clock mockClock; @Test - public void testLogging() { + void testLogging() { EventHandlers eventHandlers = EventHandlers.builder().add(TimerEvent.class, timerEventQueue::add).build(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerTest.java index 46afc78da86..110f8dfe867 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/TimerTest.java @@ -20,20 +20,23 @@ import java.time.Duration; import java.time.Instant; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link Timer}. */ -@RunWith(MockitoJUnitRunner.class) -public class TimerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class TimerTest { @Mock private Clock mockClock; @Test - public void testLap() { + void testLap() { Mockito.when(mockClock.instant()).thenReturn(Instant.EPOCH); Timer parentTimer = new Timer(mockClock, null); Mockito.when(mockClock.instant()).thenReturn(Instant.EPOCH.plusMillis(5)); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildAndCacheApplicationLayerStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildAndCacheApplicationLayerStepTest.java index df8ecf21529..271fd525475 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildAndCacheApplicationLayerStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildAndCacheApplicationLayerStepTest.java @@ -41,18 +41,20 @@ import java.util.List; import java.util.stream.Stream; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.io.TempDir; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BuildAndCacheApplicationLayerStep}. */ -@RunWith(MockitoJUnitRunner.class) -public class BuildAndCacheApplicationLayerStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildAndCacheApplicationLayerStepTest { // TODO: Consolidate with BuildStepsIntegrationTest. private static final AbsoluteUnixPath EXTRACTION_PATH_ROOT = @@ -82,7 +84,7 @@ private static void assertBlobsEqual(Blob expectedBlob, Blob blob) throws IOExce Assert.assertArrayEquals(Blobs.writeToByteArray(expectedBlob), Blobs.writeToByteArray(blob)); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock private BuildContext mockBuildContext; @@ -95,8 +97,8 @@ private static void assertBlobsEqual(Blob expectedBlob, Blob blob) throws IOExce private FileEntriesLayer fakeExtraFilesLayerConfiguration; private FileEntriesLayer emptyLayerConfiguration; - @Before - public void setUp() throws IOException, URISyntaxException, CacheDirectoryCreationException { + @BeforeEach + void setUp() throws IOException, URISyntaxException, CacheDirectoryCreationException { fakeDependenciesLayerConfiguration = makeLayerConfiguration( "core/application/dependencies", EXTRACTION_PATH_ROOT.resolve("libs")); @@ -119,7 +121,7 @@ public void setUp() throws IOException, URISyntaxException, CacheDirectoryCreati .build(); emptyLayerConfiguration = FileEntriesLayer.builder().build(); - cache = Cache.withDirectory(temporaryFolder.newFolder().toPath()); + cache = Cache.withDirectory(Files.createTempDirectory(temporaryFolder, "jib")); Mockito.when(mockBuildContext.getEventHandlers()).thenReturn(EventHandlers.NONE); Mockito.when(mockBuildContext.getApplicationLayersCache()).thenReturn(cache); @@ -143,8 +145,7 @@ private List buildFakeLayersToCache() } @Test - public void testRun() - throws LayerPropertyNotFoundException, IOException, CacheCorruptedException { + void testRun() throws LayerPropertyNotFoundException, IOException, CacheCorruptedException { ImmutableList fakeLayerConfigurations = ImmutableList.of( fakeDependenciesLayerConfiguration, @@ -204,7 +205,7 @@ public void testRun() } @Test - public void testRun_emptyLayersIgnored() throws IOException, CacheCorruptedException { + void testRun_emptyLayersIgnored() throws IOException, CacheCorruptedException { ImmutableList fakeLayerConfigurations = ImmutableList.of( fakeDependenciesLayerConfiguration, diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildImageStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildImageStepTest.java index b996946a0a5..bb694552153 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildImageStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildImageStepTest.java @@ -38,16 +38,19 @@ import java.util.Arrays; import java.util.List; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BuildImageStep}. */ -@RunWith(MockitoJUnitRunner.class) -public class BuildImageStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildImageStepTest { @Mock private ProgressEventDispatcher.Factory mockProgressEventDispatcherFactory; @Mock private BuildContext mockBuildContext; @@ -62,8 +65,8 @@ public class BuildImageStepTest { private HistoryEntry nonEmptyLayerHistory; private HistoryEntry emptyLayerHistory; - @Before - public void setUp() throws DigestException { + @BeforeEach + void setUp() throws DigestException { testDescriptorDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -135,7 +138,7 @@ public void setUp() throws DigestException { } @Test - public void test_basicCase() { + void test_basicCase() { Image image = new BuildImageStep( mockBuildContext, @@ -150,7 +153,7 @@ public void test_basicCase() { } @Test - public void test_propagateBaseImageConfiguration() { + void test_propagateBaseImageConfiguration() { Mockito.when(mockContainerConfiguration.getEnvironmentMap()) .thenReturn(ImmutableMap.of("MY_ENV", "MY_ENV_VALUE", "BASE_ENV_2", "NEW_VALUE")); Mockito.when(mockContainerConfiguration.getLabels()) @@ -216,7 +219,7 @@ public void test_propagateBaseImageConfiguration() { } @Test - public void testOverrideWorkingDirectory() { + void testOverrideWorkingDirectory() { Mockito.when(mockContainerConfiguration.getWorkingDirectory()) .thenReturn(AbsoluteUnixPath.get("/my/directory")); @@ -233,7 +236,7 @@ public void testOverrideWorkingDirectory() { } @Test - public void test_inheritedUser() { + void test_inheritedUser() { Mockito.when(mockContainerConfiguration.getUser()).thenReturn(null); Image image = @@ -249,7 +252,7 @@ public void test_inheritedUser() { } @Test - public void test_inheritedEntrypoint() { + void test_inheritedEntrypoint() { Mockito.when(mockContainerConfiguration.getEntrypoint()).thenReturn(null); Mockito.when(mockContainerConfiguration.getProgramArguments()) .thenReturn(ImmutableList.of("test")); @@ -268,7 +271,7 @@ public void test_inheritedEntrypoint() { } @Test - public void test_inheritedEntrypointAndProgramArguments() { + void test_inheritedEntrypointAndProgramArguments() { Mockito.when(mockContainerConfiguration.getEntrypoint()).thenReturn(null); Mockito.when(mockContainerConfiguration.getProgramArguments()).thenReturn(null); @@ -286,7 +289,7 @@ public void test_inheritedEntrypointAndProgramArguments() { } @Test - public void test_notInheritedProgramArguments() { + void test_notInheritedProgramArguments() { Mockito.when(mockContainerConfiguration.getEntrypoint()) .thenReturn(ImmutableList.of("myEntrypoint")); Mockito.when(mockContainerConfiguration.getProgramArguments()).thenReturn(null); @@ -305,7 +308,7 @@ public void test_notInheritedProgramArguments() { } @Test - public void test_generateHistoryObjects() { + void test_generateHistoryObjects() { Image image = new BuildImageStep( mockBuildContext, @@ -372,7 +375,7 @@ public void test_generateHistoryObjects() { } @Test - public void testTruncateLongClasspath_shortClasspath() { + void testTruncateLongClasspath_shortClasspath() { ImmutableList entrypoint = ImmutableList.of( "java", "-Dmy-property=value", "-cp", "/app/classes:/app/libs/*", "com.example.Main"); @@ -383,7 +386,7 @@ public void testTruncateLongClasspath_shortClasspath() { } @Test - public void testTruncateLongClasspath_longClasspath() { + void testTruncateLongClasspath_longClasspath() { String classpath = "/app/resources:/app/classes:/app/libs/spring-boot-starter-web-2.0.3.RELEASE.jar:/app/libs/" + "shared-library-0.1.0.jar:/app/libs/spring-boot-starter-json-2.0.3.RELEASE.jar:/app/" diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildManifestListOrSingleManifestStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildManifestListOrSingleManifestStepTest.java index be8951005e5..3b128f5dbb1 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildManifestListOrSingleManifestStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildManifestListOrSingleManifestStepTest.java @@ -29,16 +29,19 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BuildManifestListOrSingleManifest}. */ -@RunWith(MockitoJUnitRunner.class) -public class BuildManifestListOrSingleManifestStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildManifestListOrSingleManifestStepTest { @Mock private ProgressEventDispatcher.Factory progressDispatcherFactory; @Mock private BuildContext buildContext; @@ -47,8 +50,8 @@ public class BuildManifestListOrSingleManifestStepTest { private Image image1; private Image image2; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(buildContext.getEventHandlers()).thenReturn(EventHandlers.NONE); Mockito.doReturn(V22ManifestTemplate.class).when(buildContext).getTargetFormat(); Mockito.when(layer.getBlobDescriptor()).thenReturn(new BlobDescriptor(0, null)); @@ -68,7 +71,7 @@ public void setUp() { } @Test - public void testCall_singleManifest() throws IOException { + void testCall_singleManifest() throws IOException { // Expected manifest JSON // { @@ -105,7 +108,7 @@ public void testCall_singleManifest() throws IOException { } @Test - public void testCall_manifestList() throws IOException { + void testCall_manifestList() throws IOException { // Expected Manifest List JSON // { @@ -150,7 +153,7 @@ public void testCall_manifestList() throws IOException { } @Test - public void testCall_emptyImagesList() throws IOException { + void testCall_emptyImagesList() throws IOException { try { new BuildManifestListOrSingleManifestStep( buildContext, progressDispatcherFactory, Collections.emptyList()) diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildResultTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildResultTest.java index 3c42d6e0910..81601d1d1ad 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildResultTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/BuildResultTest.java @@ -22,19 +22,19 @@ import java.io.IOException; import java.security.DigestException; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link BuildResult}. */ -public class BuildResultTest { +class BuildResultTest { private DescriptorDigest digest1; private DescriptorDigest digest2; private DescriptorDigest id; private DescriptorDigest id2; - @Before - public void setUp() throws DigestException { + @BeforeEach + void setUp() throws DigestException { digest1 = DescriptorDigest.fromDigest( "sha256:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"); @@ -51,7 +51,7 @@ public void setUp() throws DigestException { } @Test - public void testCreated() { + void testCreated() { BuildResult container = new BuildResult(digest1, id, true); Assert.assertEquals(digest1, container.getImageDigest()); Assert.assertEquals(id, container.getImageId()); @@ -59,7 +59,7 @@ public void testCreated() { } @Test - public void testEquality() { + void testEquality() { BuildResult container1 = new BuildResult(digest1, id, true); BuildResult container2 = new BuildResult(digest1, id, true); BuildResult container3 = new BuildResult(digest2, id, true); @@ -78,7 +78,7 @@ public void testEquality() { } @Test - public void testFromImage() throws IOException { + void testFromImage() throws IOException { Image image1 = Image.builder(V22ManifestTemplate.class).setUser("user").build(); Image image2 = Image.builder(V22ManifestTemplate.class).setUser("user").build(); Image image3 = Image.builder(V22ManifestTemplate.class).setUser("anotherUser").build(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/LocalBaseImageStepsTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/LocalBaseImageStepsTest.java index 97bd9f12179..e6ae7360ef1 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/LocalBaseImageStepsTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/LocalBaseImageStepsTest.java @@ -36,21 +36,24 @@ import java.nio.file.Paths; import java.security.DigestException; import java.util.Optional; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.Ignore; +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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -@RunWith(MockitoJUnitRunner.class) -public class LocalBaseImageStepsTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class LocalBaseImageStepsTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir static Path temporaryFolder; private final TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider(); @@ -65,12 +68,12 @@ private static Path getResource(String resource) throws URISyntaxException { return Paths.get(Resources.getResource(resource).toURI()); } - @Before - public void setup() throws IOException, CacheDirectoryCreationException { + @BeforeEach + void setup() throws IOException, CacheDirectoryCreationException { Mockito.when(buildContext.getExecutorService()) .thenReturn(MoreExecutors.newDirectExecutorService()); Mockito.when(buildContext.getBaseImageLayersCache()) - .thenReturn(Cache.withDirectory(temporaryFolder.newFolder().toPath())); + .thenReturn(Cache.withDirectory(temporaryFolder)); Mockito.when(buildContext.getEventHandlers()).thenReturn(eventHandlers); Mockito.when(progressEventDispatcherFactory.create(Mockito.anyString(), Mockito.anyLong())) .thenReturn(progressEventDispatcher); @@ -79,17 +82,18 @@ public void setup() throws IOException, CacheDirectoryCreationException { .thenReturn(childDispatcher); } - @After - public void tearDown() { + @AfterEach + void tearDownAfterAll() { + tempDirectoryProvider.close(); } @Test - public void testCacheDockerImageTar_validDocker() throws Exception { + void testCacheDockerImageTar_validDocker() throws Exception { Path dockerBuild = getResource("core/extraction/docker-save.tar"); LocalImage result = LocalBaseImageSteps.cacheDockerImageTar( - buildContext, dockerBuild, progressEventDispatcherFactory, tempDirectoryProvider); + buildContext, dockerBuild, progressEventDispatcherFactory, new TempDirectoryProvider()); Mockito.verify(progressEventDispatcher, Mockito.times(2)).newChildProducer(); Assert.assertEquals(2, result.layers.size()); @@ -109,7 +113,8 @@ public void testCacheDockerImageTar_validDocker() throws Exception { } @Test - public void testCacheDockerImageTar_validTar() throws Exception { + @Ignore("sonar - currently disabled") + void testCacheDockerImageTar_validTar() throws Exception { Path tarBuild = getResource("core/extraction/jib-image.tar"); LocalImage result = LocalBaseImageSteps.cacheDockerImageTar( @@ -133,7 +138,8 @@ public void testCacheDockerImageTar_validTar() throws Exception { } @Test - public void testGetCachedDockerImage() + @Ignore("sonar - currently disabled") + void testGetCachedDockerImage() throws IOException, DigestException, CacheDirectoryCreationException, CacheCorruptedException, URISyntaxException { String dockerInspectJson = @@ -144,7 +150,7 @@ public void testGetCachedDockerImage() + " \"sha256:f1ac3015bcbf0ada4750d728626eb10f0f585199e2b667dcd79e49f0e926178e\" ] } }"; ImageDetails dockerImageDetails = JsonTemplateMapper.readJson(dockerInspectJson, CliDockerClient.DockerImageDetails.class); - Path cachePath = temporaryFolder.newFolder("cache").toPath(); + Path cachePath = temporaryFolder; Files.createDirectories(cachePath.resolve("local/config")); Cache cache = Cache.withDirectory(cachePath); @@ -186,7 +192,8 @@ public void testGetCachedDockerImage() } @Test - public void testIsGzipped() throws URISyntaxException, IOException { + @Ignore("sonar - currently disabled") + void testIsGzipped() throws URISyntaxException, IOException { Assert.assertTrue( LocalBaseImageSteps.isGzipped(getResource("core/extraction/compressed.tar.gz"))); Assert.assertFalse( diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/ObtainBaseImageLayerStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/ObtainBaseImageLayerStepTest.java index 1eb560c1ded..994ac9ea4d8 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/ObtainBaseImageLayerStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/ObtainBaseImageLayerStepTest.java @@ -32,19 +32,22 @@ import java.util.Optional; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Before; -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.AdditionalAnswers; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer3; /** Tests for {@link ObtainBaseImageLayerStep}. */ -@RunWith(MockitoJUnitRunner.class) -public class ObtainBaseImageLayerStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ObtainBaseImageLayerStepTest { private DescriptorDigest existingLayerDigest; private DescriptorDigest freshLayerDigest; @@ -59,8 +62,8 @@ public class ObtainBaseImageLayerStepTest { @Mock(answer = Answers.RETURNS_MOCKS) private ProgressEventDispatcher.Factory progressDispatcherFactory; - @Before - public void setUp() throws IOException, RegistryException, DigestException { + @BeforeEach + void setUp() throws IOException, RegistryException, DigestException { existingLayerDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -87,7 +90,7 @@ public void setUp() throws IOException, RegistryException, DigestException { } @Test - public void testForSelectiveDownload_existingLayer() + void testForSelectiveDownload_existingLayer() throws IOException, CacheCorruptedException, RegistryException { ObtainBaseImageLayerStep puller = ObtainBaseImageLayerStep.forSelectiveDownload( @@ -105,7 +108,7 @@ public void testForSelectiveDownload_existingLayer() } @Test - public void testForSelectiveDownload_freshLayer() + void testForSelectiveDownload_freshLayer() throws IOException, CacheCorruptedException, RegistryException { ObtainBaseImageLayerStep puller = ObtainBaseImageLayerStep.forSelectiveDownload( @@ -123,7 +126,7 @@ public void testForSelectiveDownload_freshLayer() } @Test - public void testForForcedDownload_existingLayer() + void testForForcedDownload_existingLayer() throws IOException, CacheCorruptedException, RegistryException { ObtainBaseImageLayerStep puller = ObtainBaseImageLayerStep.forForcedDownload( @@ -141,7 +144,7 @@ public void testForForcedDownload_existingLayer() } @Test - public void testForForcedDownload_freshLayer() + void testForForcedDownload_freshLayer() throws IOException, CacheCorruptedException, RegistryException { ObtainBaseImageLayerStep puller = ObtainBaseImageLayerStep.forForcedDownload( @@ -159,8 +162,7 @@ public void testForForcedDownload_freshLayer() } @Test - public void testLayerMissingInCacheInOfflineMode() - throws CacheCorruptedException, RegistryException { + void testLayerMissingInCacheInOfflineMode() throws CacheCorruptedException, RegistryException { Mockito.when(buildContext.isOffline()).thenReturn(true); ObtainBaseImageLayerStep puller = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PlatformCheckerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PlatformCheckerTest.java index d6bcb38475e..c784fefc143 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PlatformCheckerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PlatformCheckerTest.java @@ -29,29 +29,32 @@ import com.google.common.collect.ImmutableSet; import java.nio.file.Path; import java.nio.file.Paths; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link PlatformChecker}. */ -@RunWith(MockitoJUnitRunner.class) -public class PlatformCheckerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class PlatformCheckerTest { @Mock private BuildContext buildContext; @Mock private ContainerConfiguration containerConfig; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(buildContext.getBaseImageConfiguration()) .thenReturn(ImageConfiguration.builder(ImageReference.scratch()).build()); Mockito.when(buildContext.getContainerConfiguration()).thenReturn(containerConfig); } @Test - public void testCheckManifestPlatform_mismatch() { + void testCheckManifestPlatform_mismatch() { Mockito.when(containerConfig.getPlatforms()) .thenReturn(ImmutableSet.of(new Platform("configured arch", "configured OS"))); @@ -70,7 +73,7 @@ public void testCheckManifestPlatform_mismatch() { } @Test - public void testCheckManifestPlatform_noExceptionIfDefaultAmd64Linux() + void testCheckManifestPlatform_noExceptionIfDefaultAmd64Linux() throws PlatformNotFoundInBaseImageException { Mockito.when(containerConfig.getPlatforms()) .thenReturn(ImmutableSet.of(new Platform("amd64", "linux"))); @@ -82,7 +85,7 @@ public void testCheckManifestPlatform_noExceptionIfDefaultAmd64Linux() } @Test - public void testCheckManifestPlatform_multiplePlatformsConfigured() { + void testCheckManifestPlatform_multiplePlatformsConfigured() { Mockito.when(containerConfig.getPlatforms()) .thenReturn(ImmutableSet.of(new Platform("amd64", "linux"), new Platform("arch", "os"))); Exception ex = @@ -98,7 +101,7 @@ public void testCheckManifestPlatform_multiplePlatformsConfigured() { } @Test - public void testCheckManifestPlatform_tarBaseImage() { + void testCheckManifestPlatform_tarBaseImage() { Path tar = Paths.get("/foo/bar.tar"); Mockito.when(buildContext.getBaseImageConfiguration()) .thenReturn(ImageConfiguration.builder(ImageReference.scratch()).setTarPath(tar).build()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PullBaseImageStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PullBaseImageStepTest.java index f3f5005a804..fadb9ec7fe3 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PullBaseImageStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PullBaseImageStepTest.java @@ -63,17 +63,21 @@ import java.util.Optional; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link PullBaseImageStep}. */ -@RunWith(MockitoJUnitRunner.class) -public class PullBaseImageStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class PullBaseImageStepTest { @Mock private ProgressEventDispatcher.Factory progressDispatcherFactory; @Mock private ProgressEventDispatcher progressDispatcher; @@ -87,8 +91,8 @@ public class PullBaseImageStepTest { private PullBaseImageStep pullBaseImageStep; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(buildContext.getBaseImageConfiguration()).thenReturn(imageConfiguration); Mockito.when(buildContext.getEventHandlers()).thenReturn(eventHandlers); Mockito.when(buildContext.getBaseImageLayersCache()).thenReturn(cache); @@ -106,7 +110,7 @@ public void setUp() { } @Test - public void testCall_scratch_singlePlatform() + void testCall_scratch_singlePlatform() throws LayerPropertyNotFoundException, IOException, RegistryException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { @@ -120,7 +124,7 @@ public void testCall_scratch_singlePlatform() } @Test - public void testCall_scratch_multiplePlatforms() + void testCall_scratch_multiplePlatforms() throws LayerPropertyNotFoundException, IOException, RegistryException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { @@ -140,7 +144,7 @@ public void testCall_scratch_multiplePlatforms() } @Test - public void testCall_digestBaseImage() + void testCall_digestBaseImage() throws LayerPropertyNotFoundException, IOException, RegistryException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException, InvalidImageReferenceException { @@ -167,7 +171,7 @@ public void testCall_digestBaseImage() } @Test - public void testCall_offlineMode_notCached() + void testCall_offlineMode_notCached() throws LayerPropertyNotFoundException, RegistryException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException, InvalidImageReferenceException { @@ -184,7 +188,7 @@ public void testCall_offlineMode_notCached() } @Test - public void testCall_offlineMode_cached() + void testCall_offlineMode_cached() throws LayerPropertyNotFoundException, RegistryException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException, InvalidImageReferenceException, IOException { @@ -211,7 +215,7 @@ public void testCall_offlineMode_cached() } @Test - public void testLookUpPlatformSpecificDockerImageManifest() + void testLookUpPlatformSpecificDockerImageManifest() throws IOException, UnlistedPlatformInManifestListException { String manifestListJson = " {\n" @@ -251,7 +255,7 @@ public void testLookUpPlatformSpecificDockerImageManifest() } @Test - public void testLookUpPlatformSpecificOciManifest() + void testLookUpPlatformSpecificOciManifest() throws IOException, UnlistedPlatformInManifestListException { String manifestListJson = " {\n" @@ -291,7 +295,7 @@ public void testLookUpPlatformSpecificOciManifest() } @Test - public void testGetCachedBaseImages_emptyCache() + void testGetCachedBaseImages_emptyCache() throws InvalidImageReferenceException, IOException, CacheCorruptedException, UnlistedPlatformInManifestListException, PlatformNotFoundInBaseImageException, BadContainerConfigurationFormatException, LayerCountMismatchException { @@ -304,7 +308,7 @@ public void testGetCachedBaseImages_emptyCache() } @Test - public void testGetCachedBaseImages_partiallyCached_emptyListReturned() + void testGetCachedBaseImages_partiallyCached_emptyListReturned() throws InvalidImageReferenceException, CacheCorruptedException, IOException, LayerCountMismatchException, PlatformNotFoundInBaseImageException, BadContainerConfigurationFormatException, UnlistedPlatformInManifestListException { @@ -322,7 +326,7 @@ public void testGetCachedBaseImages_partiallyCached_emptyListReturned() } @Test - public void testGetCachedBaseImages_v21ManifestCached() + void testGetCachedBaseImages_v21ManifestCached() throws InvalidImageReferenceException, IOException, CacheCorruptedException, UnlistedPlatformInManifestListException, BadContainerConfigurationFormatException, LayerCountMismatchException, DigestException, PlatformNotFoundInBaseImageException { @@ -352,7 +356,7 @@ public void testGetCachedBaseImages_v21ManifestCached() } @Test - public void testGetCachedBaseImages_manifestCached() + void testGetCachedBaseImages_manifestCached() throws InvalidImageReferenceException, IOException, CacheCorruptedException, UnlistedPlatformInManifestListException, BadContainerConfigurationFormatException, LayerCountMismatchException, PlatformNotFoundInBaseImageException { @@ -379,7 +383,7 @@ public void testGetCachedBaseImages_manifestCached() } @Test - public void testGetCachedBaseImages_manifestListCached() + void testGetCachedBaseImages_manifestListCached() throws InvalidImageReferenceException, IOException, CacheCorruptedException, UnlistedPlatformInManifestListException, BadContainerConfigurationFormatException, LayerCountMismatchException, PlatformNotFoundInBaseImageException { @@ -429,7 +433,7 @@ public void testGetCachedBaseImages_manifestListCached() } @Test - public void testGetCachedBaseImages_manifestListCached_partialMatches() + void testGetCachedBaseImages_manifestListCached_partialMatches() throws InvalidImageReferenceException, IOException, CacheCorruptedException, UnlistedPlatformInManifestListException, BadContainerConfigurationFormatException, LayerCountMismatchException, PlatformNotFoundInBaseImageException { @@ -463,7 +467,7 @@ public void testGetCachedBaseImages_manifestListCached_partialMatches() } @Test - public void testGetCachedBaseImages_manifestListCached_onlyPlatforms() + void testGetCachedBaseImages_manifestListCached_onlyPlatforms() throws InvalidImageReferenceException, IOException, CacheCorruptedException, UnlistedPlatformInManifestListException, PlatformNotFoundInBaseImageException, BadContainerConfigurationFormatException, LayerCountMismatchException { @@ -507,7 +511,7 @@ public void testGetCachedBaseImages_manifestListCached_onlyPlatforms() } @Test - public void testTryMirrors_noMatchingMirrors() + void testTryMirrors_noMatchingMirrors() throws LayerCountMismatchException, BadContainerConfigurationFormatException, PlatformNotFoundInBaseImageException { Mockito.when(imageConfiguration.getImageRegistry()).thenReturn("registry"); @@ -525,7 +529,7 @@ public void testTryMirrors_noMatchingMirrors() } @Test - public void testTryMirrors_mirrorIoError() + void testTryMirrors_mirrorIoError() throws LayerCountMismatchException, BadContainerConfigurationFormatException, IOException, RegistryException { Mockito.when(imageConfiguration.getImageRegistry()).thenReturn("registry"); @@ -550,7 +554,7 @@ public void testTryMirrors_mirrorIoError() } @Test - public void testTryMirrors_multipleMirrors() + void testTryMirrors_multipleMirrors() throws LayerCountMismatchException, BadContainerConfigurationFormatException, IOException, RegistryException, InvalidImageReferenceException { Mockito.when(imageConfiguration.getImage()).thenReturn(ImageReference.parse("registry/repo")); @@ -589,7 +593,7 @@ public void testTryMirrors_multipleMirrors() } @Test - public void testCall_allMirrorsFail() + void testCall_allMirrorsFail() throws InvalidImageReferenceException, IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, @@ -629,7 +633,7 @@ public void testCall_allMirrorsFail() } @Test - public void testCall_ManifestList() + void testCall_ManifestList() throws InvalidImageReferenceException, IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, @@ -651,24 +655,28 @@ public void testCall_ManifestList() Assert.assertEquals("amd64", result.images.get(0).getArchitecture()); } - @Test(expected = UnlistedPlatformInManifestListException.class) - public void testCall_ManifestList_UnknownArchitecture() + @Test + void testCall_ManifestList_UnknownArchitecture() throws InvalidImageReferenceException, IOException, RegistryException, LayerPropertyNotFoundException, LayerCountMismatchException, BadContainerConfigurationFormatException, CacheCorruptedException, CredentialRetrievalException { - Mockito.when(buildContext.getBaseImageConfiguration()) - .thenReturn(ImageConfiguration.builder(ImageReference.parse("multiarch")).build()); - Mockito.when(buildContext.getRegistryMirrors()) - .thenReturn(ImmutableListMultimap.of("registry", "gcr.io")); - Mockito.when(containerConfig.getPlatforms()) - .thenReturn(ImmutableSet.of(new Platform("arm64", "linux"))); - RegistryClient.Factory dockerHubRegistryClientFactory = - setUpWorkingRegistryClientFactoryWithV22ManifestList(); - Mockito.when(buildContext.newBaseImageRegistryClientFactory()) - .thenReturn(dockerHubRegistryClientFactory); - - pullBaseImageStep.call(); + Assertions.assertThrows( + UnlistedPlatformInManifestListException.class, + () -> { + Mockito.when(buildContext.getBaseImageConfiguration()) + .thenReturn(ImageConfiguration.builder(ImageReference.parse("multiarch")).build()); + Mockito.when(buildContext.getRegistryMirrors()) + .thenReturn(ImmutableListMultimap.of("registry", "gcr.io")); + Mockito.when(containerConfig.getPlatforms()) + .thenReturn(ImmutableSet.of(new Platform("arm64", "linux"))); + RegistryClient.Factory dockerHubRegistryClientFactory = + setUpWorkingRegistryClientFactoryWithV22ManifestList(); + Mockito.when(buildContext.newBaseImageRegistryClientFactory()) + .thenReturn(dockerHubRegistryClientFactory); + + pullBaseImageStep.call(); + }); } private static RegistryClient.Factory setUpWorkingRegistryClientFactoryWithV22ManifestTemplate() diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushBlobStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushBlobStepTest.java index a1003783b6e..b8f24b7865f 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushBlobStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushBlobStepTest.java @@ -25,17 +25,20 @@ import com.google.cloud.tools.jib.registry.RegistryClient; import java.io.IOException; import java.util.Optional; -import org.junit.Before; -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.Answers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link PushBlobStep}. */ -@RunWith(MockitoJUnitRunner.class) -public class PushBlobStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class PushBlobStepTest { @Mock private BlobDescriptor blobDescriptor; @Mock private RegistryClient registryClient; @@ -46,14 +49,14 @@ public class PushBlobStepTest { @Mock(answer = Answers.RETURNS_MOCKS) private BuildContext buildContext; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(buildContext.getTargetImageConfiguration()) .thenReturn(ImageConfiguration.builder(ImageReference.scratch()).build()); } @Test - public void testCall_doBlobCheckAndBlobExists() throws IOException, RegistryException { + void testCall_doBlobCheckAndBlobExists() throws IOException, RegistryException { Mockito.when(registryClient.checkBlob(Mockito.any())).thenReturn(Optional.of(blobDescriptor)); call(false); @@ -64,7 +67,7 @@ public void testCall_doBlobCheckAndBlobExists() throws IOException, RegistryExce } @Test - public void testCall_doBlobCheckAndBlobDoesNotExist() throws IOException, RegistryException { + void testCall_doBlobCheckAndBlobDoesNotExist() throws IOException, RegistryException { Mockito.when(registryClient.checkBlob(Mockito.any())).thenReturn(Optional.empty()); call(false); @@ -75,7 +78,7 @@ public void testCall_doBlobCheckAndBlobDoesNotExist() throws IOException, Regist } @Test - public void testCall_forcePushWithNoBlobCheck() throws IOException, RegistryException { + void testCall_forcePushWithNoBlobCheck() throws IOException, RegistryException { call(true); Mockito.verify(registryClient, Mockito.never()).checkBlob(Mockito.any()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushImageStepTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushImageStepTest.java index b06096938aa..2dd84919f07 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushImageStepTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/PushImageStepTest.java @@ -40,18 +40,21 @@ import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.util.List; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -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.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link PushImageStep}. */ -@RunWith(MockitoJUnitRunner.class) -public class PushImageStepTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class PushImageStepTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); @@ -64,8 +67,8 @@ public class PushImageStepTest { private final V22ManifestListTemplate manifestList = new V22ManifestListTemplate(); - @Before - public void setUp() { + @BeforeEach + void setUp() { when(buildContext.getAllTargetImageTags()).thenReturn(ImmutableSet.of("tag1", "tag2")); when(buildContext.getEventHandlers()).thenReturn(EventHandlers.NONE); when(buildContext.getContainerConfiguration()).thenReturn(containerConfig); @@ -83,7 +86,7 @@ public void setUp() { } @Test - public void testMakeListForManifestList() throws IOException, RegistryException { + void testMakeListForManifestList() throws IOException, RegistryException { List pushImageStepList = PushImageStep.makeListForManifestList( buildContext, progressDispatcherFactory, registryClient, manifestList, false); @@ -99,7 +102,7 @@ public void testMakeListForManifestList() throws IOException, RegistryException } @Test - public void testMakeList_multiPlatform_platformTags() throws IOException, RegistryException { + void testMakeList_multiPlatform_platformTags() throws IOException, RegistryException { Image image = Image.builder(V22ManifestTemplate.class).setArchitecture("wasm").build(); when(buildContext.getEnablePlatformTags()).thenReturn(true); @@ -124,7 +127,7 @@ public void testMakeList_multiPlatform_platformTags() throws IOException, Regist } @Test - public void testMakeList_multiPlatform_nonPlatformTags() throws IOException, RegistryException { + void testMakeList_multiPlatform_nonPlatformTags() throws IOException, RegistryException { Image image = Image.builder(V22ManifestTemplate.class).setArchitecture("wasm").build(); when(buildContext.getEnablePlatformTags()).thenReturn(false); @@ -147,7 +150,7 @@ public void testMakeList_multiPlatform_nonPlatformTags() throws IOException, Reg } @Test - public void testMakeListForManifestList_singlePlatform() throws IOException { + void testMakeListForManifestList_singlePlatform() throws IOException { when(containerConfig.getPlatforms()) .thenReturn(ImmutableSet.of(new Platform("amd64", "linux"))); @@ -158,7 +161,7 @@ public void testMakeListForManifestList_singlePlatform() throws IOException { } @Test - public void testMakeListForManifestList_manifestListAlreadyExists() throws IOException { + void testMakeListForManifestList_manifestListAlreadyExists() throws IOException { System.setProperty(JibSystemProperties.SKIP_EXISTING_IMAGES, "true"); List pushImageStepList = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/RegistryCredentialRetrieverTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/RegistryCredentialRetrieverTest.java index 567220f925b..f82f2a5fc65 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/RegistryCredentialRetrieverTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/RegistryCredentialRetrieverTest.java @@ -33,21 +33,23 @@ import java.util.List; import java.util.Optional; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link RegistryCredentialRetriever}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegistryCredentialRetrieverTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class RegistryCredentialRetrieverTest { @Mock private EventHandlers mockEventHandlers; @Test - public void testCall_retrieved() - throws CredentialRetrievalException, CacheDirectoryCreationException { + void testCall_retrieved() throws CredentialRetrievalException, CacheDirectoryCreationException { BuildContext buildContext = makeFakeBuildContext( Arrays.asList( @@ -66,7 +68,7 @@ public void testCall_retrieved() } @Test - public void testCall_none() throws CredentialRetrievalException, CacheDirectoryCreationException { + void testCall_none() throws CredentialRetrievalException, CacheDirectoryCreationException { BuildContext buildContext = makeFakeBuildContext( Arrays.asList(Optional::empty, Optional::empty), Collections.emptyList()); @@ -84,7 +86,7 @@ public void testCall_none() throws CredentialRetrievalException, CacheDirectoryC } @Test - public void testCall_exception() throws CacheDirectoryCreationException { + void testCall_exception() throws CacheDirectoryCreationException { CredentialRetrievalException credentialRetrievalException = Mockito.mock(CredentialRetrievalException.class); BuildContext buildContext = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/StepsRunnerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/StepsRunnerTest.java index e8a60de2d57..b6c943f9a7d 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/StepsRunnerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/builder/steps/StepsRunnerTest.java @@ -39,16 +39,19 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link StepsRunner}. */ -@RunWith(MockitoJUnitRunner.class) -public class StepsRunnerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class StepsRunnerTest { // ListeningExecutorService is annotated with @DoNotMock, so define a concrete class. private class MockListeningExecutorService extends ForwardingExecutorService @@ -86,8 +89,8 @@ protected ExecutorService delegate() { private StepsRunner stepsRunner; - @Before - public void setup() { + @BeforeEach + void setup() { stepsRunner = new StepsRunner(new MockListeningExecutorService(), buildContext); Mockito.when(progressDispatcherFactory.create(Mockito.anyString(), Mockito.anyLong())) @@ -95,7 +98,7 @@ public void setup() { } @Test - public void testObtainBaseImageLayers_skipObtainingDuplicateLayers() + void testObtainBaseImageLayers_skipObtainingDuplicateLayers() throws DigestException, InterruptedException, ExecutionException { Mockito.when(executorService.submit(Mockito.any(PullBaseImageStep.class))) .thenReturn(Futures.immediateFuture(new ImagesAndRegistryClient(null, null))); @@ -154,7 +157,7 @@ public void testObtainBaseImageLayers_skipObtainingDuplicateLayers() } @Test - public void testIsImagePushed_skipExistingEnabledAndManifestPresent() { + void testIsImagePushed_skipExistingEnabledAndManifestPresent() { Optional> manifestResult = Mockito.mock(Optional.class); Mockito.when(manifestResult.isPresent()).thenReturn(true); System.setProperty(JibSystemProperties.SKIP_EXISTING_IMAGES, "true"); @@ -163,7 +166,7 @@ public void testIsImagePushed_skipExistingEnabledAndManifestPresent() { } @Test - public void testIsImagePushed_skipExistingImageDisabledAndManifestPresent() { + void testIsImagePushed_skipExistingImageDisabledAndManifestPresent() { Optional> manifestResult = Mockito.mock(Optional.class); System.setProperty(JibSystemProperties.SKIP_EXISTING_IMAGES, "false"); @@ -171,7 +174,7 @@ public void testIsImagePushed_skipExistingImageDisabledAndManifestPresent() { } @Test - public void testIsImagePushed_skipExistingImageEnabledAndManifestNotPresent() { + void testIsImagePushed_skipExistingImageEnabledAndManifestNotPresent() { Optional> manifestResult = Mockito.mock(Optional.class); System.setProperty(JibSystemProperties.SKIP_EXISTING_IMAGES, "true"); Mockito.when(manifestResult.isPresent()).thenReturn(false); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageFilesTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageFilesTest.java index c81a80c8ef9..e863e9132b9 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageFilesTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageFilesTest.java @@ -25,16 +25,16 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link CacheStorageFiles}. */ -public class CacheStorageFilesTest { +class CacheStorageFilesTest { private static final CacheStorageFiles TEST_CACHE_STORAGE_FILES = new CacheStorageFiles(Paths.get("cache/directory")); @Test - public void testIsLayerFile() { + void testIsLayerFile() { Assert.assertTrue( CacheStorageFiles.isLayerFile( Paths.get("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))); @@ -45,7 +45,7 @@ public void testIsLayerFile() { } @Test - public void testGetDiffId() throws DigestException, CacheCorruptedException { + void testGetDiffId() throws DigestException, CacheCorruptedException { Assert.assertEquals( DescriptorDigest.fromHash( "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), @@ -62,7 +62,7 @@ public void testGetDiffId() throws DigestException, CacheCorruptedException { } @Test - public void testGetDiffId_corrupted() { + void testGetDiffId_corrupted() { try { TEST_CACHE_STORAGE_FILES.getDigestFromFilename(Paths.get("not long enough")); Assert.fail("Should have thrown CacheCorruptedException"); @@ -95,7 +95,7 @@ public void testGetDiffId_corrupted() { } @Test - public void testGetLayerFile() throws DigestException { + void testGetLayerFile() throws DigestException { DescriptorDigest layerDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -114,7 +114,7 @@ public void testGetLayerFile() throws DigestException { } @Test - public void testGetLayerFilename() throws DigestException { + void testGetLayerFilename() throws DigestException { DescriptorDigest diffId = DescriptorDigest.fromHash( "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); @@ -125,7 +125,7 @@ public void testGetLayerFilename() throws DigestException { } @Test - public void testGetSelectorFile() throws DigestException { + void testGetSelectorFile() throws DigestException { DescriptorDigest selector = DescriptorDigest.fromHash( "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"); @@ -140,13 +140,13 @@ public void testGetSelectorFile() throws DigestException { } @Test - public void testGetLayersDirectory() { + void testGetLayersDirectory() { Assert.assertEquals( Paths.get("cache", "directory", "layers"), TEST_CACHE_STORAGE_FILES.getLayersDirectory()); } @Test - public void testGetLayerDirectory() throws DigestException { + void testGetLayerDirectory() throws DigestException { DescriptorDigest layerDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -161,19 +161,19 @@ public void testGetLayerDirectory() throws DigestException { } @Test - public void testGetTemporaryDirectory() { + void testGetTemporaryDirectory() { Assert.assertEquals( Paths.get("cache/directory/tmp"), TEST_CACHE_STORAGE_FILES.getTemporaryDirectory()); } @Test - public void testGetImagesDirectory() { + void testGetImagesDirectory() { Assert.assertEquals( Paths.get("cache/directory/images"), TEST_CACHE_STORAGE_FILES.getImagesDirectory()); } @Test - public void testGetImageDirectory() throws InvalidImageReferenceException { + void testGetImageDirectory() throws InvalidImageReferenceException { Path imagesDirectory = Paths.get("cache", "directory", "images"); Assert.assertEquals(imagesDirectory, TEST_CACHE_STORAGE_FILES.getImagesDirectory()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageReaderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageReaderTest.java index 47f7ff696f4..b40b8516833 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageReaderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageReaderTest.java @@ -50,14 +50,13 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; /** Tests for {@link CacheStorageReader}. */ -public class CacheStorageReaderTest { +class CacheStorageReaderTest { private static void setupCachedMetadataV21(Path cacheDirectory) throws IOException, URISyntaxException { @@ -158,7 +157,7 @@ private static T loadJsonResource(String path, Class Paths.get(Resources.getResource(path).toURI()), jsonClass); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; private Path cacheDirectory; private DescriptorDigest layerDigest1; @@ -166,9 +165,9 @@ private static T loadJsonResource(String path, Class private CacheStorageFiles cacheStorageFiles; private CacheStorageReader cacheStorageReader; - @Before - public void setUp() throws DigestException, IOException { - cacheDirectory = temporaryFolder.newFolder().toPath(); + @BeforeEach + void setUp() throws DigestException, IOException { + cacheDirectory = Files.createTempDirectory(temporaryFolder, "jib"); cacheStorageFiles = new CacheStorageFiles(cacheDirectory); cacheStorageReader = new CacheStorageReader(cacheStorageFiles); layerDigest1 = @@ -180,7 +179,7 @@ public void setUp() throws DigestException, IOException { } @Test - public void testRetrieveMetadata_v21SingleManifest() + void testRetrieveMetadata_v21SingleManifest() throws IOException, URISyntaxException, CacheCorruptedException { setupCachedMetadataV21(cacheDirectory); @@ -203,7 +202,7 @@ public void testRetrieveMetadata_v21SingleManifest() } @Test - public void testRetrieveMetadata_v22SingleManifest() + void testRetrieveMetadata_v22SingleManifest() throws IOException, URISyntaxException, CacheCorruptedException { setupCachedMetadataV22(cacheDirectory); @@ -221,7 +220,7 @@ public void testRetrieveMetadata_v22SingleManifest() } @Test - public void testRetrieveMetadata_v22ManifestList() + void testRetrieveMetadata_v22ManifestList() throws IOException, URISyntaxException, CacheCorruptedException { setupCachedMetadataV22ManifestList(cacheDirectory); @@ -272,7 +271,7 @@ public void testRetrieveMetadata_v22ManifestList() } @Test - public void testRetrieveMetadata_ociSingleManifest() + void testRetrieveMetadata_ociSingleManifest() throws IOException, URISyntaxException, CacheCorruptedException { setupCachedMetadataOci(cacheDirectory); @@ -290,7 +289,7 @@ public void testRetrieveMetadata_ociSingleManifest() } @Test - public void testRetrieveMetadata_ociImageIndex() + void testRetrieveMetadata_ociImageIndex() throws IOException, URISyntaxException, CacheCorruptedException { setupCachedMetadataOciImageIndex(cacheDirectory); @@ -320,7 +319,7 @@ public void testRetrieveMetadata_ociImageIndex() } @Test - public void testRetrieveMetadata_containerConfiguration() + void testRetrieveMetadata_containerConfiguration() throws IOException, URISyntaxException, CacheCorruptedException { setupCachedMetadataV22(cacheDirectory); @@ -337,7 +336,7 @@ public void testRetrieveMetadata_containerConfiguration() } @Test - public void testRetrieve() throws IOException, CacheCorruptedException { + void testRetrieve() throws IOException, CacheCorruptedException { // Creates the test layer directory. DescriptorDigest layerDigest = layerDigest1; DescriptorDigest layerDiffId = layerDigest2; @@ -373,7 +372,7 @@ public void testRetrieve() throws IOException, CacheCorruptedException { } @Test - public void testRetrieveTarLayer() throws IOException, CacheCorruptedException { + void testRetrieveTarLayer() throws IOException, CacheCorruptedException { // Creates the test layer directory. Path localDirectory = cacheStorageFiles.getLocalDirectory(); DescriptorDigest layerDigest = layerDigest1; @@ -411,7 +410,7 @@ public void testRetrieveTarLayer() throws IOException, CacheCorruptedException { } @Test - public void testRetrieveLocalConfig() throws IOException, URISyntaxException, DigestException { + void testRetrieveLocalConfig() throws IOException, URISyntaxException, DigestException { Path configDirectory = cacheDirectory.resolve("local").resolve("config"); Files.createDirectories(configDirectory); Files.copy( @@ -436,7 +435,7 @@ public void testRetrieveLocalConfig() throws IOException, URISyntaxException, Di } @Test - public void testSelect_invalidLayerDigest() throws IOException { + void testSelect_invalidLayerDigest() throws IOException { DescriptorDigest selector = layerDigest1; Path selectorFile = cacheStorageFiles.getSelectorFile(selector); Files.createDirectories(selectorFile.getParent()); @@ -457,7 +456,7 @@ public void testSelect_invalidLayerDigest() throws IOException { } @Test - public void testSelect() throws IOException, CacheCorruptedException { + void testSelect() throws IOException, CacheCorruptedException { DescriptorDigest selector = layerDigest1; Path selectorFile = cacheStorageFiles.getSelectorFile(selector); Files.createDirectories(selectorFile.getParent()); @@ -469,7 +468,7 @@ public void testSelect() throws IOException, CacheCorruptedException { } @Test - public void testVerifyImageMetadata_manifestCacheEmpty() { + void testVerifyImageMetadata_manifestCacheEmpty() { ImageMetadataTemplate metadata = new ImageMetadataTemplate(null, Collections.emptyList()); try { CacheStorageReader.verifyImageMetadata(metadata, Paths.get("/cache/dir")); @@ -480,7 +479,7 @@ public void testVerifyImageMetadata_manifestCacheEmpty() { } @Test - public void testVerifyImageMetadata_manifestListMissing() { + void testVerifyImageMetadata_manifestListMissing() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V22ManifestListTemplate(), new ContainerConfigurationTemplate()); @@ -495,7 +494,7 @@ public void testVerifyImageMetadata_manifestListMissing() { } @Test - public void testVerifyImageMetadata_manifestsMissing() { + void testVerifyImageMetadata_manifestsMissing() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate(null, new ContainerConfigurationTemplate()); ImageMetadataTemplate metadata = @@ -509,7 +508,7 @@ public void testVerifyImageMetadata_manifestsMissing() { } @Test - public void testVerifyImageMetadata_schema1ManifestsCorrupted_manifestListExists() { + void testVerifyImageMetadata_schema1ManifestsCorrupted_manifestListExists() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate(new V21ManifestTemplate(), null); ImageMetadataTemplate metadata = @@ -524,7 +523,7 @@ public void testVerifyImageMetadata_schema1ManifestsCorrupted_manifestListExists } @Test - public void testVerifyImageMetadata_schema1ManifestsCorrupted_containerConfigExists() { + void testVerifyImageMetadata_schema1ManifestsCorrupted_containerConfigExists() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V21ManifestTemplate(), new ContainerConfigurationTemplate()); @@ -540,7 +539,7 @@ public void testVerifyImageMetadata_schema1ManifestsCorrupted_containerConfigExi } @Test - public void testVerifyImageMetadata_schema2ManifestsCorrupted_nullContainerConfig() { + void testVerifyImageMetadata_schema2ManifestsCorrupted_nullContainerConfig() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate(new V22ManifestTemplate(), null, "sha256:digest"); ImageMetadataTemplate metadata = @@ -555,7 +554,7 @@ public void testVerifyImageMetadata_schema2ManifestsCorrupted_nullContainerConfi } @Test - public void testVerifyImageMetadata_schema2ManifestsCorrupted_nullManifestDigest() { + void testVerifyImageMetadata_schema2ManifestsCorrupted_nullManifestDigest() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V22ManifestTemplate(), new ContainerConfigurationTemplate(), null); @@ -571,7 +570,7 @@ public void testVerifyImageMetadata_schema2ManifestsCorrupted_nullManifestDigest } @Test - public void testVerifyImageMetadata_unknownManifestType() { + void testVerifyImageMetadata_unknownManifestType() { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( Mockito.mock(ManifestTemplate.class), new ContainerConfigurationTemplate()); @@ -586,7 +585,7 @@ public void testVerifyImageMetadata_unknownManifestType() { } @Test - public void testVerifyImageMetadata_validV21() throws CacheCorruptedException { + void testVerifyImageMetadata_validV21() throws CacheCorruptedException { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate(new V21ManifestTemplate(), null); ImageMetadataTemplate metadata = @@ -596,7 +595,7 @@ public void testVerifyImageMetadata_validV21() throws CacheCorruptedException { } @Test - public void testVerifyImageMetadata_validV22() throws CacheCorruptedException { + void testVerifyImageMetadata_validV22() throws CacheCorruptedException { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V22ManifestTemplate(), new ContainerConfigurationTemplate()); @@ -607,7 +606,7 @@ public void testVerifyImageMetadata_validV22() throws CacheCorruptedException { } @Test - public void testVerifyImageMetadata_validV22ManifestList() throws CacheCorruptedException { + void testVerifyImageMetadata_validV22ManifestList() throws CacheCorruptedException { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new V22ManifestTemplate(), new ContainerConfigurationTemplate(), "sha256:digest"); @@ -619,7 +618,7 @@ public void testVerifyImageMetadata_validV22ManifestList() throws CacheCorrupted } @Test - public void testVerifyImageMetadata_validOci() throws CacheCorruptedException { + void testVerifyImageMetadata_validOci() throws CacheCorruptedException { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new OciManifestTemplate(), new ContainerConfigurationTemplate(), "sha256:digest"); @@ -630,7 +629,7 @@ public void testVerifyImageMetadata_validOci() throws CacheCorruptedException { } @Test - public void testVerifyImageMetadata_validOciImageIndex() throws CacheCorruptedException { + void testVerifyImageMetadata_validOciImageIndex() throws CacheCorruptedException { ManifestAndConfigTemplate manifestAndConfig = new ManifestAndConfigTemplate( new OciManifestTemplate(), new ContainerConfigurationTemplate(), "sha256:digest"); @@ -642,7 +641,7 @@ public void testVerifyImageMetadata_validOciImageIndex() throws CacheCorruptedEx } @Test - public void testAllLayersCached_v21SingleManifest() + void testAllLayersCached_v21SingleManifest() throws IOException, CacheCorruptedException, DigestException, URISyntaxException { setupCachedMetadataV21(cacheDirectory); ImageMetadataTemplate metadata = @@ -664,7 +663,7 @@ public void testAllLayersCached_v21SingleManifest() } @Test - public void testAllLayersCached_v22SingleManifest() + void testAllLayersCached_v22SingleManifest() throws IOException, CacheCorruptedException, DigestException, URISyntaxException { setupCachedMetadataV22(cacheDirectory); ImageMetadataTemplate metadata = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageWriterTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageWriterTest.java index 63fa3e29e11..a5fa7619754 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageWriterTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheStorageWriterTest.java @@ -57,13 +57,13 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Tests for {@link CacheStorageWriter}. */ -public class CacheStorageWriterTest { +class CacheStorageWriterTest { private static BlobDescriptor getDigest(Blob blob) throws IOException { return blob.writeTo(ByteStreams.nullOutputStream()); @@ -110,21 +110,21 @@ private static T loadJsonResource(String path, Class Paths.get(Resources.getResource(path).toURI()), jsonClass); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; private CacheStorageFiles cacheStorageFiles; private CacheStorageWriter cacheStorageWriter; private Path cacheRoot; - @Before - public void setUp() throws IOException { - cacheRoot = temporaryFolder.newFolder().toPath(); + @BeforeEach + void setUp() throws IOException { + cacheRoot = Files.createTempDirectory(temporaryFolder, "jib"); cacheStorageFiles = new CacheStorageFiles(cacheRoot); cacheStorageWriter = new CacheStorageWriter(cacheStorageFiles); } @Test - public void testWriteCompressed() throws IOException { + void testWriteCompressed() throws IOException { Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); Blob compressedLayerBlob = compress(uncompressedLayerBlob); CachedLayer cachedLayer = cacheStorageWriter.writeCompressed(compressedLayerBlob); @@ -133,7 +133,7 @@ public void testWriteCompressed() throws IOException { } @Test - public void testWriteZstdCompressed() throws IOException { + void testWriteZstdCompressed() throws IOException { Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); Blob compressedLayerBlob = compress(uncompressedLayerBlob, CompressorStreamFactory.ZSTANDARD); @@ -142,15 +142,19 @@ public void testWriteZstdCompressed() throws IOException { verifyCachedLayer(cachedLayer, uncompressedLayerBlob, compressedLayerBlob); } - @Test(expected = IOException.class) - public void testWriteCompressWhenUncompressed() throws IOException { - Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); - // The detection of compression algorithm will fail - cacheStorageWriter.writeCompressed(uncompressedLayerBlob); + @Test + void testWriteCompressWhenUncompressed() throws IOException { + Assertions.assertThrows( + IOException.class, + () -> { + Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); + // The detection of compression algorithm will fail + cacheStorageWriter.writeCompressed(uncompressedLayerBlob); + }); } @Test - public void testWriteUncompressed() throws IOException { + void testWriteUncompressed() throws IOException { Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); DescriptorDigest layerDigest = getDigest(compress(uncompressedLayerBlob)).getDigest(); DescriptorDigest selector = getDigest(Blobs.from("selector")).getDigest(); @@ -166,7 +170,7 @@ public void testWriteUncompressed() throws IOException { } @Test - public void testWriteTarLayer() throws IOException { + void testWriteTarLayer() throws IOException { Blob uncompressedLayerBlob = Blobs.from("uncompressedLayerBlob"); DescriptorDigest diffId = getDigest(uncompressedLayerBlob).getDigest(); @@ -193,7 +197,7 @@ public void testWriteTarLayer() throws IOException { } @Test - public void testWriteMetadata_v21() + void testWriteMetadata_v21() throws IOException, URISyntaxException, InvalidImageReferenceException { V21ManifestTemplate v21Manifest = loadJsonResource("core/json/v21manifest.json", V21ManifestTemplate.class); @@ -222,7 +226,7 @@ public void testWriteMetadata_v21() } @Test - public void testWriteMetadata_v22() + void testWriteMetadata_v22() throws IOException, URISyntaxException, InvalidImageReferenceException { ContainerConfigurationTemplate containerConfig = loadJsonResource("core/json/containerconfig.json", ContainerConfigurationTemplate.class); @@ -305,7 +309,7 @@ public void testWriteMetadata_v22() } @Test - public void testWriteMetadata_oci() + void testWriteMetadata_oci() throws URISyntaxException, IOException, InvalidImageReferenceException { ContainerConfigurationTemplate containerConfig = loadJsonResource("core/json/containerconfig.json", ContainerConfigurationTemplate.class); @@ -359,7 +363,7 @@ public void testWriteMetadata_oci() } @Test - public void testWriteLocalConfig() throws IOException, URISyntaxException, DigestException { + void testWriteLocalConfig() throws IOException, URISyntaxException, DigestException { ContainerConfigurationTemplate containerConfigurationTemplate = loadJsonResource("core/json/containerconfig.json", ContainerConfigurationTemplate.class); @@ -380,7 +384,7 @@ public void testWriteLocalConfig() throws IOException, URISyntaxException, Diges } @Test - public void testMoveIfDoesNotExist_exceptionAfterFailure() { + void testMoveIfDoesNotExist_exceptionAfterFailure() { Exception exception = assertThrows( IOException.class, diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheTest.java index abf00f67a5a..89cad399c82 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CacheTest.java @@ -37,13 +37,12 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Tests for {@link Cache}. */ -public class CacheTest { +class CacheTest { /** * Gets a {@link Blob} that is {@code blob} compressed. Note that the output stream is closed when @@ -103,7 +102,7 @@ private static FileEntry defaultLayerEntry(Path source, AbsoluteUnixPath destina FileEntriesLayer.DEFAULT_MODIFICATION_TIME); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; private Blob layerBlob1; private DescriptorDigest layerDigest1; @@ -117,9 +116,9 @@ private static FileEntry defaultLayerEntry(Path source, AbsoluteUnixPath destina private long layerSize2; private ImmutableList layerEntries2; - @Before - public void setUp() throws IOException { - Path directory = temporaryFolder.newFolder().toPath(); + @BeforeEach + void setUp() throws IOException { + Path directory = Files.createTempDirectory(temporaryFolder, "jib"); Files.createDirectory(directory.resolve("source")); Files.createFile(directory.resolve("source/file")); Files.createDirectories(directory.resolve("another/source")); @@ -145,8 +144,8 @@ public void setUp() throws IOException { } @Test - public void testWithDirectory_existsButNotDirectory() throws IOException { - Path file = temporaryFolder.newFile().toPath(); + void testWithDirectory_existsButNotDirectory() throws IOException { + Path file = Files.createTempFile(temporaryFolder, "tmp", "jib"); try { Cache.withDirectory(file); @@ -159,9 +158,9 @@ public void testWithDirectory_existsButNotDirectory() throws IOException { } @Test - public void testWriteCompressed_retrieveByLayerDigest() + void testWriteCompressed_retrieveByLayerDigest() throws IOException, CacheDirectoryCreationException, CacheCorruptedException { - Cache cache = Cache.withDirectory(temporaryFolder.newFolder().toPath()); + Cache cache = Cache.withDirectory(Files.createTempDirectory(temporaryFolder, "jib")); verifyIsLayer1(cache.writeCompressedLayer(compress(layerBlob1))); verifyIsLayer1(cache.retrieve(layerDigest1).orElseThrow(AssertionError::new)); @@ -169,9 +168,9 @@ public void testWriteCompressed_retrieveByLayerDigest() } @Test - public void testWriteUncompressedWithLayerEntries_retrieveByLayerDigest() + void testWriteUncompressedWithLayerEntries_retrieveByLayerDigest() throws IOException, CacheDirectoryCreationException, CacheCorruptedException { - Cache cache = Cache.withDirectory(temporaryFolder.newFolder().toPath()); + Cache cache = Cache.withDirectory(Files.createTempDirectory(temporaryFolder, "jib")); verifyIsLayer1(cache.writeUncompressedLayer(layerBlob1, layerEntries1)); verifyIsLayer1(cache.retrieve(layerDigest1).orElseThrow(AssertionError::new)); @@ -179,9 +178,9 @@ public void testWriteUncompressedWithLayerEntries_retrieveByLayerDigest() } @Test - public void testWriteUncompressedWithLayerEntries_retrieveByLayerEntries() + void testWriteUncompressedWithLayerEntries_retrieveByLayerEntries() throws IOException, CacheDirectoryCreationException, CacheCorruptedException { - Cache cache = Cache.withDirectory(temporaryFolder.newFolder().toPath()); + Cache cache = Cache.withDirectory(Files.createTempDirectory(temporaryFolder, "jib")); verifyIsLayer1(cache.writeUncompressedLayer(layerBlob1, layerEntries1)); verifyIsLayer1(cache.retrieve(layerEntries1).orElseThrow(AssertionError::new)); @@ -194,9 +193,9 @@ public void testWriteUncompressedWithLayerEntries_retrieveByLayerEntries() } @Test - public void testRetrieveWithTwoEntriesInCache() + void testRetrieveWithTwoEntriesInCache() throws IOException, CacheDirectoryCreationException, CacheCorruptedException { - Cache cache = Cache.withDirectory(temporaryFolder.newFolder().toPath()); + Cache cache = Cache.withDirectory(Files.createTempDirectory(temporaryFolder, "jib")); verifyIsLayer1(cache.writeUncompressedLayer(layerBlob1, layerEntries1)); verifyIsLayer2(cache.writeUncompressedLayer(layerBlob2, layerEntries2)); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CachedLayerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CachedLayerTest.java index 16262f1fed8..e9115985368 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CachedLayerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/CachedLayerTest.java @@ -22,20 +22,23 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link CachedLayer}. */ -@RunWith(MockitoJUnitRunner.class) -public class CachedLayerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CachedLayerTest { @Mock private DescriptorDigest mockLayerDigest; @Mock private DescriptorDigest mockLayerDiffId; @Test - public void testBuilder_fail() { + void testBuilder_fail() { try { CachedLayer.builder().build(); Assert.fail("missing required"); @@ -62,7 +65,7 @@ public void testBuilder_fail() { } @Test - public void testBuilder_pass() throws IOException { + void testBuilder_pass() throws IOException { CachedLayer.Builder cachedLayerBuilder = CachedLayer.builder() .setLayerDigest(mockLayerDigest) diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/LayerEntriesSelectorTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/LayerEntriesSelectorTest.java index dbab5b386a1..bb69ad69ca9 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/LayerEntriesSelectorTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/LayerEntriesSelectorTest.java @@ -31,13 +31,12 @@ import java.nio.file.attribute.FileTime; import java.time.Instant; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Tests for {@link LayerEntriesSelector}. */ -public class LayerEntriesSelectorTest { +class LayerEntriesSelectorTest { private static FileEntry defaultLayerEntry(Path source, AbsoluteUnixPath destination) { return new FileEntry( @@ -47,7 +46,7 @@ private static FileEntry defaultLayerEntry(Path source, AbsoluteUnixPath destina FileEntriesLayer.DEFAULT_MODIFICATION_TIME); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; private ImmutableList outOfOrderLayerEntries; private ImmutableList inOrderLayerEntries; @@ -60,9 +59,9 @@ private static ImmutableList toLayerEntryTemplates( return builder.build(); } - @Before - public void setUp() throws IOException { - Path folder = temporaryFolder.newFolder().toPath(); + @BeforeEach + void setUp() throws IOException { + Path folder = Files.createTempDirectory(temporaryFolder, "jib"); Path file1 = Files.createDirectory(folder.resolve("files")); Path file2 = Files.createFile(folder.resolve("files").resolve("two")); Path file3 = Files.createFile(folder.resolve("gile")); @@ -103,28 +102,28 @@ public void setUp() throws IOException { } @Test - public void testLayerEntryTemplate_compareTo() throws IOException { + void testLayerEntryTemplate_compareTo() throws IOException { Assert.assertEquals( toLayerEntryTemplates(inOrderLayerEntries), ImmutableList.sortedCopyOf(toLayerEntryTemplates(outOfOrderLayerEntries))); } @Test - public void testToSortedJsonTemplates() throws IOException { + void testToSortedJsonTemplates() throws IOException { Assert.assertEquals( toLayerEntryTemplates(inOrderLayerEntries), LayerEntriesSelector.toSortedJsonTemplates(outOfOrderLayerEntries)); } @Test - public void testGenerateSelector_empty() throws IOException { + void testGenerateSelector_empty() throws IOException { DescriptorDigest expectedSelector = Digests.computeJsonDigest(ImmutableList.of()); Assert.assertEquals( expectedSelector, LayerEntriesSelector.generateSelector(ImmutableList.of())); } @Test - public void testGenerateSelector() throws IOException { + void testGenerateSelector() throws IOException { DescriptorDigest expectedSelector = Digests.computeJsonDigest(toLayerEntryTemplates(inOrderLayerEntries)); Assert.assertEquals( @@ -132,8 +131,8 @@ public void testGenerateSelector() throws IOException { } @Test - public void testGenerateSelector_sourceModificationTimeChanged() throws IOException { - Path layerFile = temporaryFolder.newFile().toPath(); + void testGenerateSelector_sourceModificationTimeChanged() throws IOException { + Path layerFile = Files.createTempFile(temporaryFolder, "jib", "test"); Files.setLastModifiedTime(layerFile, FileTime.from(Instant.EPOCH)); FileEntry layerEntry = defaultLayerEntry(layerFile, AbsoluteUnixPath.get("/extraction/path")); DescriptorDigest expectedSelector = @@ -151,8 +150,8 @@ public void testGenerateSelector_sourceModificationTimeChanged() throws IOExcept } @Test - public void testGenerateSelector_targetModificationTimeChanged() throws IOException { - Path layerFile = temporaryFolder.newFile().toPath(); + void testGenerateSelector_targetModificationTimeChanged() throws IOException { + Path layerFile = Files.createTempFile(temporaryFolder, "jib", "test"); AbsoluteUnixPath pathInContainer = AbsoluteUnixPath.get("/bar"); FilePermissions permissions = FilePermissions.fromOctalString("111"); @@ -166,8 +165,8 @@ public void testGenerateSelector_targetModificationTimeChanged() throws IOExcept } @Test - public void testGenerateSelector_permissionsModified() throws IOException { - Path layerFile = temporaryFolder.newFolder("testFolder").toPath().resolve("file"); + void testGenerateSelector_permissionsModified() throws IOException { + Path layerFile = Files.createTempDirectory(temporaryFolder, "testFolder").resolve("file"); Files.write(layerFile, "hello".getBytes(StandardCharsets.UTF_8)); FileEntry layerEntry111 = new FileEntry( @@ -189,8 +188,8 @@ public void testGenerateSelector_permissionsModified() throws IOException { } @Test - public void testGenerateSelector_ownersModified() throws IOException { - Path layerFile = temporaryFolder.newFolder("testFolder").toPath().resolve("file"); + void testGenerateSelector_ownersModified() throws IOException { + Path layerFile = Files.createTempDirectory(temporaryFolder, "testFolder").resolve("file"); Files.write(layerFile, "hello".getBytes(StandardCharsets.UTF_8)); FileEntry layerEntry111 = new FileEntry( diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/RetryTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/RetryTest.java index 6ea83e21f9f..07aca443ea7 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/cache/RetryTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/cache/RetryTest.java @@ -18,10 +18,10 @@ import java.util.concurrent.TimeUnit; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Retry}. */ -public class RetryTest { +class RetryTest { private int actionCount = 0; private boolean successfulAction() { @@ -40,28 +40,28 @@ private boolean exceptionAction() throws Exception { } @Test - public void testSuccessfulAction() throws Exception { + void testSuccessfulAction() throws Exception { boolean result = Retry.action(this::successfulAction).run(); Assert.assertTrue(result); Assert.assertEquals(1, actionCount); } @Test - public void testMaximumRetries_default() throws Exception { + void testMaximumRetries_default() throws Exception { boolean result = Retry.action(this::unsuccessfulAction).run(); Assert.assertFalse(result); Assert.assertEquals(5, actionCount); } @Test - public void testMaximumRetries_specified() throws Exception { + void testMaximumRetries_specified() throws Exception { boolean result = Retry.action(this::unsuccessfulAction).maximumRetries(2).run(); Assert.assertFalse(result); Assert.assertEquals(2, actionCount); } @Test - public void testRetryableException() { + void testRetryableException() { // all exceptions are retryable by default, so should retry 5 times try { Retry.action(this::exceptionAction).run(); @@ -73,7 +73,7 @@ public void testRetryableException() { } @Test - public void testNonRetryableException() { + void testNonRetryableException() { // the exception is not ok and so should only try 1 time try { Retry.action(this::exceptionAction).retryOnException(ex -> false).run(); @@ -85,7 +85,7 @@ public void testNonRetryableException() { } @Test - public void testInterruptSleep() throws Exception { + void testInterruptSleep() throws Exception { // interrupt the current thread so as to cause the retry's sleep() to throw // an InterruptedException Thread.currentThread().interrupt(); @@ -100,7 +100,7 @@ public void testInterruptSleep() throws Exception { } @Test - public void testInvalid_maximumRetries() { + void testInvalid_maximumRetries() { try { Retry.action(this::successfulAction).maximumRetries(0); Assert.fail(); @@ -110,7 +110,7 @@ public void testInvalid_maximumRetries() { } @Test - public void testInvalid_sleep() { + void testInvalid_sleep() { try { Retry.action(this::successfulAction).sleep(-1, TimeUnit.DAYS); Assert.fail(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/BuildContextTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/BuildContextTest.java index 4c052da1928..1edc83d8ff4 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/BuildContextTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/BuildContextTest.java @@ -49,15 +49,29 @@ import java.util.concurrent.ExecutorService; import org.junit.Assert; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; /** Tests for {@link BuildContext}. */ -public class BuildContextTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(SystemStubsExtension.class) +class BuildContextTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); + @SystemStub + @SuppressWarnings("unused") + private SystemProperties environmentVariables; + private static BuildContext.Builder createBasicTestBuilder() { return BuildContext.builder() .setBaseImageConfiguration( @@ -70,7 +84,7 @@ private static BuildContext.Builder createBasicTestBuilder() { } @Test - public void testBuilder() throws Exception { + void testBuilder() throws Exception { String expectedBaseImageServerUrl = "someserver"; String expectedBaseImageName = "baseimage"; String expectedBaseImageTag = "baseimagetag"; @@ -182,7 +196,7 @@ public void testBuilder() throws Exception { } @Test - public void testBuilder_default() throws CacheDirectoryCreationException { + void testBuilder_default() throws CacheDirectoryCreationException { // These are required and don't have defaults. String expectedBaseImageServerUrl = "someserver"; String expectedBaseImageName = "baseimage"; @@ -226,7 +240,7 @@ public void testBuilder_default() throws CacheDirectoryCreationException { } @Test - public void testBuilder_missingValues() throws CacheDirectoryCreationException { + void testBuilder_missingValues() throws CacheDirectoryCreationException { // Target image is missing try { BuildContext.builder() @@ -272,7 +286,7 @@ public void testBuilder_missingValues() throws CacheDirectoryCreationException { } @Test - public void testBuilder_digestWarning() + void testBuilder_digestWarning() throws CacheDirectoryCreationException, InvalidImageReferenceException { EventHandlers mockEventHandlers = Mockito.mock(EventHandlers.class); BuildContext.Builder builder = createBasicTestBuilder().setEventHandlers(mockEventHandlers); @@ -297,7 +311,7 @@ public void testBuilder_digestWarning() } @Test - public void testClose_shutDownInternalExecutorService() + void testClose_shutDownInternalExecutorService() throws IOException, CacheDirectoryCreationException { BuildContext buildContext = createBasicTestBuilder().build(); @@ -307,7 +321,7 @@ public void testClose_shutDownInternalExecutorService() } @Test - public void testClose_doNotShutDownProvidedExecutorService() + void testClose_doNotShutDownProvidedExecutorService() throws IOException, CacheDirectoryCreationException { ExecutorService executorService = MoreExecutors.newDirectExecutorService(); BuildContext buildContext = @@ -319,7 +333,7 @@ public void testClose_doNotShutDownProvidedExecutorService() } @Test - public void testGetUserAgent_unset() throws CacheDirectoryCreationException { + void testGetUserAgent_unset() throws CacheDirectoryCreationException { BuildContext buildContext = createBasicTestBuilder().build(); String generatedUserAgent = buildContext.makeUserAgent(); @@ -328,7 +342,7 @@ public void testGetUserAgent_unset() throws CacheDirectoryCreationException { } @Test - public void testGetUserAgent_withValues() throws CacheDirectoryCreationException { + void testGetUserAgent_withValues() throws CacheDirectoryCreationException { BuildContext buildContext = createBasicTestBuilder().setToolName("test-name").setToolVersion("test-version").build(); @@ -338,7 +352,7 @@ public void testGetUserAgent_withValues() throws CacheDirectoryCreationException } @Test - public void testGetUserAgentWithUpstreamClient() throws CacheDirectoryCreationException { + void testGetUserAgentWithUpstreamClient() throws CacheDirectoryCreationException { System.setProperty(JibSystemProperties.UPSTREAM_CLIENT, "skaffold/0.34.0"); BuildContext buildContext = createBasicTestBuilder().setToolName("test-name").setToolVersion("test-version").build(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/ContainerConfigurationTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/ContainerConfigurationTest.java index aeeb6ba49d4..212b038e464 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/ContainerConfigurationTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/ContainerConfigurationTest.java @@ -30,13 +30,13 @@ import java.util.Set; import java.util.TreeMap; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ContainerConfiguration}. */ -public class ContainerConfigurationTest { +class ContainerConfigurationTest { @Test - public void testBuilder_nullValues() { + void testBuilder_nullValues() { // Java arguments element should not be null. try { ContainerConfiguration.builder().setProgramArguments(Arrays.asList("first", null)); @@ -112,7 +112,7 @@ public void testBuilder_nullValues() { @Test @SuppressWarnings("JdkObsolete") // for hashtable - public void testBuilder_environmentMapTypes() { + void testBuilder_environmentMapTypes() { // Can accept empty environment. Assert.assertNotNull( ContainerConfiguration.builder().setEnvironment(ImmutableMap.of()).build()); @@ -122,20 +122,20 @@ public void testBuilder_environmentMapTypes() { } @Test - public void testBuilder_user() { + void testBuilder_user() { ContainerConfiguration configuration = ContainerConfiguration.builder().setUser("john").build(); Assert.assertEquals("john", configuration.getUser()); } @Test - public void testBuilder_workingDirectory() { + void testBuilder_workingDirectory() { ContainerConfiguration configuration = ContainerConfiguration.builder().setWorkingDirectory(AbsoluteUnixPath.get("/path")).build(); Assert.assertEquals(AbsoluteUnixPath.get("/path"), configuration.getWorkingDirectory()); } @Test - public void testSetPlatforms_emptySet() { + void testSetPlatforms_emptySet() { try { ContainerConfiguration.builder().setPlatforms(Collections.emptySet()).build(); Assert.fail(); @@ -145,7 +145,7 @@ public void testSetPlatforms_emptySet() { } @Test - public void testAddPlatform_duplicatePlatforms() { + void testAddPlatform_duplicatePlatforms() { ContainerConfiguration configuration = ContainerConfiguration.builder() .addPlatform("testArchitecture", "testOS") diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/DockerHealthCheckTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/DockerHealthCheckTest.java index 9d0a90d592c..144d063819e 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/DockerHealthCheckTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/configuration/DockerHealthCheckTest.java @@ -20,13 +20,13 @@ import java.time.Duration; import java.util.Arrays; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link DockerHealthCheck}. */ -public class DockerHealthCheckTest { +class DockerHealthCheckTest { @Test - public void testBuild() { + void testBuild() { DockerHealthCheck healthCheck = DockerHealthCheck.fromCommand(ImmutableList.of("echo", "hi")) .setInterval(Duration.ofNanos(123)) @@ -46,7 +46,7 @@ public void testBuild() { } @Test - public void testBuild_invalidCommand() { + void testBuild_invalidCommand() { try { DockerHealthCheck.fromCommand(ImmutableList.of()); Assert.fail(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/docker/CliDockerClientTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/docker/CliDockerClientTest.java index 3e7cca5b4ac..a059cbb567f 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/docker/CliDockerClientTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/docker/CliDockerClientTest.java @@ -32,6 +32,7 @@ import java.io.OutputStream; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.nio.file.Paths; import java.security.DigestException; import java.util.Arrays; @@ -39,29 +40,31 @@ import java.util.HashMap; import java.util.Map; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.io.TempDir; import org.mockito.AdditionalAnswers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.mockito.stubbing.VoidAnswer1; /** Tests for {@link CliDockerClient}. */ -@RunWith(MockitoJUnitRunner.class) -public class CliDockerClientTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CliDockerClientTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock private ProcessBuilder mockProcessBuilder; @Mock private Process mockProcess; @Mock private ImageTarball imageTarball; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { Mockito.when(mockProcessBuilder.start()).thenReturn(mockProcess); Mockito.doAnswer( AdditionalAnswers.answerVoid( @@ -72,19 +75,19 @@ public void setUp() throws IOException { } @Test - public void testIsDockerInstalled_fail() { + void testIsDockerInstalled_fail() { Assert.assertFalse(CliDockerClient.isDockerInstalled(Paths.get("path/to/nonexistent/file"))); } @Test - public void testIsDockerInstalled_pass() throws URISyntaxException { + void testIsDockerInstalled_pass() throws URISyntaxException { Assert.assertTrue( CliDockerClient.isDockerInstalled( Paths.get(Resources.getResource("core/docker/emptyFile").toURI()))); } @Test - public void testLoad() throws IOException, InterruptedException { + void testLoad() throws IOException, InterruptedException { DockerClient testDockerClient = new CliDockerClient( subcommand -> { @@ -109,7 +112,7 @@ public void testLoad() throws IOException, InterruptedException { } @Test - public void testLoad_stdinFail() throws InterruptedException { + void testLoad_stdinFail() throws InterruptedException { DockerClient testDockerClient = new CliDockerClient(ignored -> mockProcessBuilder); Mockito.when(mockProcess.getOutputStream()) @@ -134,7 +137,7 @@ public void write(int b) throws IOException { } @Test - public void testLoad_stdinFail_stderrFail() throws InterruptedException { + void testLoad_stdinFail_stderrFail() throws InterruptedException { DockerClient testDockerClient = new CliDockerClient(ignored -> mockProcessBuilder); Mockito.when(mockProcess.getOutputStream()) @@ -154,6 +157,12 @@ public void write(int b) throws IOException { public int read() throws IOException { throw new IOException(); } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + // overridden too to silence a warning + throw new IOException(); + } }); try { @@ -166,7 +175,7 @@ public int read() throws IOException { } @Test - public void testLoad_stdoutFail() throws InterruptedException { + void testLoad_stdoutFail() throws InterruptedException { DockerClient testDockerClient = new CliDockerClient(ignored -> mockProcessBuilder); Mockito.when(mockProcess.waitFor()).thenReturn(1); @@ -186,14 +195,14 @@ public void testLoad_stdoutFail() throws InterruptedException { } @Test - public void testSave() throws InterruptedException, IOException { + void testSave() throws InterruptedException, IOException { DockerClient testDockerClient = makeDockerSaveClient(); Mockito.when(mockProcess.waitFor()).thenReturn(0); long[] counter = new long[1]; testDockerClient.save( ImageReference.of(null, "testimage", null), - temporaryFolder.getRoot().toPath().resolve("out.tar"), + temporaryFolder.resolve("out.tar"), bytes -> counter[0] += bytes); // InputStream writes "jib", so 3 bytes of progress should have been counted. @@ -201,7 +210,7 @@ public void testSave() throws InterruptedException, IOException { } @Test - public void testSave_fail() throws InterruptedException { + void testSave_fail() throws InterruptedException { DockerClient testDockerClient = makeDockerSaveClient(); Mockito.when(mockProcess.waitFor()).thenReturn(1); @@ -211,7 +220,7 @@ public void testSave_fail() throws InterruptedException { try { testDockerClient.save( ImageReference.of(null, "testimage", null), - temporaryFolder.getRoot().toPath().resolve("out.tar"), + temporaryFolder.resolve("out.tar"), ignored -> {}); Assert.fail("docker save should have failed"); @@ -221,7 +230,7 @@ public void testSave_fail() throws InterruptedException { } @Test - public void testDefaultProcessorBuilderFactory_customExecutable() { + void testDefaultProcessorBuilderFactory_customExecutable() { ProcessBuilder processBuilder = CliDockerClient.defaultProcessBuilderFactory("docker-executable", ImmutableMap.of()) .apply(Arrays.asList("sub", "command")); @@ -232,7 +241,7 @@ public void testDefaultProcessorBuilderFactory_customExecutable() { } @Test - public void testDefaultProcessorBuilderFactory_customEnvironment() { + void testDefaultProcessorBuilderFactory_customEnvironment() { ImmutableMap environment = ImmutableMap.of("Key1", "Value1"); Map expectedEnvironment = new HashMap<>(System.getenv()); @@ -246,7 +255,7 @@ public void testDefaultProcessorBuilderFactory_customEnvironment() { } @Test - public void testSize_fail() throws InterruptedException { + void testSize_fail() throws InterruptedException { DockerClient testDockerClient = new CliDockerClient( subcommand -> { @@ -268,7 +277,7 @@ public void testSize_fail() throws InterruptedException { } @Test - public void testDockerImageDetails() throws DigestException, IOException { + void testDockerImageDetails() throws DigestException, IOException { String json = "{\"Size\":488118507," + "\"Id\":\"sha256:e8d00769c8a805a0656dbfd49d4f91cbc2e36d0199f10343d1beba36ecdcb3fd\"," @@ -294,7 +303,7 @@ public void testDockerImageDetails() throws DigestException, IOException { } @Test - public void testDockerImageDetails_unknownProperties() throws IOException, DigestException { + void testDockerImageDetails_unknownProperties() throws IOException, DigestException { String json = "{\"Unknown\": [ ], \"Structure\": [ { \"Test\": 0 } ], \"Size\": 1234," + "\"Id\": \"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"," @@ -314,7 +323,7 @@ public void testDockerImageDetails_unknownProperties() throws IOException, Diges } @Test - public void testDockerImageDetails_emptyJson() throws IOException, DigestException { + void testDockerImageDetails_emptyJson() throws IOException, DigestException { DockerImageDetails details = JsonTemplateMapper.readJson("{}", DockerImageDetails.class); Assert.assertEquals(0, details.getSize()); Assert.assertEquals(Collections.emptyList(), details.getDiffIds()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/docker/json/DockerManifestEntryTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/docker/json/DockerManifestEntryTemplateTest.java index 25051ac2f1d..4b448f29c67 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/docker/json/DockerManifestEntryTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/docker/json/DockerManifestEntryTemplateTest.java @@ -30,13 +30,13 @@ import java.util.Collections; import java.util.List; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link DockerManifestEntryTemplate}. */ -public class DockerManifestEntryTemplateTest { +class DockerManifestEntryTemplateTest { @Test - public void testToJson() throws URISyntaxException, IOException { + void testToJson() throws URISyntaxException, IOException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/loadmanifest.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -53,7 +53,7 @@ public void testToJson() throws URISyntaxException, IOException { } @Test - public void testFromJson() throws URISyntaxException, IOException { + void testFromJson() throws URISyntaxException, IOException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/loadmanifest.json").toURI()); String sourceJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/event/EventHandlersTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/event/EventHandlersTest.java index efcc910b4b7..f5f99d98868 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/event/EventHandlersTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/event/EventHandlersTest.java @@ -22,11 +22,11 @@ import java.util.List; import javax.annotation.Nullable; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** Tests for {@link EventHandlers}. */ -public class EventHandlersTest { +class EventHandlersTest { /** Test {@link JibEvent}. */ private interface TestJibEvent1 extends JibEvent { @@ -53,7 +53,7 @@ private void sayHello(String name) { private static class TestJibEvent3 implements JibEvent {} @Test - public void testAdd() { + void testAdd() { int[] counter = new int[1]; EventHandlers eventHandlers = EventHandlers.builder() @@ -87,7 +87,7 @@ public void testAdd() { } @Test - public void testDispatch() { + void testDispatch() { List emissions = new ArrayList<>(); EventHandlers eventHandlers = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/LogEventTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/LogEventTest.java index aa3b8737ea0..4579c91add3 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/LogEventTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/LogEventTest.java @@ -22,10 +22,10 @@ import java.util.ArrayDeque; import java.util.Deque; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link LogEvent}. */ -public class LogEventTest { +class LogEventTest { private final Deque receivedLogEvents = new ArrayDeque<>(); @@ -35,7 +35,7 @@ public class LogEventTest { EventHandlers.builder().add(LogEvent.class, receivedLogEvents::offer).build(); @Test - public void testFactories() { + void testFactories() { eventHandlers.dispatch(LogEvent.error("error")); eventHandlers.dispatch(LogEvent.lifecycle("lifecycle")); eventHandlers.dispatch(LogEvent.progress("progress")); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/ProgressEventTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/ProgressEventTest.java index b80b55e5dde..d0b31559b73 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/ProgressEventTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/event/events/ProgressEventTest.java @@ -22,10 +22,10 @@ import java.util.Map; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ProgressEvent}. */ -public class ProgressEventTest { +class ProgressEventTest { /** {@link Allocation} tree for testing. */ private static class AllocationTree { @@ -55,7 +55,7 @@ private static EventHandlers makeEventHandlers(Consumer progressE private double progress = 0.0; @Test - public void testAccumulateProgress() { + void testAccumulateProgress() { Consumer progressEventConsumer = progressEvent -> { double fractionOfRoot = progressEvent.getAllocation().getFractionOfRoot(); @@ -80,7 +80,7 @@ public void testAccumulateProgress() { } @Test - public void testSmoke() { + void testSmoke() { Consumer progressEventConsumer = progressEvent -> { Allocation allocation = progressEvent.getAllocation(); @@ -113,7 +113,7 @@ public void testSmoke() { } @Test - public void testType() { + void testType() { // Used to test whether or not progress event was consumed boolean[] called = new boolean[] {false}; Consumer buildImageConsumer = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationCompletionTrackerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationCompletionTrackerTest.java index 0f13673469c..13183d2ce3e 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationCompletionTrackerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationCompletionTrackerTest.java @@ -25,10 +25,10 @@ import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link AllocationCompletionTracker}. */ -public class AllocationCompletionTrackerTest { +class AllocationCompletionTrackerTest { /** {@link Allocation} tree for testing. */ private static class AllocationTree { @@ -48,7 +48,7 @@ private AllocationTree() {} } @Test - public void testGetUnfinishedAllocations_singleThread() { + void testGetUnfinishedAllocations_singleThread() { AllocationCompletionTracker allocationCompletionTracker = new AllocationCompletionTracker(); Assert.assertTrue(allocationCompletionTracker.updateProgress(AllocationTree.root, 0L)); @@ -99,7 +99,7 @@ public void testGetUnfinishedAllocations_singleThread() { } @Test - public void testGetUnfinishedAllocations_multipleThreads() + void testGetUnfinishedAllocations_multipleThreads() throws InterruptedException, ExecutionException, IOException { try (MultithreadedExecutor multithreadedExecutor = new MultithreadedExecutor()) { AllocationCompletionTracker allocationCompletionTracker = new AllocationCompletionTracker(); @@ -165,7 +165,7 @@ public void testGetUnfinishedAllocations_multipleThreads() } @Test - public void testGetUnfinishedLeafTasks() { + void testGetUnfinishedLeafTasks() { AllocationCompletionTracker tracker = new AllocationCompletionTracker(); tracker.updateProgress(AllocationTree.root, 0); Assert.assertEquals(Arrays.asList("root"), tracker.getUnfinishedLeafTasks()); @@ -193,7 +193,7 @@ public void testGetUnfinishedLeafTasks() { } @Test - public void testGetUnfinishedLeafTasks_differentUpdateOrder() { + void testGetUnfinishedLeafTasks_differentUpdateOrder() { AllocationCompletionTracker tracker = new AllocationCompletionTracker(); tracker.updateProgress(AllocationTree.root, 0); Assert.assertEquals(Arrays.asList("root"), tracker.getUnfinishedLeafTasks()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationTest.java index bfb060dd1e9..200f2329501 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/AllocationTest.java @@ -17,16 +17,16 @@ package com.google.cloud.tools.jib.event.progress; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Allocation}. */ -public class AllocationTest { +class AllocationTest { /** Error margin for checking equality of two doubles. */ private static final double DOUBLE_ERROR_MARGIN = 1e-10; @Test - public void testSmoke_linear() { + void testSmoke_linear() { Allocation root = Allocation.newRoot("root", 1); Allocation node1 = root.newChild("node1", 2); Allocation node2 = node1.newChild("node2", 3); @@ -50,7 +50,7 @@ public void testSmoke_linear() { } @Test - public void testFractionOfRoot_tree_partial() { + void testFractionOfRoot_tree_partial() { Allocation root = Allocation.newRoot("ignored", 10); Allocation left = root.newChild("ignored", 2); Allocation right = root.newChild("ignored", 4); @@ -70,7 +70,7 @@ public void testFractionOfRoot_tree_partial() { } @Test - public void testFractionOfRoot_tree_complete() { + void testFractionOfRoot_tree_complete() { Allocation root = Allocation.newRoot("ignored", 2); Allocation left = root.newChild("ignored", 3); @@ -92,7 +92,7 @@ public void testFractionOfRoot_tree_complete() { } @Test - public void testNonPositiveAllocationUnits() { + void testNonPositiveAllocationUnits() { Allocation root = Allocation.newRoot("ignored", 2); Allocation left = root.newChild("ignored", -30); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/ProgressEventHandlerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/ProgressEventHandlerTest.java index 484620dff5e..3452e5e2f01 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/ProgressEventHandlerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/event/progress/ProgressEventHandlerTest.java @@ -27,10 +27,10 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.DoubleAccumulator; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ProgressEventHandler}. */ -public class ProgressEventHandlerTest { +class ProgressEventHandlerTest { /** {@link Allocation} tree for testing. */ private static class AllocationTree { @@ -52,7 +52,7 @@ private AllocationTree() {} private static final double DOUBLE_ERROR_MARGIN = 1e-10; @Test - public void testAccept() throws ExecutionException, InterruptedException, IOException { + void testAccept() throws ExecutionException, InterruptedException, IOException { try (MultithreadedExecutor multithreadedExecutor = new MultithreadedExecutor()) { DoubleAccumulator maxProgress = new DoubleAccumulator(Double::max, 0); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/DirectoryWalkerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/DirectoryWalkerTest.java index 565163eab46..50ef991e778 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/DirectoryWalkerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/DirectoryWalkerTest.java @@ -25,24 +25,24 @@ import java.util.HashSet; import java.util.Set; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link DirectoryWalker}. */ -public class DirectoryWalkerTest { +class DirectoryWalkerTest { private final Set walkedPaths = new HashSet<>(); private final PathConsumer addToWalkedPaths = walkedPaths::add; private Path testDir; - @Before - public void setUp() throws URISyntaxException { + @BeforeEach + void setUp() throws URISyntaxException { testDir = Paths.get(Resources.getResource("core/layer").toURI()); } @Test - public void testWalk() throws IOException { + void testWalk() throws IOException { new DirectoryWalker(testDir).walk(addToWalkedPaths); Set expectedPaths = @@ -59,7 +59,7 @@ public void testWalk() throws IOException { } @Test - public void testWalk_withFilter() throws IOException { + void testWalk_withFilter() throws IOException { // Filters to immediate subdirectories of testDir, and foo. new DirectoryWalker(testDir) .filter(path -> path.getParent().equals(testDir)) @@ -72,7 +72,7 @@ public void testWalk_withFilter() throws IOException { } @Test - public void testWalk_withFilterRoot() throws IOException { + void testWalk_withFilterRoot() throws IOException { new DirectoryWalker(testDir).filterRoot().walk(addToWalkedPaths); Set expectedPaths = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/FileOperationsTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/FileOperationsTest.java index abfe2f3e4f5..7e5984b63e7 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/FileOperationsTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/FileOperationsTest.java @@ -24,18 +24,17 @@ import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; -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; /** Tests for {@link FileOperations}. */ -public class FileOperationsTest { +class FileOperationsTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testCopy() throws IOException, URISyntaxException { - Path destDir = temporaryFolder.newFolder().toPath(); + void testCopy() throws IOException, URISyntaxException { + Path destDir = Files.createTempDirectory(temporaryFolder, "jib"); Path libraryA = Paths.get(Resources.getResource("core/application/dependencies/libraryA.jar").toURI()); Path libraryB = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/LockFileTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/LockFileTest.java index 1181157cfe0..03c7abc1054 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/LockFileTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/LockFileTest.java @@ -18,27 +18,26 @@ import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; -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; /** Tests for {@link LockFile}. */ -public class LockFileTest { +class LockFileTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testLockAndRelease() throws InterruptedException { + void testLockAndRelease() throws InterruptedException { AtomicInteger atomicInt = new AtomicInteger(0); // Runnable that would produce a race condition without a lock file Runnable procedure = () -> { - try (LockFile ignored = - LockFile.lock(temporaryFolder.getRoot().toPath().resolve("testLock"))) { - Assert.assertTrue(Files.exists(temporaryFolder.getRoot().toPath().resolve("testLock"))); + try (LockFile ignored = LockFile.lock(temporaryFolder.resolve("testLock"))) { + Assert.assertTrue(Files.exists(temporaryFolder.resolve("testLock"))); int valueBeforeSleep = atomicInt.intValue(); Thread.sleep(100); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/TempDirectoryProviderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/TempDirectoryProviderTest.java index 2c2575a5083..98d1e250bb0 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/TempDirectoryProviderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/TempDirectoryProviderTest.java @@ -23,12 +23,11 @@ import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; -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; /** Tests for {@link TempDirectoryProvider}. */ -public class TempDirectoryProviderTest { +class TempDirectoryProviderTest { private static void createFilesInDirectory(Path directory) throws IOException, URISyntaxException { @@ -38,11 +37,11 @@ private static void createFilesInDirectory(Path directory) .walk(path -> Files.copy(path, directory.resolve(testFilesDirectory.relativize(path)))); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testClose_directoriesDeleted() throws IOException, URISyntaxException { - Path parent = temporaryFolder.newFolder().toPath(); + void testClose_directoriesDeleted() throws IOException, URISyntaxException { + Path parent = Files.createTempDirectory(temporaryFolder, "jib"); try (TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider()) { Path directory1 = tempDirectoryProvider.newDirectory(parent); @@ -57,8 +56,8 @@ public void testClose_directoriesDeleted() throws IOException, URISyntaxExceptio } @Test - public void testClose_directoryNotDeletedIfMoved() throws IOException, URISyntaxException { - Path destinationParent = temporaryFolder.newFolder().toPath(); + void testClose_directoryNotDeletedIfMoved() throws IOException, URISyntaxException { + Path destinationParent = Files.createTempDirectory(temporaryFolder, "jib"); try (TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider()) { Path directory = tempDirectoryProvider.newDirectory(destinationParent); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/XdgDirectoriesTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/XdgDirectoriesTest.java index a3e23a5b95c..4571319a43c 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/XdgDirectoriesTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/filesystem/XdgDirectoriesTest.java @@ -25,78 +25,71 @@ import java.util.Map; import java.util.Properties; import org.junit.Assert; -import org.junit.Before; -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; /** Tests for {@link XdgDirectories}. */ -public class XdgDirectoriesTest { +class XdgDirectoriesTest { - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private String fakeCacheHome; - private String fakeConfigHome; - - @Before - public void setUp() throws IOException { - fakeCacheHome = temporaryFolder.newFolder().getPath(); - fakeConfigHome = temporaryFolder.newFolder().getPath(); - } + @TempDir private Path fakeCacheHome; + @TempDir private Path fakeConfigHome; @Test - public void testGetCacheHome_hasXdgCacheHome() { + void testGetCacheHome_hasXdgCacheHome() { Properties fakeProperties = new Properties(); - fakeProperties.setProperty("user.home", fakeCacheHome); - Map fakeEnvironment = ImmutableMap.of("XDG_CACHE_HOME", fakeCacheHome); + fakeProperties.setProperty("user.home", fakeCacheHome.toString()); + Map fakeEnvironment = + ImmutableMap.of("XDG_CACHE_HOME", fakeCacheHome.toString()); fakeProperties.setProperty("os.name", "linux"); Assert.assertEquals( - Paths.get(fakeCacheHome).resolve("google-cloud-tools-java").resolve("jib"), + fakeCacheHome.resolve("google-cloud-tools-java").resolve("jib"), XdgDirectories.getCacheHome(fakeProperties, fakeEnvironment)); fakeProperties.setProperty("os.name", "windows"); Assert.assertEquals( - Paths.get(fakeCacheHome).resolve("Google").resolve("Jib").resolve("Cache"), + fakeCacheHome.resolve("Google").resolve("Jib").resolve("Cache"), XdgDirectories.getCacheHome(fakeProperties, fakeEnvironment)); fakeProperties.setProperty("os.name", "mac"); Assert.assertEquals( - Paths.get(fakeCacheHome).resolve("Google").resolve("Jib"), + fakeCacheHome.resolve("Google").resolve("Jib"), XdgDirectories.getCacheHome(fakeProperties, fakeEnvironment)); } @Test - public void testGetCacheHome_linux() { + void testGetCacheHome_linux() { Properties fakeProperties = new Properties(); - fakeProperties.setProperty("user.home", fakeCacheHome); + fakeProperties.setProperty("user.home", fakeCacheHome.toString()); fakeProperties.setProperty("os.name", "os is LiNuX"); Assert.assertEquals( - Paths.get(fakeCacheHome, ".cache").resolve("google-cloud-tools-java").resolve("jib"), + Paths.get(fakeCacheHome.toString(), ".cache") + .resolve("google-cloud-tools-java") + .resolve("jib"), XdgDirectories.getCacheHome(fakeProperties, Collections.emptyMap())); } @Test - public void testGetCacheHome_windows() { + void testGetCacheHome_windows() { Properties fakeProperties = new Properties(); fakeProperties.setProperty("user.home", "nonexistent"); fakeProperties.setProperty("os.name", "os is WiNdOwS"); - Map fakeEnvironment = ImmutableMap.of("LOCALAPPDATA", fakeCacheHome); + Map fakeEnvironment = ImmutableMap.of("LOCALAPPDATA", fakeCacheHome.toString()); Assert.assertEquals( - Paths.get(fakeCacheHome).resolve("Google").resolve("Jib").resolve("Cache"), + fakeCacheHome.resolve("Google").resolve("Jib").resolve("Cache"), XdgDirectories.getCacheHome(fakeProperties, fakeEnvironment)); } @Test - public void testGetCacheHome_mac() throws IOException { - Path libraryApplicationSupport = Paths.get(fakeCacheHome, "Library", "Caches"); + void testGetCacheHome_mac() throws IOException { + Path libraryApplicationSupport = Paths.get(fakeCacheHome.toString(), "Library", "Caches"); Files.createDirectories(libraryApplicationSupport); Properties fakeProperties = new Properties(); - fakeProperties.setProperty("user.home", fakeCacheHome); + fakeProperties.setProperty("user.home", fakeCacheHome.toString()); fakeProperties.setProperty("os.name", "os is mAc or DaRwIn"); Assert.assertEquals( @@ -105,58 +98,62 @@ public void testGetCacheHome_mac() throws IOException { } @Test - public void testGetConfigHome_hasXdgConfigHome() { + void testGetConfigHome_hasXdgConfigHome() { Properties fakeProperties = new Properties(); - fakeProperties.setProperty("user.home", fakeConfigHome); - Map fakeEnvironment = ImmutableMap.of("XDG_CONFIG_HOME", fakeConfigHome); + fakeProperties.setProperty("user.home", fakeConfigHome.toString()); + Map fakeEnvironment = + ImmutableMap.of("XDG_CONFIG_HOME", fakeConfigHome.toString()); fakeProperties.setProperty("os.name", "linux"); Assert.assertEquals( - Paths.get(fakeConfigHome).resolve("google-cloud-tools-java").resolve("jib"), + fakeConfigHome.resolve("google-cloud-tools-java").resolve("jib"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); fakeProperties.setProperty("os.name", "windows"); Assert.assertEquals( - Paths.get(fakeConfigHome).resolve("Google").resolve("Jib").resolve("Config"), + fakeConfigHome.resolve("Google").resolve("Jib").resolve("Config"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); fakeProperties.setProperty("os.name", "mac"); Assert.assertEquals( - Paths.get(fakeConfigHome).resolve("Google").resolve("Jib"), + fakeConfigHome.resolve("Google").resolve("Jib"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); } @Test - public void testGetConfigHome_linux() { + void testGetConfigHome_linux() { Properties fakeProperties = new Properties(); - fakeProperties.setProperty("user.home", fakeConfigHome); + fakeProperties.setProperty("user.home", fakeConfigHome.toString()); fakeProperties.setProperty("os.name", "os is LiNuX"); Assert.assertEquals( - Paths.get(fakeConfigHome, ".config").resolve("google-cloud-tools-java").resolve("jib"), + Paths.get(fakeConfigHome.toString(), ".config") + .resolve("google-cloud-tools-java") + .resolve("jib"), XdgDirectories.getConfigHome(fakeProperties, Collections.emptyMap())); } @Test - public void testGetConfigHome_windows() { + void testGetConfigHome_windows() { Properties fakeProperties = new Properties(); fakeProperties.setProperty("user.home", "nonexistent"); fakeProperties.setProperty("os.name", "os is WiNdOwS"); - Map fakeEnvironment = ImmutableMap.of("LOCALAPPDATA", fakeConfigHome); + Map fakeEnvironment = + ImmutableMap.of("LOCALAPPDATA", fakeConfigHome.toString()); Assert.assertEquals( - Paths.get(fakeConfigHome).resolve("Google").resolve("Jib").resolve("Config"), + fakeConfigHome.resolve("Google").resolve("Jib").resolve("Config"), XdgDirectories.getConfigHome(fakeProperties, fakeEnvironment)); } @Test - public void testGetConfigHome_mac() throws IOException { - Path libraryApplicationSupport = Paths.get(fakeConfigHome, "Library", "Preferences"); + void testGetConfigHome_mac() throws IOException { + Path libraryApplicationSupport = Paths.get(fakeConfigHome.toString(), "Library", "Preferences"); Files.createDirectories(libraryApplicationSupport); Properties fakeProperties = new Properties(); - fakeProperties.setProperty("user.home", fakeConfigHome); + fakeProperties.setProperty("user.home", fakeConfigHome.toString()); fakeProperties.setProperty("os.name", "os is mAc or DaRwIn"); Assert.assertEquals( diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/frontend/CredentialRetrieverFactoryTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/frontend/CredentialRetrieverFactoryTest.java index 9c05c08a05e..777459b316d 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/frontend/CredentialRetrieverFactoryTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/frontend/CredentialRetrieverFactoryTest.java @@ -35,16 +35,19 @@ import java.util.Optional; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link CredentialRetrieverFactory}. */ -@RunWith(MockitoJUnitRunner.class) -public class CredentialRetrieverFactoryTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CredentialRetrieverFactoryTest { private static final Credential FAKE_CREDENTIALS = Credential.from("username", "password"); @@ -53,8 +56,8 @@ public class CredentialRetrieverFactoryTest { @Mock private DockerCredentialHelperFactory mockDockerCredentialHelperFactory; @Mock private GoogleCredentials mockGoogleCredentials; - @Before - public void setUp() + @BeforeEach + void setUp() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { Mockito.when( @@ -67,7 +70,7 @@ public void setUp() } @Test - public void testDockerCredentialHelper() throws CredentialRetrievalException { + void testDockerCredentialHelper() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("registry", "repo"); @@ -85,7 +88,7 @@ public void testDockerCredentialHelper() throws CredentialRetrievalException { } @Test - public void testDockerCredentialHelperWithEnvironment() throws CredentialRetrievalException { + void testDockerCredentialHelperWithEnvironment() throws CredentialRetrievalException { Map environment = Collections.singletonMap("ENV_VARIABLE", "Value"); CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("registry", "repo", environment); @@ -104,7 +107,7 @@ public void testDockerCredentialHelperWithEnvironment() throws CredentialRetriev } @Test - public void testWellKnownCredentialHelpers() throws CredentialRetrievalException { + void testWellKnownCredentialHelpers() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("something.gcr.io", "repo"); @@ -121,8 +124,7 @@ public void testWellKnownCredentialHelpers() throws CredentialRetrievalException } @Test - public void testWellKnownCredentialHelpers_info() - throws CredentialRetrievalException, IOException { + void testWellKnownCredentialHelpers_info() throws CredentialRetrievalException, IOException { CredentialHelperNotFoundException notFoundException = Mockito.mock(CredentialHelperNotFoundException.class); Mockito.when(notFoundException.getMessage()).thenReturn("warning"); @@ -145,7 +147,7 @@ public void testWellKnownCredentialHelpers_info() } @Test - public void testDockerConfig() throws IOException, CredentialRetrievalException { + void testDockerConfig() throws IOException, CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("registry", "repo"); @@ -167,7 +169,7 @@ public void testDockerConfig() throws IOException, CredentialRetrievalException } @Test - public void testGoogleApplicationDefaultCredentials_notGoogleContainerRegistry() + void testGoogleApplicationDefaultCredentials_notGoogleContainerRegistry() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("non.gcr.registry", "repository"); @@ -179,8 +181,7 @@ public void testGoogleApplicationDefaultCredentials_notGoogleContainerRegistry() } @Test - public void testGoogleApplicationDefaultCredentials_adcNotPresent() - throws CredentialRetrievalException { + void testGoogleApplicationDefaultCredentials_adcNotPresent() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = new CredentialRetrieverFactory( ImageReference.of("awesome.gcr.io", "repository", null), @@ -199,7 +200,7 @@ public void testGoogleApplicationDefaultCredentials_adcNotPresent() } @Test - public void testGoogleApplicationDefaultCredentials_refreshFailure() + void testGoogleApplicationDefaultCredentials_refreshFailure() throws CredentialRetrievalException, IOException { Mockito.doThrow(new IOException("refresh failed")) .when(mockGoogleCredentials) @@ -218,7 +219,7 @@ public void testGoogleApplicationDefaultCredentials_refreshFailure() } @Test - public void testGoogleApplicationDefaultCredentials_endUserCredentials() + void testGoogleApplicationDefaultCredentials_endUserCredentials() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("awesome.gcr.io", "repo"); @@ -239,7 +240,7 @@ public void testGoogleApplicationDefaultCredentials_endUserCredentials() } @Test - public void testGoogleApplicationDefaultCredentials_endUserCredentials_artifactRegistry() + void testGoogleApplicationDefaultCredentials_endUserCredentials_artifactRegistry() throws CredentialRetrievalException { CredentialRetrieverFactory credentialRetrieverFactory = createCredentialRetrieverFactory("us-docker.pkg.dev", "my-project/repo/my-app"); @@ -261,7 +262,7 @@ public void testGoogleApplicationDefaultCredentials_endUserCredentials_artifactR } @Test - public void testGoogleApplicationDefaultCredentials_serviceAccount() + void testGoogleApplicationDefaultCredentials_serviceAccount() throws CredentialRetrievalException { Mockito.when(mockGoogleCredentials.createScopedRequired()).thenReturn(true); Mockito.when(mockGoogleCredentials.createScoped(Mockito.anyCollection())) diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/global/JibSystemPropertiesTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/global/JibSystemPropertiesTest.java index 8774de988b5..d5d85488282 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/global/JibSystemPropertiesTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/global/JibSystemPropertiesTest.java @@ -18,22 +18,22 @@ import org.junit.Assert; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; +import org.junit.jupiter.api.Test; /** Tests for {@link JibSystemProperties}. */ -public class JibSystemPropertiesTest { +class JibSystemPropertiesTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); @Test - public void testCheckHttpTimeoutProperty_okWhenUndefined() throws NumberFormatException { + void testCheckHttpTimeoutProperty_okWhenUndefined() throws NumberFormatException { System.clearProperty(JibSystemProperties.HTTP_TIMEOUT); JibSystemProperties.checkHttpTimeoutProperty(); } @Test - public void testCheckHttpTimeoutProperty_stringValue() { + void testCheckHttpTimeoutProperty_stringValue() { System.setProperty(JibSystemProperties.HTTP_TIMEOUT, "random string"); try { JibSystemProperties.checkHttpTimeoutProperty(); @@ -44,14 +44,14 @@ public void testCheckHttpTimeoutProperty_stringValue() { } @Test - public void testCheckHttpProxyPortProperty_undefined() throws NumberFormatException { + void testCheckHttpProxyPortProperty_undefined() throws NumberFormatException { System.clearProperty("http.proxyPort"); System.clearProperty("https.proxyPort"); JibSystemProperties.checkProxyPortProperty(); } @Test - public void testCheckHttpProxyPortProperty() throws NumberFormatException { + void testCheckHttpProxyPortProperty() throws NumberFormatException { System.setProperty("http.proxyPort", "0"); System.setProperty("https.proxyPort", "0"); JibSystemProperties.checkProxyPortProperty(); @@ -70,7 +70,7 @@ public void testCheckHttpProxyPortProperty() throws NumberFormatException { } @Test - public void testCheckHttpProxyPortProperty_negativeValue() { + void testCheckHttpProxyPortProperty_negativeValue() { System.setProperty("http.proxyPort", "-1"); System.clearProperty("https.proxyPort"); try { @@ -91,7 +91,7 @@ public void testCheckHttpProxyPortProperty_negativeValue() { } @Test - public void testCheckHttpProxyPortProperty_over65535() { + void testCheckHttpProxyPortProperty_over65535() { System.setProperty("http.proxyPort", "65536"); System.clearProperty("https.proxyPort"); try { @@ -112,7 +112,7 @@ public void testCheckHttpProxyPortProperty_over65535() { } @Test - public void testCheckHttpProxyPortProperty_stringValue() { + void testCheckHttpProxyPortProperty_stringValue() { System.setProperty("http.proxyPort", "some string"); System.clearProperty("https.proxyPort"); try { @@ -133,36 +133,36 @@ public void testCheckHttpProxyPortProperty_stringValue() { } @Test - public void testUseBlobMountsPropertyName() { + void testUseBlobMountsPropertyName() { Assert.assertEquals("jib.blobMounts", JibSystemProperties.CROSS_REPOSITORY_BLOB_MOUNTS); } @Test - public void testUseBlobMounts_undefined() { + void testUseBlobMounts_undefined() { System.clearProperty(JibSystemProperties.CROSS_REPOSITORY_BLOB_MOUNTS); Assert.assertTrue(JibSystemProperties.useCrossRepositoryBlobMounts()); } @Test - public void testUseBlobMounts_true() { + void testUseBlobMounts_true() { System.setProperty(JibSystemProperties.CROSS_REPOSITORY_BLOB_MOUNTS, "true"); Assert.assertTrue(JibSystemProperties.useCrossRepositoryBlobMounts()); } @Test - public void testUseBlobMounts_false() { + void testUseBlobMounts_false() { System.setProperty(JibSystemProperties.CROSS_REPOSITORY_BLOB_MOUNTS, "false"); Assert.assertFalse(JibSystemProperties.useCrossRepositoryBlobMounts()); } @Test - public void testUseBlobMounts_other() { + void testUseBlobMounts_other() { System.setProperty(JibSystemProperties.CROSS_REPOSITORY_BLOB_MOUNTS, "nonbool"); Assert.assertFalse(JibSystemProperties.useCrossRepositoryBlobMounts()); } @Test - public void testSkipExistingImages_undefined() { + void testSkipExistingImages_undefined() { System.clearProperty(JibSystemProperties.SKIP_EXISTING_IMAGES); Assert.assertFalse(JibSystemProperties.skipExistingImages()); } diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/hash/CountingDigestOutputStreamTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/hash/CountingDigestOutputStreamTest.java index 51a628d1b70..32557424e68 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/hash/CountingDigestOutputStreamTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/hash/CountingDigestOutputStreamTest.java @@ -29,10 +29,10 @@ import java.security.DigestException; import java.util.Map; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link CountingDigestOutputStream}. */ -public class CountingDigestOutputStreamTest { +class CountingDigestOutputStreamTest { private static final ImmutableMap KNOWN_SHA256_HASHES = ImmutableMap.of( @@ -44,7 +44,7 @@ public class CountingDigestOutputStreamTest { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); @Test - public void test_smokeTest() throws IOException, DigestException { + void test_smokeTest() throws IOException, DigestException { for (Map.Entry knownHash : KNOWN_SHA256_HASHES.entrySet()) { String toHash = knownHash.getKey(); String expectedHash = knownHash.getValue(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/http/FailoverHttpClientTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/http/FailoverHttpClientTest.java index b46267d96d7..35cafbb6fb1 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/http/FailoverHttpClientTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/http/FailoverHttpClientTest.java @@ -46,18 +46,21 @@ import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.junit.Assert; -import org.junit.Before; -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.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link FailoverHttpClient}. */ -@RunWith(MockitoJUnitRunner.class) -public class FailoverHttpClientTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class FailoverHttpClientTest { @FunctionalInterface private interface CallFunction { @@ -81,29 +84,29 @@ private interface CallFunction { private final GenericUrl fakeUrl = new GenericUrl("https://crepecake/fake/url"); private final LongAdder totalByteCount = new LongAdder(); - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(new byte[] {'b', 'o', 'd', 'y'}); Mockito.when(mockHttpResponse.getContent()).thenReturn(inStream); } @Test - public void testGet() throws IOException { + void testGet() throws IOException { verifyCall(HttpMethods.GET, FailoverHttpClient::get); } @Test - public void testPost() throws IOException { + void testPost() throws IOException { verifyCall(HttpMethods.POST, FailoverHttpClient::post); } @Test - public void testPut() throws IOException { + void testPut() throws IOException { verifyCall(HttpMethods.PUT, FailoverHttpClient::put); } @Test - public void testHttpTimeout_doNotSetByDefault() throws IOException { + void testHttpTimeout_doNotSetByDefault() throws IOException { try (Response ignored = newHttpClient(false, false).get(fakeUrl.toURL(), fakeRequest(null))) { // intentionally empty } @@ -113,7 +116,7 @@ public void testHttpTimeout_doNotSetByDefault() throws IOException { } @Test - public void testHttpTimeout() throws IOException { + void testHttpTimeout() throws IOException { FailoverHttpClient httpClient = newHttpClient(false, false); try (Response ignored = httpClient.get(fakeUrl.toURL(), fakeRequest(5982))) { // intentionally empty @@ -124,7 +127,7 @@ public void testHttpTimeout() throws IOException { } @Test - public void testGet_nonHttpsServer_insecureConnectionAndFailoverDisabled() + void testGet_nonHttpsServer_insecureConnectionAndFailoverDisabled() throws MalformedURLException, IOException { FailoverHttpClient httpClient = newHttpClient(false, false); try (Response response = httpClient.get(new URL("http://plain.http"), fakeRequest(null))) { @@ -136,7 +139,7 @@ public void testGet_nonHttpsServer_insecureConnectionAndFailoverDisabled() } @Test - public void testCall_secureClientOnUnverifiableServer() throws IOException { + void testCall_secureClientOnUnverifiableServer() throws IOException { FailoverHttpClient httpClient = newHttpClient(false, false); Mockito.when(mockHttpRequest.execute()).thenThrow(new SSLPeerUnverifiedException("unverified")); @@ -150,7 +153,7 @@ public void testCall_secureClientOnUnverifiableServer() throws IOException { } @Test - public void testGet_insecureClientOnUnverifiableServer() throws IOException { + void testGet_insecureClientOnUnverifiableServer() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()).thenThrow(new SSLPeerUnverifiedException("")); @@ -168,7 +171,7 @@ public void testGet_insecureClientOnUnverifiableServer() throws IOException { } @Test - public void testGet_insecureClientOnHttpServer() throws IOException { + void testGet_insecureClientOnHttpServer() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -194,7 +197,7 @@ public void testGet_insecureClientOnHttpServer() throws IOException { } @Test - public void testGet_insecureClientOnHttpServerAndNoPortSpecified() throws IOException { + void testGet_insecureClientOnHttpServerAndNoPortSpecified() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -216,7 +219,7 @@ public void testGet_insecureClientOnHttpServerAndNoPortSpecified() throws IOExce } @Test - public void testGet_secureClientOnNonListeningServerAndNoPortSpecified() throws IOException { + void testGet_secureClientOnNonListeningServerAndNoPortSpecified() throws IOException { FailoverHttpClient httpClient = newHttpClient(false, false); Mockito.when(mockHttpRequest.execute()) @@ -235,7 +238,7 @@ public void testGet_secureClientOnNonListeningServerAndNoPortSpecified() throws } @Test - public void testGet_insecureClientOnNonListeningServerAndPortSpecified() throws IOException { + void testGet_insecureClientOnNonListeningServerAndPortSpecified() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -255,7 +258,7 @@ public void testGet_insecureClientOnNonListeningServerAndPortSpecified() throws } @Test - public void testGet_timeoutFromConnectException() throws IOException { + void testGet_timeoutFromConnectException() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()).thenThrow(new ConnectException("Connection timed out")); @@ -274,7 +277,7 @@ public void testGet_timeoutFromConnectException() throws IOException { } @Test - public void testGet_doNotSendCredentialsOverHttp() throws IOException { + void testGet_doNotSendCredentialsOverHttp() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); // make it fall back to HTTP @@ -297,7 +300,7 @@ public void testGet_doNotSendCredentialsOverHttp() throws IOException { } @Test - public void testGet_sendCredentialsOverHttp() throws IOException { + void testGet_sendCredentialsOverHttp() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, true); // sendCredentialsOverHttp try (Response response = @@ -313,7 +316,7 @@ public void testGet_sendCredentialsOverHttp() throws IOException { } @Test - public void testGet_originalRequestHeaderUntouchedWhenClearingHeader() throws IOException { + void testGet_originalRequestHeaderUntouchedWhenClearingHeader() throws IOException { FailoverHttpClient insecureHttpClient = newHttpClient(true, false); Request request = fakeRequest(null); @@ -330,7 +333,7 @@ public void testGet_originalRequestHeaderUntouchedWhenClearingHeader() throws IO } @Test - public void testShutDown() throws IOException { + void testShutDown() throws IOException { FailoverHttpClient secureHttpClient = newHttpClient(false, false); try (Response response = secureHttpClient.get(fakeUrl.toURL(), fakeRequest(null))) { @@ -342,7 +345,7 @@ public void testShutDown() throws IOException { } @Test - public void testFollowFailoverHistory_insecureHttps() throws IOException { + void testFollowFailoverHistory_insecureHttps() throws IOException { FailoverHttpClient httpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -361,7 +364,7 @@ public void testFollowFailoverHistory_insecureHttps() throws IOException { } @Test - public void testFollowFailoverHistory_httpFailoverByConnectionError() throws IOException { + void testFollowFailoverHistory_httpFailoverByConnectionError() throws IOException { FailoverHttpClient httpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -379,7 +382,7 @@ public void testFollowFailoverHistory_httpFailoverByConnectionError() throws IOE } @Test - public void testFollowFailoverHistory_httpFailover() throws IOException { + void testFollowFailoverHistory_httpFailover() throws IOException { FailoverHttpClient httpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -401,7 +404,7 @@ public void testFollowFailoverHistory_httpFailover() throws IOException { } @Test - public void testFollowFailoverHistory_portsDifferent() throws IOException { + void testFollowFailoverHistory_portsDifferent() throws IOException { FailoverHttpClient httpClient = newHttpClient(true, false); Mockito.when(mockHttpRequest.execute()) @@ -423,7 +426,7 @@ public void testFollowFailoverHistory_portsDifferent() throws IOException { } @Test - public void testRetries() throws IOException { + void testRetries() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(0), 1); AtomicBoolean failed = new AtomicBoolean(); server diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/http/NotifyingOutputStreamTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/http/NotifyingOutputStreamTest.java index facf1cdd766..e9d1c803b19 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/http/NotifyingOutputStreamTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/http/NotifyingOutputStreamTest.java @@ -27,13 +27,13 @@ import java.util.List; import java.util.Queue; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link NotifyingOutputStream}. */ -public class NotifyingOutputStreamTest { +class NotifyingOutputStreamTest { @Test - public void testCallback_correctSequence() throws IOException { + void testCallback_correctSequence() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); List byteCounts = new ArrayList<>(); @@ -50,7 +50,7 @@ public void testCallback_correctSequence() throws IOException { } @Test - public void testDelay() throws IOException { + void testDelay() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); List byteCounts = new ArrayList<>(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/http/RequestTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/http/RequestTest.java index 012ee51df63..8b7a1f2d817 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/http/RequestTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/http/RequestTest.java @@ -17,20 +17,20 @@ package com.google.cloud.tools.jib.http; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link Request}. */ -public class RequestTest { +class RequestTest { @Test - public void testGetHttpTimeout() { + void testGetHttpTimeout() { Request request = Request.builder().build(); Assert.assertNull(request.getHttpTimeout()); } @Test - public void testSetHttpTimeout() { + void testSetHttpTimeout() { Request request = Request.builder().setHttpTimeout(3000).build(); Assert.assertEquals(Integer.valueOf(3000), request.getHttpTimeout()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/http/ResponseTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/http/ResponseTest.java index dd27e0bd7e7..d228606da58 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/http/ResponseTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/http/ResponseTest.java @@ -22,20 +22,23 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link Response}. */ -@RunWith(MockitoJUnitRunner.class) -public class ResponseTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ResponseTest { @Mock private HttpResponse httpResponseMock; @Test - public void testGetContent() throws IOException { + void testGetContent() throws IOException { byte[] expectedResponse = "crepecake\nis\ngood!".getBytes(StandardCharsets.UTF_8); ByteArrayInputStream responseInputStream = new ByteArrayInputStream(expectedResponse); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/http/WithServerFailoverHttpClientTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/http/WithServerFailoverHttpClientTest.java index 05d9b00058f..4e85e05a699 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/http/WithServerFailoverHttpClientTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/http/WithServerFailoverHttpClientTest.java @@ -33,16 +33,19 @@ import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link FailoverHttpClient} using an actual local server. */ -@RunWith(MockitoJUnitRunner.class) -public class WithServerFailoverHttpClientTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class WithServerFailoverHttpClientTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); @@ -51,7 +54,7 @@ public class WithServerFailoverHttpClientTest { private final Request request = new Request.Builder().build(); @Test - public void testGet() + void testGet() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { FailoverHttpClient insecureHttpClient = new FailoverHttpClient(true /*insecure*/, false, logger); @@ -67,7 +70,7 @@ public void testGet() } @Test - public void testSecureConnectionOnInsecureHttpsServer() + void testSecureConnectionOnInsecureHttpsServer() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { FailoverHttpClient secureHttpClient = new FailoverHttpClient(false /*secure*/, false, logger, false); @@ -81,7 +84,7 @@ public void testSecureConnectionOnInsecureHttpsServer() } @Test - public void testInsecureConnection_insecureHttpsFailover() + void testInsecureConnection_insecureHttpsFailover() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { FailoverHttpClient insecureHttpClient = new FailoverHttpClient(true /*insecure*/, false, logger); @@ -101,7 +104,7 @@ public void testInsecureConnection_insecureHttpsFailover() } @Test - public void testInsecureConnection_plainHttpFailover() + void testInsecureConnection_plainHttpFailover() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { FailoverHttpClient insecureHttpClient = new FailoverHttpClient(true /*insecure*/, false, logger); @@ -125,7 +128,7 @@ public void testInsecureConnection_plainHttpFailover() } @Test - public void testProxyCredentialProperties() + void testProxyCredentialProperties() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { String proxyResponse = "HTTP/1.1 407 Proxy Authentication Required\n" @@ -156,7 +159,7 @@ public void testProxyCredentialProperties() } @Test - public void testClosingResourcesMultipleTimes_noErrors() + void testClosingResourcesMultipleTimes_noErrors() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { FailoverHttpClient httpClient = new FailoverHttpClient(true /*insecure*/, false, logger); try (TestWebServer server = new TestWebServer(false, 2); @@ -175,7 +178,7 @@ public void testClosingResourcesMultipleTimes_noErrors() } @Test - public void testRedirectionUrls() + void testRedirectionUrls() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { // Sample query strings from // https://github.com/GoogleContainerTools/jib/issues/1986#issuecomment-547610104 diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTarballTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTarballTest.java index 0ad3c8cafc9..5c9d6f556db 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTarballTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTarballTest.java @@ -45,16 +45,19 @@ import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ImageTarball}. */ -@RunWith(MockitoJUnitRunner.class) -public class ImageTarballTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ImageTarballTest { private Path fileA; private Path fileB; @@ -64,8 +67,8 @@ public class ImageTarballTest { @Mock private Layer mockLayer1; @Mock private Layer mockLayer2; - @Before - public void setup() throws URISyntaxException, IOException, DigestException { + @BeforeEach + void setup() throws URISyntaxException, IOException, DigestException { fileA = Paths.get(Resources.getResource("core/fileA").toURI()); fileB = Paths.get(Resources.getResource("core/fileB").toURI()); long fileASize = Files.size(fileA); @@ -89,7 +92,7 @@ public void setup() throws URISyntaxException, IOException, DigestException { } @Test - public void testWriteTo_docker() + void testWriteTo_docker() throws InvalidImageReferenceException, IOException, LayerPropertyNotFoundException { Image testImage = Image.builder(V22ManifestTemplate.class).addLayer(mockLayer1).addLayer(mockLayer2).build(); @@ -143,7 +146,7 @@ public void testWriteTo_docker() } @Test - public void testWriteTo_oci() + void testWriteTo_oci() throws InvalidImageReferenceException, IOException, LayerPropertyNotFoundException { Image testImage = Image.builder(OciManifestTemplate.class).addLayer(mockLayer1).addLayer(mockLayer2).build(); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTest.java index b2c8e967287..fd3b431b966 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/ImageTest.java @@ -27,28 +27,31 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link Image}. */ -@RunWith(MockitoJUnitRunner.class) -public class ImageTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ImageTest { @Mock private Layer mockLayer; @Mock private DescriptorDigest mockDescriptorDigest; - @Before - public void setUp() throws LayerPropertyNotFoundException { + @BeforeEach + void setUp() throws LayerPropertyNotFoundException { Mockito.when(mockLayer.getBlobDescriptor()) .thenReturn(new BlobDescriptor(mockDescriptorDigest)); } @Test - public void test_smokeTest() throws LayerPropertyNotFoundException { + void test_smokeTest() throws LayerPropertyNotFoundException { Image image = Image.builder(V22ManifestTemplate.class) .setCreated(Instant.ofEpochSecond(10000)) @@ -80,7 +83,7 @@ public void test_smokeTest() throws LayerPropertyNotFoundException { } @Test - public void testDefaults() { + void testDefaults() { Image image = Image.builder(V22ManifestTemplate.class).build(); Assert.assertEquals("amd64", image.getArchitecture()); Assert.assertEquals("linux", image.getOs()); @@ -89,7 +92,7 @@ public void testDefaults() { } @Test - public void testOsArch() { + void testOsArch() { Image image = Image.builder(V22ManifestTemplate.class).setArchitecture("wasm").setOs("js").build(); Assert.assertEquals("wasm", image.getArchitecture()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/LayerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/LayerTest.java index 5d062e08f36..66f91f662bb 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/LayerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/LayerTest.java @@ -19,21 +19,24 @@ import com.google.cloud.tools.jib.api.DescriptorDigest; import com.google.cloud.tools.jib.blob.BlobDescriptor; import org.junit.Assert; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link Layer}. */ -@RunWith(MockitoJUnitRunner.class) -public class LayerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class LayerTest { @Mock private DescriptorDigest mockDescriptorDigest; @Mock private BlobDescriptor mockBlobDescriptor; @Mock private DescriptorDigest mockDiffId; @Test - public void testNew_reference() throws LayerPropertyNotFoundException { + void testNew_reference() throws LayerPropertyNotFoundException { Layer layer = new ReferenceLayer(mockBlobDescriptor, mockDiffId); try { @@ -48,7 +51,7 @@ public void testNew_reference() throws LayerPropertyNotFoundException { } @Test - public void testNew_digestOnly() throws LayerPropertyNotFoundException { + void testNew_digestOnly() throws LayerPropertyNotFoundException { Layer layer = new DigestOnlyLayer(mockDescriptorDigest); try { diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/ReproducibleLayerBuilderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/ReproducibleLayerBuilderTest.java index d3860184aed..eafb942418f 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/ReproducibleLayerBuilderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/ReproducibleLayerBuilderTest.java @@ -40,12 +40,11 @@ import java.time.Instant; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; -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; /** Tests for {@link ReproducibleLayerBuilder}. */ -public class ReproducibleLayerBuilderTest { +class ReproducibleLayerBuilderTest { /** * Verifies the correctness of the next {@link TarArchiveEntry} in the {@link @@ -92,10 +91,10 @@ private static FileEntry defaultLayerEntry(Path source, AbsoluteUnixPath destina FileEntriesLayer.DEFAULT_MODIFICATION_TIME); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testBuild() throws URISyntaxException, IOException { + void testBuild() throws URISyntaxException, IOException { Path layerDirectory = Paths.get(Resources.getResource("core/layer").toURI()); Path blobA = Paths.get(Resources.getResource("core/blobA").toURI()); @@ -112,7 +111,7 @@ public void testBuild() throws URISyntaxException, IOException { // Writes the layer tar to a temporary file. Blob unwrittenBlob = layerBuilder.build(); - Path temporaryFile = temporaryFolder.newFile().toPath(); + Path temporaryFile = Files.createTempFile(temporaryFolder, "jib", "test"); try (OutputStream temporaryFileOutputStream = new BufferedOutputStream(Files.newOutputStream(temporaryFile))) { unwrittenBlob.writeTo(temporaryFileOutputStream); @@ -147,8 +146,8 @@ public void testBuild() throws URISyntaxException, IOException { } @Test - public void testToBlob_reproducibility() throws IOException { - Path testRoot = temporaryFolder.getRoot().toPath(); + void testToBlob_reproducibility() throws IOException { + Path testRoot = temporaryFolder; Path root1 = Files.createDirectories(testRoot.resolve("files1")); Path root2 = Files.createDirectories(testRoot.resolve("files2")); @@ -186,8 +185,8 @@ public void testToBlob_reproducibility() throws IOException { } @Test - public void testBuild_parentDirBehavior() throws IOException { - Path testRoot = temporaryFolder.getRoot().toPath(); + void testBuild_parentDirBehavior() throws IOException { + Path testRoot = temporaryFolder; // the path doesn't really matter on source files, but these are structured Path parent = Files.createDirectories(testRoot.resolve("dirA")); @@ -227,7 +226,7 @@ public void testBuild_parentDirBehavior() throws IOException { Instant.ofEpochSecond(50)))) .build(); - Path tarFile = temporaryFolder.newFile().toPath(); + Path tarFile = Files.createTempFile(temporaryFolder, "jib", "test"); try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(tarFile))) { layer.writeTo(out); } @@ -282,15 +281,16 @@ public void testBuild_parentDirBehavior() throws IOException { } @Test - public void testBuild_timestampDefault() throws IOException { - Path file = createFile(temporaryFolder.getRoot().toPath(), "fileA", "some content", 54321); + void testBuild_timestampDefault() throws IOException { + Path file = createFile(temporaryFolder, "fileA", "some content", 54321); Blob blob = new ReproducibleLayerBuilder( ImmutableList.of(defaultLayerEntry(file, AbsoluteUnixPath.get("/fileA")))) .build(); - Path tarFile = temporaryFolder.newFile().toPath(); + Path tarFile = Files.createTempFile(temporaryFolder, "jib", "test"); + ; try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(tarFile))) { blob.writeTo(out); } @@ -303,8 +303,8 @@ public void testBuild_timestampDefault() throws IOException { } @Test - public void testBuild_timestampNonDefault() throws IOException { - Path file = createFile(temporaryFolder.getRoot().toPath(), "fileA", "some content", 54321); + void testBuild_timestampNonDefault() throws IOException { + Path file = createFile(temporaryFolder, "fileA", "some content", 54321); Blob blob = new ReproducibleLayerBuilder( @@ -316,7 +316,8 @@ public void testBuild_timestampNonDefault() throws IOException { Instant.ofEpochSecond(123)))) .build(); - Path tarFile = temporaryFolder.newFile().toPath(); + Path tarFile = Files.createTempFile(temporaryFolder, "jib", "test"); + ; try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(tarFile))) { blob.writeTo(out); } @@ -329,8 +330,8 @@ public void testBuild_timestampNonDefault() throws IOException { } @Test - public void testBuild_permissions() throws IOException { - Path testRoot = temporaryFolder.getRoot().toPath(); + void testBuild_permissions() throws IOException { + Path testRoot = temporaryFolder; Path folder = Files.createDirectories(testRoot.resolve("files1")); Path fileA = createFile(testRoot, "fileA", "abc", 54321); Path fileB = createFile(testRoot, "fileB", "def", 54321); @@ -351,7 +352,8 @@ public void testBuild_permissions() throws IOException { FileEntriesLayer.DEFAULT_MODIFICATION_TIME))) .build(); - Path tarFile = temporaryFolder.newFile().toPath(); + Path tarFile = Files.createTempFile(temporaryFolder, "jib", "test"); + ; try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(tarFile))) { blob.writeTo(out); } @@ -369,8 +371,9 @@ public void testBuild_permissions() throws IOException { } @Test - public void testBuild_ownership() throws IOException { - Path testRoot = temporaryFolder.getRoot().toPath(); + @SuppressWarnings("java:S5961") + void testBuild_ownership() throws IOException { + Path testRoot = temporaryFolder; Path someFile = createFile(testRoot, "someFile", "content", 54321); Blob blob = @@ -427,7 +430,8 @@ public void testBuild_ownership() throws IOException { "user:group"))) .build(); - Path tarFile = temporaryFolder.newFile().toPath(); + Path tarFile = Files.createTempFile(temporaryFolder, "jib", "test"); + ; try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(tarFile))) { blob.writeTo(out); } diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ContainerConfigurationTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ContainerConfigurationTemplateTest.java index b5de33f79b0..b7e0ccd2333 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ContainerConfigurationTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ContainerConfigurationTemplateTest.java @@ -32,13 +32,13 @@ import java.time.Instant; import java.util.Arrays; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ContainerConfigurationTemplate}. */ -public class ContainerConfigurationTemplateTest { +class ContainerConfigurationTemplateTest { @Test - public void testToJson() throws IOException, URISyntaxException, DigestException { + void testToJson() throws IOException, URISyntaxException, DigestException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/containerconfig.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -94,7 +94,7 @@ public void testToJson() throws IOException, URISyntaxException, DigestException } @Test - public void testFromJson() throws IOException, URISyntaxException, DigestException { + void testFromJson() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/containerconfig.json").toURI()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ImageToJsonTranslatorTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ImageToJsonTranslatorTest.java index 7b5e5fb4269..ba5ef6e772b 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ImageToJsonTranslatorTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ImageToJsonTranslatorTest.java @@ -46,10 +46,10 @@ import java.util.Arrays; import java.util.Map; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ImageToJsonTranslator}. */ -public class ImageToJsonTranslatorTest { +class ImageToJsonTranslatorTest { private ImageToJsonTranslator imageToJsonTranslator; @@ -118,8 +118,7 @@ public DescriptorDigest getDiffId() throws LayerPropertyNotFoundException { } @Test - public void testGetContainerConfiguration() - throws IOException, URISyntaxException, DigestException { + void testGetContainerConfiguration() throws IOException, URISyntaxException, DigestException { setUp(V22ManifestTemplate.class); // Loads the expected JSON string. @@ -133,19 +132,19 @@ public void testGetContainerConfiguration() } @Test - public void testGetManifest_v22() throws URISyntaxException, IOException, DigestException { + void testGetManifest_v22() throws URISyntaxException, IOException, DigestException { setUp(V22ManifestTemplate.class); testGetManifest(V22ManifestTemplate.class, "core/json/translated_v22manifest.json"); } @Test - public void testGetManifest_oci() throws URISyntaxException, IOException, DigestException { + void testGetManifest_oci() throws URISyntaxException, IOException, DigestException { setUp(OciManifestTemplate.class); testGetManifest(OciManifestTemplate.class, "core/json/translated_ocimanifest.json"); } @Test - public void testPortListToMap() { + void testPortListToMap() { ImmutableSet input = ImmutableSet.of(Port.tcp(1000), Port.udp(2000)); ImmutableSortedMap> expected = ImmutableSortedMap.of("1000/tcp", ImmutableMap.of(), "2000/udp", ImmutableMap.of()); @@ -153,7 +152,7 @@ public void testPortListToMap() { } @Test - public void testVolumeListToMap() { + void testVolumeListToMap() { ImmutableSet input = ImmutableSet.of( AbsoluteUnixPath.get("/var/job-result-data"), @@ -165,7 +164,7 @@ public void testVolumeListToMap() { } @Test - public void testEnvironmentMapToList() { + void testEnvironmentMapToList() { ImmutableMap input = ImmutableMap.of("NAME1", "VALUE1", "NAME2", "VALUE2"); ImmutableList expected = ImmutableList.of("NAME1=VALUE1", "NAME2=VALUE2"); Assert.assertEquals(expected, ImageToJsonTranslator.environmentMapToList(input)); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/JsonToImageTranslatorTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/JsonToImageTranslatorTest.java index 5beabb6b940..aa50d5dd346 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/JsonToImageTranslatorTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/JsonToImageTranslatorTest.java @@ -40,13 +40,13 @@ import java.util.Map; import java.util.regex.Matcher; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link JsonToImageTranslator}. */ -public class JsonToImageTranslatorTest { +class JsonToImageTranslatorTest { @Test - public void testToImage_v21() + void testToImage_v21() throws IOException, LayerPropertyNotFoundException, DigestException, URISyntaxException, BadContainerConfigurationFormatException { // Loads the JSON string. @@ -72,21 +72,21 @@ public void testToImage_v21() } @Test - public void testToImage_v22() + void testToImage_v22() throws IOException, LayerPropertyNotFoundException, LayerCountMismatchException, DigestException, URISyntaxException, BadContainerConfigurationFormatException { testToImage_buildable("core/json/v22manifest.json", V22ManifestTemplate.class); } @Test - public void testToImage_oci() + void testToImage_oci() throws IOException, LayerPropertyNotFoundException, LayerCountMismatchException, DigestException, URISyntaxException, BadContainerConfigurationFormatException { testToImage_buildable("core/json/ocimanifest.json", OciManifestTemplate.class); } @Test - public void testToImage_canParseTimestampWithOffset() + void testToImage_canParseTimestampWithOffset() throws IOException, LayerPropertyNotFoundException, URISyntaxException, LayerCountMismatchException, BadContainerConfigurationFormatException { Path containerConfigJson = @@ -109,7 +109,7 @@ public void testToImage_canParseTimestampWithOffset() } @Test - public void testPortMapToList() throws BadContainerConfigurationFormatException { + void testPortMapToList() throws BadContainerConfigurationFormatException { ImmutableSortedMap> input = ImmutableSortedMap.of( "1000", @@ -138,7 +138,7 @@ public void testPortMapToList() throws BadContainerConfigurationFormatException } @Test - public void testVolumeMapToList() throws BadContainerConfigurationFormatException { + void testVolumeMapToList() throws BadContainerConfigurationFormatException { ImmutableSortedMap> input = ImmutableSortedMap.of( "/var/job-result-data", ImmutableMap.of(), "/var/log/my-app-logs", ImmutableMap.of()); @@ -164,7 +164,7 @@ public void testVolumeMapToList() throws BadContainerConfigurationFormatExceptio } @Test - public void testJsonToImageTranslatorRegex() { + void testJsonToImageTranslatorRegex() { assertGoodEnvironmentPattern("NAME=VALUE", "NAME", "VALUE"); assertGoodEnvironmentPattern("A1203921=www=ww", "A1203921", "www=ww"); assertGoodEnvironmentPattern("&*%(&#$(*@(%&@$*$(=", "&*%(&#$(*@(%&@$*$(", ""); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ManifestListGeneratorTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ManifestListGeneratorTest.java index 3c7a15e2ac2..957c06a70ad 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ManifestListGeneratorTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/ManifestListGeneratorTest.java @@ -21,18 +21,18 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link ManifestListGenerator}. */ -public class ManifestListGeneratorTest { +class ManifestListGeneratorTest { private Image image1; private Image image2; private ManifestListGenerator manifestListGenerator; - @Before - public void setUp() { + @BeforeEach + void setUp() { image1 = Image.builder(V22ManifestTemplate.class).setArchitecture("amd64").setOs("linux").build(); image2 = @@ -41,7 +41,7 @@ public void setUp() { } @Test - public void testGetManifestListTemplate() throws IOException { + void testGetManifestListTemplate() throws IOException { // Expected Manifest List JSON // { @@ -83,7 +83,7 @@ public void testGetManifestListTemplate() throws IOException { } @Test - public void testGetManifestListTemplate_emptyImagesList() throws IOException { + void testGetManifestListTemplate_emptyImagesList() throws IOException { try { new ManifestListGenerator(Collections.emptyList()) .getManifestListTemplate(V22ManifestTemplate.class); @@ -94,7 +94,7 @@ public void testGetManifestListTemplate_emptyImagesList() throws IOException { } @Test - public void testGetManifestListTemplate_unsupportedImageFormat() throws IOException { + void testGetManifestListTemplate_unsupportedImageFormat() throws IOException { try { new ManifestListGenerator(Arrays.asList(image1, image2)) .getManifestListTemplate(OciManifestTemplate.class); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciIndexTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciIndexTemplateTest.java index f95a0643064..1033e9d5d8d 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciIndexTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciIndexTemplateTest.java @@ -28,13 +28,13 @@ import java.nio.file.Paths; import java.security.DigestException; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link OciIndexTemplate}. */ -public class OciIndexTemplateTest { +class OciIndexTemplateTest { @Test - public void testToJson() throws DigestException, IOException, URISyntaxException { + void testToJson() throws DigestException, IOException, URISyntaxException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/ociindex.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -54,7 +54,7 @@ public void testToJson() throws DigestException, IOException, URISyntaxException } @Test - public void testFromJson() throws IOException, URISyntaxException, DigestException { + void testFromJson() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/ociindex.json").toURI()); @@ -76,7 +76,7 @@ public void testFromJson() throws IOException, URISyntaxException, DigestExcepti } @Test - public void testToJsonWithPlatform() throws DigestException, IOException, URISyntaxException { + void testToJsonWithPlatform() throws DigestException, IOException, URISyntaxException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/ociindex_platforms.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -108,7 +108,7 @@ public void testToJsonWithPlatform() throws DigestException, IOException, URISyn } @Test - public void testFromJsonWithPlatform() throws IOException, URISyntaxException, DigestException { + void testFromJsonWithPlatform() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/ociindex_platforms.json").toURI()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciManifestTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciManifestTemplateTest.java index 6eaac9c4bf4..8c8712824ca 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciManifestTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/OciManifestTemplateTest.java @@ -27,13 +27,13 @@ import java.nio.file.Paths; import java.security.DigestException; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link OciManifestTemplate}. */ -public class OciManifestTemplateTest { +class OciManifestTemplateTest { @Test - public void testToJson() throws DigestException, IOException, URISyntaxException { + void testToJson() throws DigestException, IOException, URISyntaxException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/ocimanifest.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -56,7 +56,7 @@ public void testToJson() throws DigestException, IOException, URISyntaxException } @Test - public void testFromJson() throws IOException, URISyntaxException, DigestException { + void testFromJson() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/ocimanifest.json").toURI()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V21ManifestTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V21ManifestTemplateTest.java index a2f33c1b5cd..14598cc4d52 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V21ManifestTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V21ManifestTemplateTest.java @@ -26,13 +26,13 @@ import java.security.DigestException; import java.util.Arrays; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link V21ManifestTemplate}. */ -public class V21ManifestTemplateTest { +class V21ManifestTemplateTest { @Test - public void testFromJson() throws URISyntaxException, IOException, DigestException { + void testFromJson() throws URISyntaxException, IOException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/v21manifest.json").toURI()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestListTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestListTemplateTest.java index c04ab5f2912..af2f0e69cd6 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestListTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestListTemplateTest.java @@ -25,12 +25,12 @@ import java.nio.file.Paths; import java.util.List; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class V22ManifestListTemplateTest { +class V22ManifestListTemplateTest { @Test - public void testFromJson() throws IOException, URISyntaxException { + void testFromJson() throws IOException, URISyntaxException { Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest_list.json").toURI()); V22ManifestListTemplate manifestListJson = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestTemplateTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestTemplateTest.java index 91955bc9019..d2e9dd8a3f5 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestTemplateTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/image/json/V22ManifestTemplateTest.java @@ -31,13 +31,13 @@ import java.util.Arrays; import java.util.List; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link V22ManifestTemplate}. */ -public class V22ManifestTemplateTest { +class V22ManifestTemplateTest { @Test - public void testToJson() throws DigestException, IOException, URISyntaxException { + void testToJson() throws DigestException, IOException, URISyntaxException { // Loads the expected JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -60,7 +60,7 @@ public void testToJson() throws DigestException, IOException, URISyntaxException } @Test - public void testFromJson() throws IOException, URISyntaxException, DigestException { + void testFromJson() throws IOException, URISyntaxException, DigestException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest.json").toURI()); @@ -84,7 +84,7 @@ public void testFromJson() throws IOException, URISyntaxException, DigestExcepti } @Test - public void testFromJson_optionalProperties() throws IOException, URISyntaxException { + void testFromJson_optionalProperties() throws IOException, URISyntaxException { Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest_optional_properties.json").toURI()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/json/JsonTemplateMapperTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/json/JsonTemplateMapperTest.java index 6723a84c0b5..112ae3fccb3 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/json/JsonTemplateMapperTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/json/JsonTemplateMapperTest.java @@ -32,10 +32,10 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link JsonTemplateMapper}. */ -public class JsonTemplateMapperTest { +class JsonTemplateMapperTest { private static class TestJson implements JsonTemplate { private int number; @@ -54,7 +54,7 @@ private static class InnerObject implements JsonTemplate { } @Test - public void testWriteJson() throws DigestException, IOException, URISyntaxException { + void testWriteJson() throws DigestException, IOException, URISyntaxException { Path jsonFile = Paths.get(Resources.getResource("core/json/basic.json").toURI()); String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -90,7 +90,7 @@ public void testWriteJson() throws DigestException, IOException, URISyntaxExcept } @Test - public void testReadJsonWithLock() throws IOException, URISyntaxException, DigestException { + void testReadJsonWithLock() throws IOException, URISyntaxException, DigestException { Path jsonFile = Paths.get(Resources.getResource("core/json/basic.json").toURI()); // Deserializes into a metadata JSON object. @@ -120,7 +120,7 @@ public void testReadJsonWithLock() throws IOException, URISyntaxException, Diges } @Test - public void testReadListOfJson() throws IOException, URISyntaxException, DigestException { + void testReadListOfJson() throws IOException, URISyntaxException, DigestException { Path jsonFile = Paths.get(Resources.getResource("core/json/basic_list.json").toURI()); String jsonString = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -148,7 +148,7 @@ public void testReadListOfJson() throws IOException, URISyntaxException, DigestE } @Test - public void testToBlob_listOfJson() throws IOException, URISyntaxException { + void testToBlob_listOfJson() throws IOException, URISyntaxException { Path jsonFile = Paths.get(Resources.getResource("core/json/basic_list.json").toURI()); String jsonString = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8); @@ -158,7 +158,7 @@ public void testToBlob_listOfJson() throws IOException, URISyntaxException { } @Test - public void testReadJson_inputStream() throws IOException { + void testReadJson_inputStream() throws IOException { String testJson = "{\"number\":3, \"text\":\"cool\"}"; ByteArrayInputStream in = new ByteArrayInputStream(testJson.getBytes(StandardCharsets.UTF_8)); TestJson json = JsonTemplateMapper.readJson(in, TestJson.class); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/AuthenticationMethodRetrieverTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/AuthenticationMethodRetrieverTest.java index 44d3fd7c9f6..363b8a206c8 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/AuthenticationMethodRetrieverTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/AuthenticationMethodRetrieverTest.java @@ -28,15 +28,18 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link AuthenticationMethodRetriever}. */ -@RunWith(MockitoJUnitRunner.class) -public class AuthenticationMethodRetrieverTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AuthenticationMethodRetrieverTest { @Mock private ResponseException mockResponseException; @Mock private HttpHeaders mockHeaders; @@ -49,42 +52,42 @@ public class AuthenticationMethodRetrieverTest { fakeRegistryEndpointRequestProperties, "user-agent", httpClient); @Test - public void testGetContent() { + void testGetContent() { Assert.assertNull(testAuthenticationMethodRetriever.getContent()); } @Test - public void testGetAccept() { + void testGetAccept() { Assert.assertEquals(0, testAuthenticationMethodRetriever.getAccept().size()); } @Test - public void testHandleResponse() { + void testHandleResponse() { Assert.assertFalse( testAuthenticationMethodRetriever.handleResponse(Mockito.mock(Response.class)).isPresent()); } @Test - public void testGetApiRoute() throws MalformedURLException { + void testGetApiRoute() throws MalformedURLException { Assert.assertEquals( new URL("http://someApiBase/"), testAuthenticationMethodRetriever.getApiRoute("http://someApiBase/")); } @Test - public void testGetHttpMethod() { + void testGetHttpMethod() { Assert.assertEquals(HttpMethods.GET, testAuthenticationMethodRetriever.getHttpMethod()); } @Test - public void testGetActionDescription() { + void testGetActionDescription() { Assert.assertEquals( "retrieve authentication method for someServerUrl", testAuthenticationMethodRetriever.getActionDescription()); } @Test - public void testHandleHttpResponseException_invalidStatusCode() throws RegistryErrorException { + void testHandleHttpResponseException_invalidStatusCode() throws RegistryErrorException { Mockito.when(mockResponseException.getStatusCode()).thenReturn(-1); try { @@ -98,7 +101,7 @@ public void testHandleHttpResponseException_invalidStatusCode() throws RegistryE } @Test - public void testHandleHttpResponseException_noHeader() throws ResponseException { + void testHandleHttpResponseException_noHeader() throws ResponseException { Mockito.when(mockResponseException.getStatusCode()) .thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); Mockito.when(mockResponseException.getHeaders()).thenReturn(mockHeaders); @@ -116,7 +119,7 @@ public void testHandleHttpResponseException_noHeader() throws ResponseException } @Test - public void testHandleHttpResponseException_badAuthenticationMethod() throws ResponseException { + void testHandleHttpResponseException_badAuthenticationMethod() throws ResponseException { String authenticationMethod = "bad authentication method"; Mockito.when(mockResponseException.getStatusCode()) @@ -138,7 +141,7 @@ public void testHandleHttpResponseException_badAuthenticationMethod() throws Res } @Test - public void testHandleHttpResponseException_pass() + void testHandleHttpResponseException_pass() throws RegistryErrorException, ResponseException, MalformedURLException { String authenticationMethod = "Bearer realm=\"https://somerealm\",service=\"someservice\",scope=\"somescope\""; diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobCheckerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobCheckerTest.java index 49cb7fa31db..99bee373f54 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobCheckerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobCheckerTest.java @@ -31,16 +31,19 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BlobChecker}. */ -@RunWith(MockitoJUnitRunner.class) -public class BlobCheckerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BlobCheckerTest { @Mock private Response mockResponse; @@ -50,8 +53,8 @@ public class BlobCheckerTest { private BlobChecker testBlobChecker; private DescriptorDigest fakeDigest; - @Before - public void setUpFakes() throws DigestException { + @BeforeEach + void setUpFakes() throws DigestException { fakeDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -59,7 +62,7 @@ public void setUpFakes() throws DigestException { } @Test - public void testHandleResponse() throws RegistryErrorException { + void testHandleResponse() throws RegistryErrorException { Mockito.when(mockResponse.getContentLength()).thenReturn(0L); BlobDescriptor expectedBlobDescriptor = new BlobDescriptor(0, fakeDigest); @@ -69,7 +72,7 @@ public void testHandleResponse() throws RegistryErrorException { } @Test - public void testHandleResponse_noContentLength() { + void testHandleResponse_noContentLength() { Mockito.when(mockResponse.getContentLength()).thenReturn(-1L); try { @@ -83,7 +86,7 @@ public void testHandleResponse_noContentLength() { } @Test - public void testHandleHttpResponseException() throws IOException { + void testHandleHttpResponseException() throws IOException { ResponseException mockResponseException = Mockito.mock(ResponseException.class); Mockito.when(mockResponseException.getStatusCode()) .thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND); @@ -99,7 +102,7 @@ public void testHandleHttpResponseException() throws IOException { } @Test - public void testHandleHttpResponseException_hasOtherErrors() throws IOException { + void testHandleHttpResponseException_hasOtherErrors() throws IOException { ResponseException mockResponseException = Mockito.mock(ResponseException.class); Mockito.when(mockResponseException.getStatusCode()) .thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND); @@ -121,7 +124,7 @@ public void testHandleHttpResponseException_hasOtherErrors() throws IOException } @Test - public void testHandleHttpResponseException_notBlobUnknown() throws IOException { + void testHandleHttpResponseException_notBlobUnknown() throws IOException { ResponseException mockResponseException = Mockito.mock(ResponseException.class); Mockito.when(mockResponseException.getStatusCode()) .thenReturn(HttpStatusCodes.STATUS_CODE_NOT_FOUND); @@ -140,7 +143,7 @@ public void testHandleHttpResponseException_notBlobUnknown() throws IOException } @Test - public void testHandleHttpResponseException_invalidStatusCode() { + void testHandleHttpResponseException_invalidStatusCode() { ResponseException mockResponseException = Mockito.mock(ResponseException.class); Mockito.when(mockResponseException.getStatusCode()).thenReturn(-1); @@ -154,31 +157,31 @@ public void testHandleHttpResponseException_invalidStatusCode() { } @Test - public void testGetApiRoute() throws MalformedURLException { + void testGetApiRoute() throws MalformedURLException { Assert.assertEquals( new URL("http://someApiBase/someImageName/blobs/" + fakeDigest), testBlobChecker.getApiRoute("http://someApiBase/")); } @Test - public void testGetContent() { + void testGetContent() { Assert.assertNull(testBlobChecker.getContent()); } @Test - public void testGetAccept() { + void testGetAccept() { Assert.assertEquals(0, testBlobChecker.getAccept().size()); } @Test - public void testGetActionDescription() { + void testGetActionDescription() { Assert.assertEquals( "check BLOB exists for someServerUrl/someImageName with digest " + fakeDigest, testBlobChecker.getActionDescription()); } @Test - public void testGetHttpMethod() { + void testGetHttpMethod() { Assert.assertEquals("HEAD", testBlobChecker.getHttpMethod()); } } diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPullerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPullerTest.java index 09d9f09e39a..4b2e980b68f 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPullerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPullerTest.java @@ -30,15 +30,18 @@ import java.security.DigestException; import java.util.concurrent.atomic.LongAdder; import org.junit.Assert; -import org.junit.Before; -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.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BlobPuller}. */ -@RunWith(MockitoJUnitRunner.class) -public class BlobPullerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BlobPullerTest { private final RegistryEndpointRequestProperties fakeRegistryEndpointRequestProperties = new RegistryEndpointRequestProperties("someServerUrl", "someImageName"); @@ -50,8 +53,8 @@ public class BlobPullerTest { private BlobPuller testBlobPuller; - @Before - public void setUpFakes() throws DigestException { + @BeforeEach + void setUpFakes() throws DigestException { fakeDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -66,7 +69,7 @@ public void setUpFakes() throws DigestException { } @Test - public void testHandleResponse() throws IOException, UnexpectedBlobDigestException { + void testHandleResponse() throws IOException, UnexpectedBlobDigestException { InputStream blobContent = new ByteArrayInputStream("some BLOB content".getBytes(StandardCharsets.UTF_8)); DescriptorDigest testBlobDigest = Digests.computeDigest(blobContent).getDigest(); @@ -93,7 +96,7 @@ public void testHandleResponse() throws IOException, UnexpectedBlobDigestExcepti } @Test - public void testHandleResponse_unexpectedDigest() throws IOException { + void testHandleResponse_unexpectedDigest() throws IOException { InputStream blobContent = new ByteArrayInputStream("some BLOB content".getBytes(StandardCharsets.UTF_8)); DescriptorDigest testBlobDigest = Digests.computeDigest(blobContent).getDigest(); @@ -118,31 +121,31 @@ public void testHandleResponse_unexpectedDigest() throws IOException { } @Test - public void testGetApiRoute() throws MalformedURLException { + void testGetApiRoute() throws MalformedURLException { Assert.assertEquals( new URL("http://someApiBase/someImageName/blobs/" + fakeDigest), testBlobPuller.getApiRoute("http://someApiBase/")); } @Test - public void testGetActionDescription() { + void testGetActionDescription() { Assert.assertEquals( "pull BLOB for someServerUrl/someImageName with digest " + fakeDigest, testBlobPuller.getActionDescription()); } @Test - public void testGetHttpMethod() { + void testGetHttpMethod() { Assert.assertEquals("GET", testBlobPuller.getHttpMethod()); } @Test - public void testGetContent() { + void testGetContent() { Assert.assertNull(testBlobPuller.getContent()); } @Test - public void testGetAccept() { + void testGetAccept() { Assert.assertEquals(0, testBlobPuller.getAccept().size()); } } diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPusherTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPusherTest.java index 7950a5f822b..7666667dd34 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPusherTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/BlobPusherTest.java @@ -35,16 +35,19 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link BlobPusher}. */ -@RunWith(MockitoJUnitRunner.class) -public class BlobPusherTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BlobPusherTest { private static final String TEST_BLOB_CONTENT = "some BLOB content"; private static final Blob TEST_BLOB = Blobs.from(TEST_BLOB_CONTENT); @@ -55,8 +58,8 @@ public class BlobPusherTest { private DescriptorDigest fakeDescriptorDigest; private BlobPusher testBlobPusher; - @Before - public void setUpFakes() throws DigestException { + @BeforeEach + void setUpFakes() throws DigestException { fakeDescriptorDigest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); @@ -69,23 +72,23 @@ public void setUpFakes() throws DigestException { } @Test - public void testInitializer_getContent() { + void testInitializer_getContent() { Assert.assertNull(testBlobPusher.initializer().getContent()); } @Test - public void testGetAccept() { + void testGetAccept() { Assert.assertEquals(0, testBlobPusher.initializer().getAccept().size()); } @Test - public void testInitializer_handleResponse_created() throws IOException, RegistryException { + void testInitializer_handleResponse_created() throws IOException, RegistryException { Mockito.when(mockResponse.getStatusCode()).thenReturn(201); // Created Assert.assertFalse(testBlobPusher.initializer().handleResponse(mockResponse).isPresent()); } @Test - public void testInitializer_handleResponse_accepted() throws IOException, RegistryException { + void testInitializer_handleResponse_accepted() throws IOException, RegistryException { Mockito.when(mockResponse.getStatusCode()).thenReturn(202); // Accepted Mockito.when(mockResponse.getHeader("Location")) .thenReturn(Collections.singletonList("location")); @@ -97,7 +100,7 @@ public void testInitializer_handleResponse_accepted() throws IOException, Regist } @Test - public void testInitializer_handleResponse_accepted_multipleLocations() + void testInitializer_handleResponse_accepted_multipleLocations() throws IOException, RegistryException { Mockito.when(mockResponse.getStatusCode()).thenReturn(202); // Accepted Mockito.when(mockResponse.getHeader("Location")) @@ -114,7 +117,7 @@ public void testInitializer_handleResponse_accepted_multipleLocations() } @Test - public void testInitializer_handleResponse_unrecognized() throws IOException, RegistryException { + void testInitializer_handleResponse_unrecognized() throws IOException, RegistryException { Mockito.when(mockResponse.getStatusCode()).thenReturn(-1); // Unrecognized try { testBlobPusher.initializer().handleResponse(mockResponse); @@ -127,14 +130,14 @@ public void testInitializer_handleResponse_unrecognized() throws IOException, Re } @Test - public void testInitializer_getApiRoute_nullSource() throws MalformedURLException { + void testInitializer_getApiRoute_nullSource() throws MalformedURLException { Assert.assertEquals( new URL("http://someApiBase/someImageName/blobs/uploads/"), testBlobPusher.initializer().getApiRoute("http://someApiBase/")); } @Test - public void testInitializer_getApiRoute_sameSource() throws MalformedURLException { + void testInitializer_getApiRoute_sameSource() throws MalformedURLException { testBlobPusher = new BlobPusher( new RegistryEndpointRequestProperties("someServerUrl", "someImageName"), @@ -151,19 +154,19 @@ public void testInitializer_getApiRoute_sameSource() throws MalformedURLExceptio } @Test - public void testInitializer_getHttpMethod() { + void testInitializer_getHttpMethod() { Assert.assertEquals("POST", testBlobPusher.initializer().getHttpMethod()); } @Test - public void testInitializer_getActionDescription() { + void testInitializer_getActionDescription() { Assert.assertEquals( "push BLOB for someServerUrl/someImageName with digest " + fakeDescriptorDigest, testBlobPusher.initializer().getActionDescription()); } @Test - public void testWriter_getContent() throws IOException { + void testWriter_getContent() throws IOException { LongAdder byteCount = new LongAdder(); BlobHttpContent body = testBlobPusher.writer(mockUrl, byteCount::add).getContent(); @@ -179,12 +182,12 @@ public void testWriter_getContent() throws IOException { } @Test - public void testWriter_GetAccept() { + void testWriter_GetAccept() { Assert.assertEquals(0, testBlobPusher.writer(mockUrl, ignored -> {}).getAccept().size()); } @Test - public void testWriter_handleResponse() throws IOException, RegistryException { + void testWriter_handleResponse() throws IOException, RegistryException { Mockito.when(mockResponse.getHeader("Location")) .thenReturn(Collections.singletonList("https://somenewurl/location")); GenericUrl requestUrl = new GenericUrl("https://someurl"); @@ -195,53 +198,53 @@ public void testWriter_handleResponse() throws IOException, RegistryException { } @Test - public void testWriter_getApiRoute() throws MalformedURLException { + void testWriter_getApiRoute() throws MalformedURLException { URL fakeUrl = new URL("http://someurl"); Assert.assertEquals(fakeUrl, testBlobPusher.writer(fakeUrl, ignored -> {}).getApiRoute("")); } @Test - public void testWriter_getHttpMethod() { + void testWriter_getHttpMethod() { Assert.assertEquals("PATCH", testBlobPusher.writer(mockUrl, ignored -> {}).getHttpMethod()); } @Test - public void testWriter_getActionDescription() { + void testWriter_getActionDescription() { Assert.assertEquals( "push BLOB for someServerUrl/someImageName with digest " + fakeDescriptorDigest, testBlobPusher.writer(mockUrl, ignored -> {}).getActionDescription()); } @Test - public void testCommitter_getContent() { + void testCommitter_getContent() { Assert.assertNull(testBlobPusher.committer(mockUrl).getContent()); } @Test - public void testCommitter_GetAccept() { + void testCommitter_GetAccept() { Assert.assertEquals(0, testBlobPusher.committer(mockUrl).getAccept().size()); } @Test - public void testCommitter_handleResponse() throws IOException, RegistryException { + void testCommitter_handleResponse() throws IOException, RegistryException { Assert.assertNull( testBlobPusher.committer(mockUrl).handleResponse(Mockito.mock(Response.class))); } @Test - public void testCommitter_getApiRoute() throws MalformedURLException { + void testCommitter_getApiRoute() throws MalformedURLException { Assert.assertEquals( new URL("https://someurl?somequery=somevalue&digest=" + fakeDescriptorDigest), testBlobPusher.committer(new URL("https://someurl?somequery=somevalue")).getApiRoute("")); } @Test - public void testCommitter_getHttpMethod() { + void testCommitter_getHttpMethod() { Assert.assertEquals("PUT", testBlobPusher.committer(mockUrl).getHttpMethod()); } @Test - public void testCommitter_getActionDescription() { + void testCommitter_getActionDescription() { Assert.assertEquals( "push BLOB for someServerUrl/someImageName with digest " + fakeDescriptorDigest, testBlobPusher.committer(mockUrl).getActionDescription()); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/DockerRegistryBearerTokenTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/DockerRegistryBearerTokenTest.java index 06558ed94ed..b20551d2861 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/DockerRegistryBearerTokenTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/DockerRegistryBearerTokenTest.java @@ -21,8 +21,8 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * Tests for {@link RegistryClient} around handling of Docker Registry Bearer Tokens. @@ -30,9 +30,9 @@ *

JWTs were generated from jwt.io's JWT Debugger. Set the * algorithm to HS256, and paste the JSON shown as the Payload. */ -public class DockerRegistryBearerTokenTest { +class DockerRegistryBearerTokenTest { @Test - public void testDecode_dockerToken() { + void testDecode_dockerToken() { // A genuine token from accessing docker.io's openjdk: // {"access":[{"type":"repository","name":"library/openjdk","actions":["pull"]}] // Generated by @@ -51,7 +51,7 @@ public void testDecode_dockerToken() { } @Test - public void testDecode_nonToken() { + void testDecode_nonToken() { String base64Text = Base64.getEncoder() .encodeToString("something other than a JWT token".getBytes(StandardCharsets.UTF_8)); @@ -60,7 +60,7 @@ public void testDecode_nonToken() { } @Test - public void testDecode_invalidToken_accessString() { + void testDecode_invalidToken_accessString() { // a JWT with an "access" field that is not an array: {"access": "string"} String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJzdHJpbmcifQ.12ODBkkfh6J79qEejxwlD5AfOa9mjObPCzOnUL75NSQ"; @@ -69,7 +69,7 @@ public void testDecode_invalidToken_accessString() { } @Test - public void testDecode_invalidToken_accessArray() { + void testDecode_invalidToken_accessArray() { // a JWT with an "access" field that is an array of non-claim objects: {"access":["string"]} String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOlsic3RyaW5nIl19.gWZ9J4sO_w0hIVVxrfuuUC2lNhqkU3P0_z46xMCXfwU"; @@ -78,8 +78,8 @@ public void testDecode_invalidToken_accessArray() { } @Test - @Ignore("Annotate AccessClaim.actions to disallow coercion of integers to strings") - public void testDecode_invalidToken_actionsArray() { + @Disabled("Annotate AccessClaim.actions to disallow coercion of integers to strings") + void testDecode_invalidToken_actionsArray() { // a JWT with an "access" field that is an action array of non-strings: // {"access":[{"type": "repository","name": "library/openjdk","actions":[1]}]} String jwt = @@ -89,7 +89,7 @@ public void testDecode_invalidToken_actionsArray() { } @Test - public void testDecode_invalidToken_randoJwt() { + void testDecode_invalidToken_randoJwt() { // the JWT example token from jwt.io String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; @@ -99,14 +99,14 @@ public void testDecode_invalidToken_randoJwt() { /** Basic credential should allow access to all. */ @Test - public void testCanAttemptBlobMount_basicCredential() { + void testCanAttemptBlobMount_basicCredential() { Authorization fixture = Authorization.fromBasicCredentials("foo", "bar"); Assert.assertTrue(RegistryClient.canAttemptBlobMount(fixture, "random")); Assert.assertTrue(RegistryClient.canAttemptBlobMount(fixture, "library/openjdk")); } @Test - public void testCanAttemptBlobMount_bearer_withToken() { + void testCanAttemptBlobMount_bearer_withToken() { // a synthetic token for accessing docker.io's openjdk with push and pull // {"access":[{"type":"repository","name":"library/openjdk","actions":["pull","push"]}]} String token = @@ -118,7 +118,7 @@ public void testCanAttemptBlobMount_bearer_withToken() { } @Test - public void testCanAttemptBlobMount_bearer_withNonToken() { + void testCanAttemptBlobMount_bearer_withNonToken() { // non-Docker Registry Bearer Tokens are assumed to allow access to all // the JWT example token from jwt.io String jwt = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ErrorResponseUtilTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ErrorResponseUtilTest.java index d5dd5ae0078..a2fff6f0648 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ErrorResponseUtilTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ErrorResponseUtilTest.java @@ -18,20 +18,23 @@ import com.google.cloud.tools.jib.http.ResponseException; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Test for {@link ErrorReponseUtil}. */ -@RunWith(MockitoJUnitRunner.class) -public class ErrorResponseUtilTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ErrorResponseUtilTest { @Mock private ResponseException responseException; @Test - public void testGetErrorCode_knownErrorCode() throws ResponseException { + void testGetErrorCode_knownErrorCode() throws ResponseException { Mockito.when(responseException.getContent()) .thenReturn( "{\"errors\":[{\"code\":\"MANIFEST_INVALID\",\"message\":\"manifest invalid\",\"detail\":{}}]}"); @@ -42,7 +45,7 @@ public void testGetErrorCode_knownErrorCode() throws ResponseException { /** An unknown {@link ErrorCodes} should cause original exception to be rethrown. */ @Test - public void testGetErrorCode_unknownErrorCode() { + void testGetErrorCode_unknownErrorCode() { Mockito.when(responseException.getContent()) .thenReturn( "{\"errors\":[{\"code\":\"INVALID_ERROR_CODE\",\"message\":\"invalid code\",\"detail\":{}}]}"); @@ -56,7 +59,7 @@ public void testGetErrorCode_unknownErrorCode() { /** Multiple error objects should cause original exception to be rethrown. */ @Test - public void testGetErrorCode_multipleErrors() { + void testGetErrorCode_multipleErrors() { Mockito.when(responseException.getContent()) .thenReturn( "{\"errors\":[" @@ -73,7 +76,7 @@ public void testGetErrorCode_multipleErrors() { /** An non-error object should cause original exception to be rethrown. */ @Test - public void testGetErrorCode_invalidErrorObject() { + void testGetErrorCode_invalidErrorObject() { Mockito.when(responseException.getContent()) .thenReturn("{\"type\":\"other\",\"message\":\"some other object\"}"); try { diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPullerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPullerTest.java index e168ae0239d..526c87e80c0 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPullerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPullerTest.java @@ -42,15 +42,18 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ManifestPuller}. */ -@RunWith(MockitoJUnitRunner.class) -public class ManifestPullerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ManifestPullerTest { private static InputStream stringToInputStreamUtf8(String string) { return new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)); @@ -65,7 +68,7 @@ private static InputStream stringToInputStreamUtf8(String string) { @Mock private Response mockResponse; @Test - public void testHandleResponse_v21() + void testHandleResponse_v21() throws URISyntaxException, IOException, UnknownManifestFormatException { Path v21ManifestFile = Paths.get(Resources.getResource("core/json/v21manifest.json").toURI()); InputStream v21Manifest = new ByteArrayInputStream(Files.readAllBytes(v21ManifestFile)); @@ -85,7 +88,7 @@ public void testHandleResponse_v21() } @Test - public void testHandleResponse_v22() + void testHandleResponse_v22() throws URISyntaxException, IOException, UnknownManifestFormatException { Path v22ManifestFile = Paths.get(Resources.getResource("core/json/v22manifest.json").toURI()); InputStream v22Manifest = new ByteArrayInputStream(Files.readAllBytes(v22ManifestFile)); @@ -105,7 +108,7 @@ public void testHandleResponse_v22() } @Test - public void testHandleResponse_ociManifest() + void testHandleResponse_ociManifest() throws URISyntaxException, IOException, UnknownManifestFormatException { Path ociManifestFile = Paths.get(Resources.getResource("core/json/ocimanifest.json").toURI()); InputStream ociManifest = new ByteArrayInputStream(Files.readAllBytes(ociManifestFile)); @@ -125,7 +128,7 @@ public void testHandleResponse_ociManifest() } @Test - public void testHandleResponse_v22ManifestListFailsWhenParsedAsV22Manifest() + void testHandleResponse_v22ManifestListFailsWhenParsedAsV22Manifest() throws URISyntaxException, IOException, UnknownManifestFormatException { Path v22ManifestListFile = Paths.get(Resources.getResource("core/json/v22manifest_list.json").toURI()); @@ -143,7 +146,7 @@ public void testHandleResponse_v22ManifestListFailsWhenParsedAsV22Manifest() } @Test - public void testHandleResponse_v22ManifestListFromParentType() + void testHandleResponse_v22ManifestListFromParentType() throws URISyntaxException, IOException, UnknownManifestFormatException { Path v22ManifestListFile = Paths.get(Resources.getResource("core/json/v22manifest_list.json").toURI()); @@ -165,7 +168,7 @@ public void testHandleResponse_v22ManifestListFromParentType() } @Test - public void testHandleResponse_v22ManifestList() + void testHandleResponse_v22ManifestList() throws URISyntaxException, IOException, UnknownManifestFormatException { Path v22ManifestListFile = Paths.get(Resources.getResource("core/json/v22manifest_list.json").toURI()); @@ -190,7 +193,7 @@ public void testHandleResponse_v22ManifestList() } @Test - public void testHandleResponse_OciIndex() + void testHandleResponse_OciIndex() throws URISyntaxException, IOException, UnknownManifestFormatException { Path ociIndexFile = Paths.get(Resources.getResource("core/json/ociindex_platforms.json").toURI()); @@ -212,7 +215,7 @@ public void testHandleResponse_OciIndex() } @Test - public void testHandleResponse_noSchemaVersion() throws IOException { + void testHandleResponse_noSchemaVersion() throws IOException { Mockito.when(mockResponse.getBody()).thenReturn(stringToInputStreamUtf8("{}")); try { testManifestPuller.handleResponse(mockResponse); @@ -224,7 +227,7 @@ public void testHandleResponse_noSchemaVersion() throws IOException { } @Test - public void testHandleResponse_invalidSchemaVersion() throws IOException { + void testHandleResponse_invalidSchemaVersion() throws IOException { Mockito.when(mockResponse.getBody()) .thenReturn(stringToInputStreamUtf8("{\"schemaVersion\":\"not valid\"}")); try { @@ -237,7 +240,7 @@ public void testHandleResponse_invalidSchemaVersion() throws IOException { } @Test - public void testHandleResponse_unknownSchemaVersion() throws IOException { + void testHandleResponse_unknownSchemaVersion() throws IOException { Mockito.when(mockResponse.getBody()) .thenReturn(stringToInputStreamUtf8("{\"schemaVersion\":0}")); try { @@ -250,7 +253,7 @@ public void testHandleResponse_unknownSchemaVersion() throws IOException { } @Test - public void testHandleResponse_ociIndexWithNoMediaType() + void testHandleResponse_ociIndexWithNoMediaType() throws IOException, UnknownManifestFormatException { String ociManifestJson = "{\n" @@ -282,7 +285,7 @@ public void testHandleResponse_ociIndexWithNoMediaType() } @Test - public void testHandleResponse_ociManfiestWithNoMediaType() + void testHandleResponse_ociManfiestWithNoMediaType() throws IOException, UnknownManifestFormatException { String ociManifestJson = "{\n" @@ -313,7 +316,7 @@ public void testHandleResponse_ociManfiestWithNoMediaType() } @Test - public void testHandleResponse_invalidOciManfiest() throws IOException { + void testHandleResponse_invalidOciManfiest() throws IOException { Mockito.when(mockResponse.getBody()) .thenReturn(stringToInputStreamUtf8("{\"schemaVersion\": 2}")); @@ -330,31 +333,31 @@ public void testHandleResponse_invalidOciManfiest() throws IOException { } @Test - public void testGetApiRoute() throws MalformedURLException { + void testGetApiRoute() throws MalformedURLException { Assert.assertEquals( new URL("http://someApiBase/someImageName/manifests/test-image-tag"), testManifestPuller.getApiRoute("http://someApiBase/")); } @Test - public void testGetHttpMethod() { + void testGetHttpMethod() { Assert.assertEquals("GET", testManifestPuller.getHttpMethod()); } @Test - public void testGetActionDescription() { + void testGetActionDescription() { Assert.assertEquals( "pull image manifest for someServerUrl/someImageName:test-image-tag", testManifestPuller.getActionDescription()); } @Test - public void testGetContent() { + void testGetContent() { Assert.assertNull(testManifestPuller.getContent()); } @Test - public void testGetAccept() { + void testGetAccept() { Assert.assertEquals( Arrays.asList( OciManifestTemplate.MANIFEST_MEDIA_TYPE, diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPusherTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPusherTest.java index e5bd833c459..5c3a335f441 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPusherTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/ManifestPusherTest.java @@ -41,16 +41,19 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ManifestPusher}. */ -@RunWith(MockitoJUnitRunner.class) -public class ManifestPusherTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ManifestPusherTest { @Mock private Response mockResponse; @Mock private EventHandlers mockEventHandlers; @@ -59,8 +62,8 @@ public class ManifestPusherTest { private V22ManifestTemplate fakeManifestTemplate; private ManifestPusher testManifestPusher; - @Before - public void setUp() throws URISyntaxException, IOException { + @BeforeEach + void setUp() throws URISyntaxException, IOException { v22manifestJsonFile = Paths.get(Resources.getResource("core/json/v22manifest.json").toURI()); fakeManifestTemplate = JsonTemplateMapper.readJsonFromFile(v22manifestJsonFile, V22ManifestTemplate.class); @@ -74,7 +77,7 @@ public void setUp() throws URISyntaxException, IOException { } @Test - public void testGetContent() throws IOException { + void testGetContent() throws IOException { BlobHttpContent body = testManifestPusher.getContent(); Assert.assertNotNull(body); @@ -89,7 +92,7 @@ public void testGetContent() throws IOException { } @Test - public void testHandleResponse_valid() throws IOException { + void testHandleResponse_valid() throws IOException { DescriptorDigest expectedDigest = Digests.computeJsonDigest(fakeManifestTemplate); Mockito.when(mockResponse.getHeader("Docker-Content-Digest")) .thenReturn(Collections.singletonList(expectedDigest.toString())); @@ -97,7 +100,7 @@ public void testHandleResponse_valid() throws IOException { } @Test - public void testHandleResponse_noDigest() throws IOException { + void testHandleResponse_noDigest() throws IOException { DescriptorDigest expectedDigest = Digests.computeJsonDigest(fakeManifestTemplate); Mockito.when(mockResponse.getHeader("Docker-Content-Digest")) .thenReturn(Collections.emptyList()); @@ -108,7 +111,7 @@ public void testHandleResponse_noDigest() throws IOException { } @Test - public void testHandleResponse_multipleDigests() throws IOException { + void testHandleResponse_multipleDigests() throws IOException { DescriptorDigest expectedDigest = Digests.computeJsonDigest(fakeManifestTemplate); Mockito.when(mockResponse.getHeader("Docker-Content-Digest")) .thenReturn(Arrays.asList("too", "many")); @@ -120,7 +123,7 @@ public void testHandleResponse_multipleDigests() throws IOException { } @Test - public void testHandleResponse_invalidDigest() throws IOException { + void testHandleResponse_invalidDigest() throws IOException { DescriptorDigest expectedDigest = Digests.computeJsonDigest(fakeManifestTemplate); Mockito.when(mockResponse.getHeader("Docker-Content-Digest")) .thenReturn(Collections.singletonList("not valid")); @@ -132,32 +135,32 @@ public void testHandleResponse_invalidDigest() throws IOException { } @Test - public void testApiRoute() throws MalformedURLException { + void testApiRoute() throws MalformedURLException { Assert.assertEquals( new URL("http://someApiBase/someImageName/manifests/test-image-tag"), testManifestPusher.getApiRoute("http://someApiBase/")); } @Test - public void testGetHttpMethod() { + void testGetHttpMethod() { Assert.assertEquals("PUT", testManifestPusher.getHttpMethod()); } @Test - public void testGetActionDescription() { + void testGetActionDescription() { Assert.assertEquals( "push image manifest for someServerUrl/someImageName:test-image-tag", testManifestPusher.getActionDescription()); } @Test - public void testGetAccept() { + void testGetAccept() { Assert.assertEquals(0, testManifestPusher.getAccept().size()); } /** Docker Registry 2.0 and 2.1 return 400 / TAG_INVALID. */ @Test - public void testHandleHttpResponseException_dockerRegistry_tagInvalid() throws ResponseException { + void testHandleHttpResponseException_dockerRegistry_tagInvalid() throws ResponseException { ResponseException exception = Mockito.mock(ResponseException.class); Mockito.when(exception.getStatusCode()).thenReturn(HttpStatus.SC_BAD_REQUEST); Mockito.when(exception.getContent()) @@ -179,8 +182,7 @@ public void testHandleHttpResponseException_dockerRegistry_tagInvalid() throws R /** Docker Registry 2.2 returns a 400 / MANIFEST_INVALID. */ @Test - public void testHandleHttpResponseException_dockerRegistry_manifestInvalid() - throws ResponseException { + void testHandleHttpResponseException_dockerRegistry_manifestInvalid() throws ResponseException { ResponseException exception = Mockito.mock(ResponseException.class); Mockito.when(exception.getStatusCode()).thenReturn(HttpStatus.SC_BAD_REQUEST); Mockito.when(exception.getContent()) @@ -202,7 +204,7 @@ public void testHandleHttpResponseException_dockerRegistry_manifestInvalid() /** Quay.io returns an undocumented 415 / MANIFEST_INVALID. */ @Test - public void testHandleHttpResponseException_quayIo() throws ResponseException { + void testHandleHttpResponseException_quayIo() throws ResponseException { ResponseException exception = Mockito.mock(ResponseException.class); Mockito.when(exception.getStatusCode()).thenReturn(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE); Mockito.when(exception.getContent()) @@ -224,7 +226,7 @@ public void testHandleHttpResponseException_quayIo() throws ResponseException { } @Test - public void testHandleHttpResponseException_otherError() throws RegistryErrorException { + void testHandleHttpResponseException_otherError() throws RegistryErrorException { ResponseException exception = Mockito.mock(ResponseException.class); Mockito.when(exception.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED); try { diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAliasGroupTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAliasGroupTest.java index 4c78c26f8ba..36bc817482b 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAliasGroupTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAliasGroupTest.java @@ -21,20 +21,20 @@ import java.util.List; import java.util.Set; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link RegistryAliasGroup}. */ -public class RegistryAliasGroupTest { +class RegistryAliasGroupTest { @Test - public void testGetAliasesGroup_noKnownAliases() { + void testGetAliasesGroup_noKnownAliases() { List singleton = RegistryAliasGroup.getAliasesGroup("something.gcr.io"); Assert.assertEquals(1, singleton.size()); Assert.assertEquals("something.gcr.io", singleton.get(0)); } @Test - public void testGetAliasesGroup_dockerHub() { + void testGetAliasesGroup_dockerHub() { Set aliases = Sets.newHashSet( "registry.hub.docker.com", "index.docker.io", "registry-1.docker.io", "docker.io"); @@ -44,13 +44,13 @@ public void testGetAliasesGroup_dockerHub() { } @Test - public void testGetHost_noAlias() { + void testGetHost_noAlias() { String host = RegistryAliasGroup.getHost("something.gcr.io"); Assert.assertEquals("something.gcr.io", host); } @Test - public void testGetHost_dockerIo() { + void testGetHost_dockerIo() { String host = RegistryAliasGroup.getHost("docker.io"); Assert.assertEquals("registry-1.docker.io", host); } diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticationFailedExceptionTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticationFailedExceptionTest.java index cba6cd769ac..5a797b487e4 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticationFailedExceptionTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticationFailedExceptionTest.java @@ -18,13 +18,13 @@ import com.google.cloud.tools.jib.api.RegistryAuthenticationFailedException; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link RegistryAuthenticationFailedException}. */ -public class RegistryAuthenticationFailedExceptionTest { +class RegistryAuthenticationFailedExceptionTest { @Test - public void testRegistryAuthenticationFailedException_message() { + void testRegistryAuthenticationFailedException_message() { RegistryAuthenticationFailedException exception = new RegistryAuthenticationFailedException("serverUrl", "imageName", "message"); Assert.assertEquals("serverUrl", exception.getServerUrl()); @@ -35,7 +35,7 @@ public void testRegistryAuthenticationFailedException_message() { } @Test - public void testRegistryAuthenticationFailedException_exception() { + void testRegistryAuthenticationFailedException_exception() { Throwable cause = new Throwable("message"); RegistryAuthenticationFailedException exception = new RegistryAuthenticationFailedException("serverUrl", "imageName", cause); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticatorTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticatorTest.java index 0ce5be3dba7..8ee1f090057 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticatorTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryAuthenticatorTest.java @@ -37,18 +37,23 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link RegistryAuthenticator}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegistryAuthenticatorTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class RegistryAuthenticatorTest { private final RegistryEndpointRequestProperties registryEndpointRequestProperties = new RegistryEndpointRequestProperties("someserver", "someimage"); @@ -59,8 +64,8 @@ public class RegistryAuthenticatorTest { private RegistryAuthenticator registryAuthenticator; - @Before - public void setUp() throws RegistryAuthenticationFailedException, IOException { + @BeforeEach + void setUp() throws RegistryAuthenticationFailedException, IOException { registryAuthenticator = RegistryAuthenticator.fromAuthenticationMethod( "Bearer realm=\"https://somerealm\",service=\"someservice\",scope=\"somescope\"", @@ -77,7 +82,7 @@ public void setUp() throws RegistryAuthenticationFailedException, IOException { } @Test - public void testFromAuthenticationMethod_bearer() + void testFromAuthenticationMethod_bearer() throws MalformedURLException, RegistryAuthenticationFailedException { RegistryAuthenticator registryAuthenticator = RegistryAuthenticator.fromAuthenticationMethod( @@ -107,7 +112,7 @@ public void testFromAuthenticationMethod_bearer() } @Test - public void testAuthRequestParameters_basicAuth() { + void testAuthRequestParameters_basicAuth() { Assert.assertEquals( "service=someservice&scope=repository:someimage:scope", registryAuthenticator.getAuthRequestParameters( @@ -115,7 +120,7 @@ public void testAuthRequestParameters_basicAuth() { } @Test - public void testAuthRequestParameters_oauth2() { + void testAuthRequestParameters_oauth2() { Credential credential = Credential.from("", "oauth2_access_token"); Assert.assertEquals( "service=someservice&scope=repository:someimage:scope" @@ -126,24 +131,24 @@ public void testAuthRequestParameters_oauth2() { } @Test - public void isOAuth2Auth_nullCredential() { + void isOAuth2Auth_nullCredential() { Assert.assertFalse(registryAuthenticator.isOAuth2Auth(null)); } @Test - public void isOAuth2Auth_basicAuth() { + void isOAuth2Auth_basicAuth() { Credential credential = Credential.from("name", "password"); Assert.assertFalse(registryAuthenticator.isOAuth2Auth(credential)); } @Test - public void isOAuth2Auth_oauth2() { + void isOAuth2Auth_oauth2() { Credential credential = Credential.from("", "oauth2_token"); Assert.assertTrue(registryAuthenticator.isOAuth2Auth(credential)); } @Test - public void getAuthenticationUrl_basicAuth() throws MalformedURLException { + void getAuthenticationUrl_basicAuth() throws MalformedURLException { Assert.assertEquals( new URL("https://somerealm?service=someservice&scope=repository:someimage:scope"), registryAuthenticator.getAuthenticationUrl( @@ -151,7 +156,7 @@ public void getAuthenticationUrl_basicAuth() throws MalformedURLException { } @Test - public void istAuthenticationUrl_oauth2() throws MalformedURLException { + void istAuthenticationUrl_oauth2() throws MalformedURLException { Credential credential = Credential.from("", "oauth2_token"); Assert.assertEquals( new URL("https://somerealm"), @@ -159,7 +164,7 @@ public void istAuthenticationUrl_oauth2() throws MalformedURLException { } @Test - public void testFromAuthenticationMethod_basic() throws RegistryAuthenticationFailedException { + void testFromAuthenticationMethod_basic() throws RegistryAuthenticationFailedException { assertThat( RegistryAuthenticator.fromAuthenticationMethod( "Basic", registryEndpointRequestProperties, "user-agent", httpClient)) @@ -191,7 +196,7 @@ public void testFromAuthenticationMethod_basic() throws RegistryAuthenticationFa } @Test - public void testFromAuthenticationMethod_noBearer() { + void testFromAuthenticationMethod_noBearer() { try { RegistryAuthenticator.fromAuthenticationMethod( "realm=\"https://somerealm\",service=\"someservice\",scope=\"somescope\"", @@ -208,7 +213,7 @@ public void testFromAuthenticationMethod_noBearer() { } @Test - public void testFromAuthenticationMethod_noRealm() { + void testFromAuthenticationMethod_noRealm() { try { RegistryAuthenticator.fromAuthenticationMethod( "Bearer scope=\"somescope\"", @@ -225,7 +230,7 @@ public void testFromAuthenticationMethod_noRealm() { } @Test - public void testFromAuthenticationMethod_noService() + void testFromAuthenticationMethod_noService() throws MalformedURLException, RegistryAuthenticationFailedException { RegistryAuthenticator registryAuthenticator = RegistryAuthenticator.fromAuthenticationMethod( @@ -242,7 +247,7 @@ public void testFromAuthenticationMethod_noService() } @Test - public void testUserAgent() + void testUserAgent() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryCredentialsNotSentException { try (TestWebServer server = new TestWebServer(false)) { @@ -264,7 +269,7 @@ public void testUserAgent() } @Test - public void testSourceImage_differentSourceRepository() + void testSourceImage_differentSourceRepository() throws RegistryCredentialsNotSentException, RegistryAuthenticationFailedException { RegistryAuthenticator authenticator = RegistryAuthenticator.fromAuthenticationMethod( @@ -281,7 +286,7 @@ public void testSourceImage_differentSourceRepository() } @Test - public void testSourceImage_sameSourceRepository() + void testSourceImage_sameSourceRepository() throws RegistryCredentialsNotSentException, RegistryAuthenticationFailedException { RegistryAuthenticator authenticator = RegistryAuthenticator.fromAuthenticationMethod( @@ -297,7 +302,7 @@ public void testSourceImage_sameSourceRepository() } @Test - public void testAuthorizationCleared() throws RegistryAuthenticationFailedException, IOException { + void testAuthorizationCleared() throws RegistryAuthenticationFailedException, IOException { ResponseException responseException = Mockito.mock(ResponseException.class); Mockito.when(responseException.getStatusCode()).thenReturn(401); Mockito.when(responseException.requestAuthorizationCleared()).thenReturn(true); @@ -315,27 +320,15 @@ public void testAuthorizationCleared() throws RegistryAuthenticationFailedExcept } } - @Test - public void testAuthenticationResponseTemplate_readsToken() throws IOException { - String input = "{\"token\":\"test_value\"}"; - RegistryAuthenticator.AuthenticationResponseTemplate template = - JsonTemplateMapper.readJson( - input, RegistryAuthenticator.AuthenticationResponseTemplate.class); - Assert.assertEquals("test_value", template.getToken()); - } - - @Test - public void testAuthenticationResponseTemplate_readsAccessToken() throws IOException { - String input = "{\"access_token\":\"test_value\"}"; - RegistryAuthenticator.AuthenticationResponseTemplate template = - JsonTemplateMapper.readJson( - input, RegistryAuthenticator.AuthenticationResponseTemplate.class); - Assert.assertEquals("test_value", template.getToken()); - } - - @Test - public void testAuthenticationResponseTemplate_prefersToken() throws IOException { - String input = "{\"token\":\"test_value\",\"access_token\":\"wrong_value\"}"; + @ParameterizedTest + @CsvSource( + value = { + "{\"token\":\"test_value\"}", + "{\"access_token\":\"test_value\"}", + "{\"token\":\"test_value\",\"access_token\":\"wrong_value\"}" + }, + delimiter = '|') + void testAuthenticationResponseTemplate_readsToken(String input) throws IOException { RegistryAuthenticator.AuthenticationResponseTemplate template = JsonTemplateMapper.readJson( input, RegistryAuthenticator.AuthenticationResponseTemplate.class); @@ -343,7 +336,7 @@ public void testAuthenticationResponseTemplate_prefersToken() throws IOException } @Test - public void testAuthenticationResponseTemplate_acceptsNull() throws IOException { + void testAuthenticationResponseTemplate_acceptsNull() throws IOException { String input = "{}"; RegistryAuthenticator.AuthenticationResponseTemplate template = JsonTemplateMapper.readJson( diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryClientTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryClientTest.java index 97f72cda048..34f1a6c9cd4 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryClientTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryClientTest.java @@ -38,22 +38,25 @@ import javax.annotation.Nullable; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +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.ArgumentMatcher; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** * Tests for {@link RegistryClient}. More comprehensive tests can be found in the integration tests. */ -@RunWith(MockitoJUnitRunner.class) -public class RegistryClientTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class RegistryClientTest { @Mock private EventHandlers eventHandlers; @@ -62,15 +65,15 @@ public class RegistryClientTest { private TestWebServer registry; private TestWebServer authServer; - @Before - public void setUp() throws DigestException { + @BeforeEach + void setUp() throws DigestException { digest = DescriptorDigest.fromHash( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } - @After - public void tearDown() throws IOException { + @AfterEach + void tearDown() throws IOException { if (registry != null) { registry.close(); } @@ -80,7 +83,7 @@ public void tearDown() throws IOException { } @Test - public void testDoBearerAuth_returnsFalseOnBasicAuth() + void testDoBearerAuth_returnsFalseOnBasicAuth() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String basicAuth = @@ -95,7 +98,7 @@ public void testDoBearerAuth_returnsFalseOnBasicAuth() } @Test - public void testDoBearerAuth() + void testDoBearerAuth() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { setUpAuthServerAndRegistry(1, "HTTP/1.1 200 OK\nContent-Length: 1234\n\n"); @@ -111,7 +114,7 @@ public void testDoBearerAuth() } @Test - public void testAutomaticTokenRefresh() + void testAutomaticTokenRefresh() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { setUpAuthServerAndRegistry(3, "HTTP/1.1 200 OK\nContent-Length: 5678\n\n"); @@ -133,7 +136,7 @@ public void testAutomaticTokenRefresh() } @Test - public void testAutomaticTokenRefresh_badWwwAuthenticateResponse() + void testAutomaticTokenRefresh_badWwwAuthenticateResponse() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String tokenResponse = "HTTP/1.1 200 OK\nContent-Length: 26\n\n{\"token\":\"awesome-token!\"}"; @@ -168,7 +171,7 @@ public void testAutomaticTokenRefresh_badWwwAuthenticateResponse() } @Test - public void testAutomaticTokenRefresh_refreshLimit() + void testAutomaticTokenRefresh_refreshLimit() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String tokenResponse = "HTTP/1.1 200 OK\nContent-Length: 26\n\n{\"token\":\"awesome-token!\"}"; @@ -200,7 +203,7 @@ public void testAutomaticTokenRefresh_refreshLimit() } @Test - public void testConfigureBasicAuth() + void testConfigureBasicAuth() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String basicAuth = "HTTP/1.1 200 OK\nContent-Length: 56789\n\n"; @@ -215,7 +218,7 @@ public void testConfigureBasicAuth() } @Test - public void testAuthPullByWwwAuthenticate_bearerAuth() + void testAuthPullByWwwAuthenticate_bearerAuth() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String tokenResponse = "HTTP/1.1 200 OK\nContent-Length: 26\n\n{\"token\":\"awesome-token!\"}"; @@ -234,7 +237,7 @@ public void testAuthPullByWwwAuthenticate_bearerAuth() } @Test - public void testAuthPullByWwwAuthenticate_basicAuth() + void testAuthPullByWwwAuthenticate_basicAuth() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String blobResponse = "HTTP/1.1 200 OK\nContent-Length: 5678\n\n"; @@ -251,7 +254,7 @@ public void testAuthPullByWwwAuthenticate_basicAuth() } @Test - public void testAuthPullByWwwAuthenticate_basicAuthRequestedButNullCredential() + void testAuthPullByWwwAuthenticate_basicAuthRequestedButNullCredential() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String blobResponse = "HTTP/1.1 200 OK\nContent-Length: 5678\n\n"; @@ -268,7 +271,7 @@ public void testAuthPullByWwwAuthenticate_basicAuthRequestedButNullCredential() } @Test - public void testAuthPullByWwwAuthenticate_basicAuthRequestedButOAuth2Credential() + void testAuthPullByWwwAuthenticate_basicAuthRequestedButOAuth2Credential() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String blobResponse = "HTTP/1.1 200 OK\nContent-Length: 5678\n\n"; @@ -287,7 +290,7 @@ public void testAuthPullByWwwAuthenticate_basicAuthRequestedButOAuth2Credential( } @Test - public void testAuthPullByWwwAuthenticate_invalidAuthMethod() { + void testAuthPullByWwwAuthenticate_invalidAuthMethod() { RegistryClient registryClient = RegistryClient.factory(eventHandlers, "server", "foo/bar", null).newRegistryClient(); try { @@ -302,7 +305,7 @@ public void testAuthPullByWwwAuthenticate_invalidAuthMethod() { } @Test - public void testPullManifest() + void testPullManifest() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String manifestResponse = @@ -340,7 +343,7 @@ public void testPullManifest() } @Test - public void testPullManifest_manifestList() + void testPullManifest_manifestList() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException, RegistryException { String manifestResponse = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryEndpointCallerTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryEndpointCallerTest.java index d9b85bc9208..8de6f964315 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryEndpointCallerTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryEndpointCallerTest.java @@ -47,19 +47,24 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link RegistryEndpointCaller}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegistryEndpointCallerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class RegistryEndpointCallerTest { /** Implementation of {@link RegistryEndpointProvider} for testing. */ private static class TestRegistryEndpointProvider implements RegistryEndpointProvider { @@ -118,8 +123,8 @@ private static ResponseException mockResponseException(int statusCode) { private RegistryEndpointCaller endpointCaller; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { endpointCaller = new RegistryEndpointCaller<>( mockEventHandlers, @@ -134,7 +139,7 @@ public void setUp() throws IOException { } @Test - public void testCall_secureCallerOnUnverifiableServer() throws IOException, RegistryException { + void testCall_secureCallerOnUnverifiableServer() throws IOException, RegistryException { Mockito.when(mockHttpClient.call(Mockito.any(), Mockito.any(), Mockito.any())) .thenThrow(Mockito.mock(SSLPeerUnverifiedException.class)); @@ -150,7 +155,7 @@ public void testCall_secureCallerOnUnverifiableServer() throws IOException, Regi } @Test - public void testCall_noHttpResponse() throws IOException, RegistryException { + void testCall_noHttpResponse() throws IOException, RegistryException { NoHttpResponseException mockNoResponseException = Mockito.mock(NoHttpResponseException.class); setUpRegistryResponse(mockNoResponseException); @@ -164,12 +169,12 @@ public void testCall_noHttpResponse() throws IOException, RegistryException { } @Test - public void testCall_unauthorized() throws IOException, RegistryException { + void testCall_unauthorized() throws IOException, RegistryException { verifyThrowsRegistryUnauthorizedException(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); } @Test - public void testCall_credentialsNotSentOverHttp() throws IOException, RegistryException { + void testCall_credentialsNotSentOverHttp() throws IOException, RegistryException { ResponseException unauthorizedException = mockResponseException(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); Mockito.when(unauthorizedException.requestAuthorizationCleared()).thenReturn(true); @@ -187,7 +192,7 @@ public void testCall_credentialsNotSentOverHttp() throws IOException, RegistryEx } @Test - public void testCall_credentialsForcedOverHttp() throws IOException, RegistryException { + void testCall_credentialsForcedOverHttp() throws IOException, RegistryException { ResponseException unauthorizedException = mockResponseException(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); setUpRegistryResponse(unauthorizedException); @@ -205,27 +210,27 @@ public void testCall_credentialsForcedOverHttp() throws IOException, RegistryExc } @Test - public void testCall_forbidden() throws IOException, RegistryException { + void testCall_forbidden() throws IOException, RegistryException { verifyThrowsRegistryUnauthorizedException(HttpStatusCodes.STATUS_CODE_FORBIDDEN); } @Test - public void testCall_badRequest() throws IOException, RegistryException { + void testCall_badRequest() throws IOException, RegistryException { verifyThrowsRegistryErrorException(HttpStatusCodes.STATUS_CODE_BAD_REQUEST); } @Test - public void testCall_notFound() throws IOException, RegistryException { + void testCall_notFound() throws IOException, RegistryException { verifyThrowsRegistryErrorException(HttpStatusCodes.STATUS_CODE_NOT_FOUND); } @Test - public void testCall_methodNotAllowed() throws IOException, RegistryException { + void testCall_methodNotAllowed() throws IOException, RegistryException { verifyThrowsRegistryErrorException(HttpStatusCodes.STATUS_CODE_METHOD_NOT_ALLOWED); } @Test - public void testCall_unknown() throws IOException, RegistryException { + void testCall_unknown() throws IOException, RegistryException { ResponseException responseException = mockResponseException(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); setUpRegistryResponse(responseException); @@ -240,7 +245,7 @@ public void testCall_unknown() throws IOException, RegistryException { } @Test - public void testCall_logErrorOnIoExceptions() throws IOException, RegistryException { + void testCall_logErrorOnIoExceptions() throws IOException, RegistryException { IOException ioException = new IOException("detailed exception message"); setUpRegistryResponse(ioException); @@ -262,7 +267,7 @@ public void testCall_logErrorOnIoExceptions() throws IOException, RegistryExcept } @Test - public void testCall_logErrorOnBrokenPipe() throws IOException, RegistryException { + void testCall_logErrorOnBrokenPipe() throws IOException, RegistryException { IOException ioException = new IOException("this is due to broken pipe"); setUpRegistryResponse(ioException); @@ -290,7 +295,7 @@ public void testCall_logErrorOnBrokenPipe() throws IOException, RegistryExceptio } @Test - public void testCall_logNullExceptionMessage() throws IOException, RegistryException { + void testCall_logNullExceptionMessage() throws IOException, RegistryException { setUpRegistryResponse(new IOException()); try { @@ -310,7 +315,7 @@ public void testCall_logNullExceptionMessage() throws IOException, RegistryExcep } @Test - public void testHttpTimeout_propertyNotSet() throws IOException, RegistryException { + void testHttpTimeout_propertyNotSet() throws IOException, RegistryException { ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); Mockito.when(mockHttpClient.call(Mockito.any(), Mockito.any(), requestCaptor.capture())) .thenReturn(mockResponse); @@ -323,20 +328,21 @@ public void testHttpTimeout_propertyNotSet() throws IOException, RegistryExcepti Assert.assertEquals(20000, new RequestWrapper(requestCaptor.getValue()).getHttpTimeout()); } - @Test - public void testHttpTimeout_stringValue() throws IOException, RegistryException { + @ParameterizedTest + @CsvSource({"random string, 20000", "0, 0", "7593, 7593"}) + void testHttpTimeout_stringValue(String prop, long val) throws IOException, RegistryException { ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); Mockito.when(mockHttpClient.call(Mockito.any(), Mockito.any(), requestCaptor.capture())) .thenReturn(mockResponse); - System.setProperty(JibSystemProperties.HTTP_TIMEOUT, "random string"); + System.setProperty(JibSystemProperties.HTTP_TIMEOUT, prop); endpointCaller.call(); - Assert.assertEquals(20000, new RequestWrapper(requestCaptor.getValue()).getHttpTimeout()); + Assert.assertEquals(val, new RequestWrapper(requestCaptor.getValue()).getHttpTimeout()); } @Test - public void testHttpTimeout_negativeValue() throws IOException, RegistryException { + void testHttpTimeout_negativeValue() throws IOException, RegistryException { ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); Mockito.when(mockHttpClient.call(Mockito.any(), Mockito.any(), requestCaptor.capture())) .thenReturn(mockResponse); @@ -350,51 +356,27 @@ public void testHttpTimeout_negativeValue() throws IOException, RegistryExceptio } @Test - public void testHttpTimeout_0accepted() throws IOException, RegistryException { - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); - Mockito.when(mockHttpClient.call(Mockito.any(), Mockito.any(), requestCaptor.capture())) - .thenReturn(mockResponse); - - System.setProperty(JibSystemProperties.HTTP_TIMEOUT, "0"); - endpointCaller.call(); - - Assert.assertEquals(0, new RequestWrapper(requestCaptor.getValue()).getHttpTimeout()); - } - - @Test - public void testHttpTimeout() throws IOException, RegistryException { - ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); - Mockito.when(mockHttpClient.call(Mockito.any(), Mockito.any(), requestCaptor.capture())) - .thenReturn(mockResponse); - - System.setProperty(JibSystemProperties.HTTP_TIMEOUT, "7593"); - endpointCaller.call(); - - Assert.assertEquals(7593, new RequestWrapper(requestCaptor.getValue()).getHttpTimeout()); - } - - @Test - public void testIsBrokenPipe_notBrokenPipe() { + void testIsBrokenPipe_notBrokenPipe() { Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new IOException())); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new SocketException())); Assert.assertFalse(RegistryEndpointCaller.isBrokenPipe(new SSLException("mock"))); } @Test - public void testIsBrokenPipe_brokenPipe() { + void testIsBrokenPipe_brokenPipe() { Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(new IOException("cool broken pipe !"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(new SocketException("BROKEN PIPE"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(new SSLException("calm BrOkEn PiPe"))); } @Test - public void testIsBrokenPipe_nestedBrokenPipe() { + void testIsBrokenPipe_nestedBrokenPipe() { IOException exception = new IOException(new SSLException(new SocketException("Broken pipe"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(exception)); } @Test - public void testIsBrokenPipe_terminatesWhenCauseIsOriginal() { + void testIsBrokenPipe_terminatesWhenCauseIsOriginal() { IOException exception = Mockito.mock(IOException.class); Mockito.when(exception.getCause()).thenReturn(exception); @@ -402,7 +384,7 @@ public void testIsBrokenPipe_terminatesWhenCauseIsOriginal() { } @Test - public void testNewRegistryErrorException_jsonErrorOutput() { + void testNewRegistryErrorException_jsonErrorOutput() { ResponseException httpException = Mockito.mock(ResponseException.class); Mockito.when(httpException.getContent()) .thenReturn( @@ -417,7 +399,7 @@ public void testNewRegistryErrorException_jsonErrorOutput() { } @Test - public void testNewRegistryErrorException_nonJsonErrorOutput() { + void testNewRegistryErrorException_nonJsonErrorOutput() { ResponseException httpException = Mockito.mock(ResponseException.class); // Registry returning non-structured error output Mockito.when(httpException.getContent()).thenReturn(">>>>> (404) page not found <<<<<"); @@ -434,7 +416,7 @@ public void testNewRegistryErrorException_nonJsonErrorOutput() { } @Test - public void testNewRegistryErrorException_noOutputFromRegistry() { + void testNewRegistryErrorException_noOutputFromRegistry() { ResponseException httpException = Mockito.mock(ResponseException.class); // Registry returning null error output Mockito.when(httpException.getContent()).thenReturn(null); diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryErrorExceptionBuilderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryErrorExceptionBuilderTest.java index 17d8895be26..5b37490fa02 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryErrorExceptionBuilderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/RegistryErrorExceptionBuilderTest.java @@ -19,19 +19,22 @@ import com.google.api.client.http.HttpResponseException; import com.google.cloud.tools.jib.registry.json.ErrorEntryTemplate; import org.junit.Assert; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link RegistryErrorExceptionBuilder}. */ -@RunWith(MockitoJUnitRunner.class) -public class RegistryErrorExceptionBuilderTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class RegistryErrorExceptionBuilderTest { @Mock private HttpResponseException mockHttpResponseException; @Test - public void testAddErrorEntry() { + void testAddErrorEntry() { RegistryErrorExceptionBuilder builder = new RegistryErrorExceptionBuilder("do something", mockHttpResponseException) .addReason( diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigCredentialRetrieverTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigCredentialRetrieverTest.java index 509ed28ed4e..d6e441d0db9 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigCredentialRetrieverTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigCredentialRetrieverTest.java @@ -26,16 +26,19 @@ import java.util.Optional; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link DockerConfigCredentialRetriever}. */ -@RunWith(MockitoJUnitRunner.class) -public class DockerConfigCredentialRetrieverTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DockerConfigCredentialRetrieverTest { private static final Credential FAKE_CREDENTIAL = Credential.from("username", "password"); @@ -45,8 +48,8 @@ public class DockerConfigCredentialRetrieverTest { private Path dockerConfigFile; - @Before - public void setUp() + @BeforeEach + void setUp() throws URISyntaxException, CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { dockerConfigFile = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); @@ -54,7 +57,7 @@ public void setUp() } @Test - public void testRetrieve_nonExistentDockerConfigFile() throws IOException { + void testRetrieve_nonExistentDockerConfigFile() throws IOException { DockerConfigCredentialRetriever dockerConfigCredentialRetriever = DockerConfigCredentialRetriever.create("some registry", Paths.get("fake/path")); @@ -62,7 +65,7 @@ public void testRetrieve_nonExistentDockerConfigFile() throws IOException { } @Test - public void testRetrieve_hasAuth() throws IOException { + void testRetrieve_hasAuth() throws IOException { DockerConfigCredentialRetriever dockerConfigCredentialRetriever = DockerConfigCredentialRetriever.create("some other registry", dockerConfigFile); @@ -77,7 +80,7 @@ public void testRetrieve_hasAuth() throws IOException { } @Test - public void testRetrieve_authTakesPrecedenceOverUsernameAndPassword() throws IOException { + void testRetrieve_authTakesPrecedenceOverUsernameAndPassword() throws IOException { DockerConfigCredentialRetriever dockerConfigCredentialRetriever = DockerConfigCredentialRetriever.create("auth and userpw registry", dockerConfigFile); @@ -92,7 +95,7 @@ public void testRetrieve_authTakesPrecedenceOverUsernameAndPassword() throws IOE } @Test - public void testRetrieve_hasAuthWithUsernameAndPassword() throws IOException { + void testRetrieve_hasAuthWithUsernameAndPassword() throws IOException { DockerConfigCredentialRetriever dockerConfigCredentialRetriever = DockerConfigCredentialRetriever.create("userpw registry", dockerConfigFile); @@ -107,7 +110,7 @@ public void testRetrieve_hasAuthWithUsernameAndPassword() throws IOException { } @Test - public void testRetrieve_hasAuth_legacyConfigFormat() throws IOException, URISyntaxException { + void testRetrieve_hasAuth_legacyConfigFormat() throws IOException, URISyntaxException { dockerConfigFile = Paths.get(Resources.getResource("core/json/legacy_dockercfg").toURI()); DockerConfigCredentialRetriever retriever1 = @@ -129,7 +132,7 @@ public void testRetrieve_hasAuth_legacyConfigFormat() throws IOException, URISyn } @Test - public void testRetrieve_credentialHelperTakesPrecedenceOverAuth() { + void testRetrieve_credentialHelperTakesPrecedenceOverAuth() { Mockito.when(mockDockerConfig.getCredentialHelperFor("some registry")) .thenReturn(mockDockerCredentialHelper); Mockito.when(mockDockerCredentialHelper.getCredentialHelper()) @@ -145,7 +148,7 @@ public void testRetrieve_credentialHelperTakesPrecedenceOverAuth() { } @Test - public void testRetrieve_credentialHelper_warn() + void testRetrieve_credentialHelper_warn() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { Mockito.when(mockDockerConfig.getCredentialHelperFor("another registry")) @@ -164,7 +167,7 @@ public void testRetrieve_credentialHelper_warn() } @Test - public void testRetrieve_none() throws IOException { + void testRetrieve_none() throws IOException { DockerConfigCredentialRetriever dockerConfigCredentialRetriever = DockerConfigCredentialRetriever.create("unknown registry", dockerConfigFile); @@ -172,7 +175,7 @@ public void testRetrieve_none() throws IOException { } @Test - public void testRetrieve_credentialFromAlias() { + void testRetrieve_credentialFromAlias() { Mockito.when(mockDockerConfig.getCredentialHelperFor("registry.hub.docker.com")) .thenReturn(mockDockerCredentialHelper); DockerConfigCredentialRetriever dockerConfigCredentialRetriever = @@ -184,7 +187,7 @@ public void testRetrieve_credentialFromAlias() { } @Test - public void testRetrieve_suffixMatching() throws IOException, URISyntaxException { + void testRetrieve_suffixMatching() throws IOException, URISyntaxException { Path dockerConfigFile = Paths.get(Resources.getResource("core/json/dockerconfig_index_docker_io_v1.json").toURI()); @@ -198,7 +201,7 @@ public void testRetrieve_suffixMatching() throws IOException, URISyntaxException } @Test - public void testRetrieve_suffixMatchingFromAlias() throws IOException, URISyntaxException { + void testRetrieve_suffixMatchingFromAlias() throws IOException, URISyntaxException { Path dockerConfigFile = Paths.get(Resources.getResource("core/json/dockerconfig_index_docker_io_v1.json").toURI()); @@ -212,7 +215,7 @@ public void testRetrieve_suffixMatchingFromAlias() throws IOException, URISyntax } @Test - public void testRetrieve_azureIdentityToken() throws IOException, URISyntaxException { + void testRetrieve_azureIdentityToken() throws IOException, URISyntaxException { Path dockerConfigFile = Paths.get(Resources.getResource("core/json/dockerconfig_identity_token.json").toURI()); @@ -226,7 +229,7 @@ public void testRetrieve_azureIdentityToken() throws IOException, URISyntaxExcep } @Test - public void testRetrieve_noErrorWhenMissingAuthField() throws IOException, URISyntaxException { + void testRetrieve_noErrorWhenMissingAuthField() throws IOException, URISyntaxException { Path dockerConfigFile = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfigCredentialRetriever dockerConfigCredentialRetriever = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigTest.java index 3bd62ac404d..58197a57618 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerConfigTest.java @@ -26,17 +26,17 @@ import java.nio.file.Paths; import java.util.Base64; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link DockerConfig}. */ -public class DockerConfigTest { +class DockerConfigTest { private static String decodeBase64(String base64String) { return new String(Base64.getDecoder().decode(base64String), StandardCharsets.UTF_8); } @Test - public void test_fromJson() throws URISyntaxException, IOException { + void test_fromJson() throws URISyntaxException, IOException { // Loads the JSON string. Path jsonFile = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); @@ -65,7 +65,7 @@ public void test_fromJson() throws URISyntaxException, IOException { } @Test - public void testGetAuthFor_orderOfMatchPreference() throws URISyntaxException, IOException { + void testGetAuthFor_orderOfMatchPreference() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig_extra_matches.json").toURI()); @@ -85,7 +85,7 @@ public void testGetAuthFor_orderOfMatchPreference() throws URISyntaxException, I } @Test - public void testGetAuthFor_correctSuffixMatching() throws URISyntaxException, IOException { + void testGetAuthFor_correctSuffixMatching() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig_extra_matches.json").toURI()); @@ -96,8 +96,7 @@ public void testGetAuthFor_correctSuffixMatching() throws URISyntaxException, IO } @Test - public void testGetCredentialHelperFor_exactMatchInCredHelpers() - throws URISyntaxException, IOException { + void testGetCredentialHelperFor_exactMatchInCredHelpers() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = @@ -109,7 +108,7 @@ public void testGetCredentialHelperFor_exactMatchInCredHelpers() } @Test - public void testGetCredentialHelperFor_withHttps() throws URISyntaxException, IOException { + void testGetCredentialHelperFor_withHttps() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = @@ -121,7 +120,7 @@ public void testGetCredentialHelperFor_withHttps() throws URISyntaxException, IO } @Test - public void testGetCredentialHelperFor_withSuffix() throws URISyntaxException, IOException { + void testGetCredentialHelperFor_withSuffix() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = @@ -133,8 +132,7 @@ public void testGetCredentialHelperFor_withSuffix() throws URISyntaxException, I } @Test - public void testGetCredentialHelperFor_withProtocolAndSuffix() - throws URISyntaxException, IOException { + void testGetCredentialHelperFor_withProtocolAndSuffix() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = @@ -149,8 +147,7 @@ public void testGetCredentialHelperFor_withProtocolAndSuffix() } @Test - public void testGetCredentialHelperFor_correctSuffixMatching() - throws URISyntaxException, IOException { + void testGetCredentialHelperFor_correctSuffixMatching() throws URISyntaxException, IOException { Path json = Paths.get(Resources.getResource("core/json/dockerconfig.json").toURI()); DockerConfig dockerConfig = diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperTest.java index 1f17aca613b..b1e7602a855 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/registry/credentials/DockerCredentialHelperTest.java @@ -33,15 +33,20 @@ import java.util.Properties; import java.util.function.Function; import org.junit.Assert; -import org.junit.Before; -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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -@RunWith(MockitoJUnitRunner.class) -public class DockerCredentialHelperTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DockerCredentialHelperTest { private static final String CREDENTIAL_JSON = "{\"Username\":\"myusername\",\"Secret\":\"mysecret\"}"; @@ -53,8 +58,8 @@ public class DockerCredentialHelperTest { private final Properties systemProperties = new Properties(); - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { systemProperties.put("os.name", "unknown"); Mockito.when(process.getInputStream()) @@ -66,7 +71,7 @@ public void setUp() throws IOException { } @Test - public void testDockerCredentialsTemplate_read() throws IOException { + void testDockerCredentialsTemplate_read() throws IOException { DockerCredentialHelper.DockerCredentialsTemplate template = JsonTemplateMapper.readJson( CREDENTIAL_JSON, DockerCredentialHelper.DockerCredentialsTemplate.class); @@ -75,7 +80,7 @@ public void testDockerCredentialsTemplate_read() throws IOException { } @Test - public void testDockerCredentialsTemplate_canReadNull() throws IOException { + void testDockerCredentialsTemplate_canReadNull() throws IOException { String input = "{}"; DockerCredentialHelper.DockerCredentialsTemplate template = JsonTemplateMapper.readJson(input, DockerCredentialHelper.DockerCredentialsTemplate.class); @@ -84,7 +89,7 @@ public void testDockerCredentialsTemplate_canReadNull() throws IOException { } @Test - public void testRetrieve() + void testRetrieve() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { List command = Arrays.asList(Paths.get("/foo/bar").toString(), "get"); @@ -101,7 +106,7 @@ public void testRetrieve() } @Test - public void testRetrieveWithEnvironment() + void testRetrieveWithEnvironment() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { List command = Arrays.asList(Paths.get("/foo/bar").toString(), "get"); @@ -127,53 +132,22 @@ public void testRetrieveWithEnvironment() Assert.assertEquals("Value", processBuilderEnvironment.get("ENV_VARIABLE")); } - @Test - public void testRetrieve_cmdSuffixAddedOnWindows() - throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, - IOException { - systemProperties.setProperty("os.name", "WINdows"); - List command = Arrays.asList(Paths.get("/foo/bar.cmd").toString(), "get"); - Mockito.when(processBuilderFactory.apply(command)).thenReturn(processBuilder); - - DockerCredentialHelper credentialHelper = - dockerCredentialHelper( - "serverUrl", Paths.get("/foo/bar"), systemProperties, processBuilderFactory); - Credential credential = credentialHelper.retrieve(); - Assert.assertEquals("myusername", credential.getUsername()); - Assert.assertEquals("mysecret", credential.getPassword()); - - Mockito.verify(processBuilderFactory).apply(command); - } - - @Test - public void testRetrieve_cmdSuffixAlreadyGivenOnWindows() - throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, - IOException { - systemProperties.setProperty("os.name", "WINdows"); - List command = Arrays.asList(Paths.get("/foo/bar.CmD").toString(), "get"); - Mockito.when(processBuilderFactory.apply(command)).thenReturn(processBuilder); - - DockerCredentialHelper credentialHelper = - dockerCredentialHelper( - "serverUrl", Paths.get("/foo/bar.CmD"), systemProperties, processBuilderFactory); - Credential credential = credentialHelper.retrieve(); - Assert.assertEquals("myusername", credential.getUsername()); - Assert.assertEquals("mysecret", credential.getPassword()); - - Mockito.verify(processBuilderFactory).apply(command); - } - - @Test - public void testRetrieve_exeSuffixAlreadyGivenOnWindows() + @ParameterizedTest + @CsvSource({ + "/foo/bar.cmd, /foo/bar", // suffix added on windows + "/foo/bar.CmD, /foo/bar.CmD", // suffix already given on Windows + "/foo/bar.eXE, /foo/bar.eXE" // exe suffix already given + }) + void testRetrieve_cmdSuffixAddedOnWindows(String cmd, String path) throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { systemProperties.setProperty("os.name", "WINdows"); - List command = Arrays.asList(Paths.get("/foo/bar.eXE").toString(), "get"); + List command = Arrays.asList(Paths.get(cmd).toString(), "get"); Mockito.when(processBuilderFactory.apply(command)).thenReturn(processBuilder); DockerCredentialHelper credentialHelper = dockerCredentialHelper( - "serverUrl", Paths.get("/foo/bar.eXE"), systemProperties, processBuilderFactory); + "serverUrl", Paths.get(path), systemProperties, processBuilderFactory); Credential credential = credentialHelper.retrieve(); Assert.assertEquals("myusername", credential.getUsername()); Assert.assertEquals("mysecret", credential.getPassword()); @@ -182,7 +156,7 @@ public void testRetrieve_exeSuffixAlreadyGivenOnWindows() } @Test - public void testRetrieve_cmdSuffixNotFoundOnWindows() + void testRetrieve_cmdSuffixNotFoundOnWindows() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException { systemProperties.setProperty("os.name", "WINdows"); @@ -206,7 +180,7 @@ public void testRetrieve_cmdSuffixNotFoundOnWindows() } @Test - public void testRetrieve_fileNotFoundExceptionMessage() + void testRetrieve_fileNotFoundExceptionMessage() throws CredentialHelperUnhandledServerUrlException, IOException { Mockito.when(processBuilderFactory.apply(Mockito.any())).thenReturn(processBuilder); Mockito.when(processBuilder.start()) diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarExtractorTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarExtractorTest.java index 9f82420b398..87935e2f708 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarExtractorTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarExtractorTest.java @@ -30,19 +30,18 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Assert; -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; /** Tests for {@link TarExtractor}. */ -public class TarExtractorTest { +class TarExtractorTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testExtract() throws URISyntaxException, IOException { + void testExtract() throws URISyntaxException, IOException { Path source = Paths.get(Resources.getResource("core/extract.tar").toURI()); - Path destination = temporaryFolder.getRoot().toPath(); + Path destination = temporaryFolder; TarExtractor.extract(source, destination); Assert.assertTrue(Files.exists(destination.resolve("file A"))); @@ -57,9 +56,9 @@ public void testExtract() throws URISyntaxException, IOException { } @Test - public void testExtract_missingDirectoryEntries() throws URISyntaxException, IOException { + void testExtract_missingDirectoryEntries() throws URISyntaxException, IOException { Path source = Paths.get(Resources.getResource("core/extract-missing-dirs.tar").toURI()); - Path destination = temporaryFolder.getRoot().toPath(); + Path destination = temporaryFolder; TarExtractor.extract(source, destination); Assert.assertTrue(Files.exists(destination.resolve("world"))); @@ -73,9 +72,9 @@ public void testExtract_missingDirectoryEntries() throws URISyntaxException, IOE } @Test - public void testExtract_symlinks() throws URISyntaxException, IOException { + void testExtract_symlinks() throws URISyntaxException, IOException { Path source = Paths.get(Resources.getResource("core/symlinks.tar").toURI()); - Path destination = temporaryFolder.getRoot().toPath(); + Path destination = temporaryFolder; TarExtractor.extract(source, destination); Assert.assertTrue(Files.isDirectory(destination.resolve("directory1"))); @@ -86,9 +85,9 @@ public void testExtract_symlinks() throws URISyntaxException, IOException { } @Test - public void testExtract_modificationTimePreserved() throws URISyntaxException, IOException { + void testExtract_modificationTimePreserved() throws URISyntaxException, IOException { Path source = Paths.get(Resources.getResource("core/extract.tar").toURI()); - Path destination = temporaryFolder.getRoot().toPath(); + Path destination = temporaryFolder; TarExtractor.extract(source, destination); @@ -105,11 +104,11 @@ public void testExtract_modificationTimePreserved() throws URISyntaxException, I } @Test - public void testExtract_reproducibleTimestampsEnabled() throws URISyntaxException, IOException { + void testExtract_reproducibleTimestampsEnabled() throws URISyntaxException, IOException { // The tarfile has only level1/level2/level3/file.txt packaged Path source = Paths.get(Resources.getResource("core/tarfile-only-file-packaged.tar").toURI()); - Path destination = temporaryFolder.getRoot().toPath(); + Path destination = temporaryFolder; TarExtractor.extract(source, destination, true); @@ -124,9 +123,9 @@ public void testExtract_reproducibleTimestampsEnabled() throws URISyntaxExceptio } @Test - public void testExtract_reproducibleTimestampsEnabled_destinationNotEmpty() throws IOException { - Path destination = temporaryFolder.getRoot().toPath(); - temporaryFolder.newFile(); + void testExtract_reproducibleTimestampsEnabled_destinationNotEmpty() throws IOException { + Path destination = temporaryFolder; + Files.createTempFile(temporaryFolder, "jib", "test"); IllegalStateException exception = assertThrows( diff --git a/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarStreamBuilderTest.java b/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarStreamBuilderTest.java index 19066e29973..5fe76acb8e2 100644 --- a/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarStreamBuilderTest.java +++ b/jib-core/src/test/java/com/google/cloud/tools/jib/tar/TarStreamBuilderTest.java @@ -37,11 +37,11 @@ import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link TarStreamBuilder}. */ -public class TarStreamBuilderTest { +class TarStreamBuilderTest { private Path fileA; private Path fileB; @@ -50,8 +50,8 @@ public class TarStreamBuilderTest { private byte[] fileBContents; private final TarStreamBuilder testTarStreamBuilder = new TarStreamBuilder(); - @Before - public void setup() throws URISyntaxException, IOException { + @BeforeEach + void setup() throws URISyntaxException, IOException { // Gets the test resource files. fileA = Paths.get(Resources.getResource("core/fileA").toURI()); fileB = Paths.get(Resources.getResource("core/fileB").toURI()); @@ -62,43 +62,43 @@ public void setup() throws URISyntaxException, IOException { } @Test - public void testToBlob_tarArchiveEntries() throws IOException { + void testToBlob_tarArchiveEntries() throws IOException { setUpWithTarEntries(); verifyBlobWithoutCompression(); } @Test - public void testToBlob_strings() throws IOException { + void testToBlob_strings() throws IOException { setUpWithStrings(); verifyBlobWithoutCompression(); } @Test - public void testToBlob_stringsAndTarArchiveEntries() throws IOException { + void testToBlob_stringsAndTarArchiveEntries() throws IOException { setUpWithStringsAndTarEntries(); verifyBlobWithoutCompression(); } @Test - public void testToBlob_tarArchiveEntriesWithCompression() throws IOException { + void testToBlob_tarArchiveEntriesWithCompression() throws IOException { setUpWithTarEntries(); verifyBlobWithCompression(); } @Test - public void testToBlob_stringsWithCompression() throws IOException { + void testToBlob_stringsWithCompression() throws IOException { setUpWithStrings(); verifyBlobWithCompression(); } @Test - public void testToBlob_stringsAndTarArchiveEntriesWithCompression() throws IOException { + void testToBlob_stringsAndTarArchiveEntriesWithCompression() throws IOException { setUpWithStringsAndTarEntries(); verifyBlobWithCompression(); } @Test - public void testToBlob_multiByte() throws IOException { + void testToBlob_multiByte() throws IOException { testTarStreamBuilder.addByteEntry( "日本語".getBytes(StandardCharsets.UTF_8), "test", Instant.EPOCH); testTarStreamBuilder.addByteEntry( @@ -137,7 +137,7 @@ public void testToBlob_multiByte() throws IOException { } @Test - public void testToBlob_modificationTime() throws IOException { + void testToBlob_modificationTime() throws IOException { testTarStreamBuilder.addByteEntry( "foo".getBytes(StandardCharsets.UTF_8), "foo", Instant.ofEpochSecond(1234)); testTarStreamBuilder.addBlobEntry( diff --git a/jib-gradle-plugin-extension-api/build.gradle b/jib-gradle-plugin-extension-api/build.gradle index 1478f301273..977be52bf14 100644 --- a/jib-gradle-plugin-extension-api/build.gradle +++ b/jib-gradle-plugin-extension-api/build.gradle @@ -44,7 +44,7 @@ publishing { release { tagTemplate = 'v$version-gradle-extension' git { - requireBranch = /^gradle-extension-release-v\d+.*$/ //regex + requireBranch.set(/^gradle-extension-release-v\d+.*$/) //regex } } /* RELEASE */ diff --git a/jib-gradle-plugin/build.gradle b/jib-gradle-plugin/build.gradle index 46f416ab1ed..4fca76e2658 100644 --- a/jib-gradle-plugin/build.gradle +++ b/jib-gradle-plugin/build.gradle @@ -32,20 +32,21 @@ dependencies { implementation dependencyStrings.GRADLE_EXTENSION - testImplementation dependencyStrings.JUNIT + testImplementation dependencyStrings.JUNIT_API + testRuntimeOnly dependencyStrings.JUNIT_ENGINE testImplementation dependencyStrings.TRUTH testImplementation dependencyStrings.TRUTH8 testImplementation dependencyStrings.MOCKITO_CORE testImplementation dependencyStrings.SLF4J_API testImplementation dependencyStrings.SYSTEM_RULES - + testImplementation dependencyStrings.SYSTEM_RULES_STUB testImplementation project(path:':jib-plugins-common', configuration:'tests') integrationTestImplementation project(path:':jib-core', configuration:'integrationTests') integrationTestImplementation dependencyStrings.JBCRYPT // only for testing a concrete Spring Boot example in a test (not for test infrastructure) - testImplementation 'org.springframework.boot:spring-boot-gradle-plugin:2.2.11.RELEASE' + testImplementation 'org.springframework.boot:spring-boot-gradle-plugin:2.7.13' } /* RELEASE */ @@ -57,17 +58,13 @@ release { 'com.google.cloud.tools:jib-plugins-common', ] git { - requireBranch = /^gradle-release-v\d+.*$/ //regex + requireBranch.set(/^gradle-release-v\d+.*$/) //regex } } // Gradle Plugin Portal releases -pluginBundle { +gradlePlugin { website = 'https://github.com/GoogleContainerTools/jib/' vcsUrl = 'https://github.com/GoogleContainerTools/jib/' - tags = ['google', 'java', 'containers', 'docker', 'kubernetes', 'microservices'] -} - -gradlePlugin { testSourceSets sourceSets.integrationTest, sourceSets.test plugins { jibPlugin { @@ -75,6 +72,7 @@ gradlePlugin { displayName = 'Jib' description = 'Containerize your Java application' implementationClass = 'com.google.cloud.tools.jib.gradle.JibPlugin' + tags.set(['google', 'java', 'containers', 'docker', 'kubernetes', 'microservices']) } } } diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/DefaultTargetProjectIntegrationTest.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/DefaultTargetProjectIntegrationTest.java index 8d78986bc9b..588b7ed75a1 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/DefaultTargetProjectIntegrationTest.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/DefaultTargetProjectIntegrationTest.java @@ -18,19 +18,23 @@ import com.google.cloud.tools.jib.Command; import java.io.IOException; +import java.nio.file.Path; import java.security.DigestException; import org.gradle.testkit.runner.UnexpectedBuildFailure; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Integration tests for building "default-target" project images. */ -public class DefaultTargetProjectIntegrationTest { +class DefaultTargetProjectIntegrationTest { + + @TempDir Path tempDir; @ClassRule - public static final TestProject defaultTargetTestProject = new TestProject("default-target"); + public final TestProject defaultTargetTestProject = new TestProject("default-target", tempDir); /** * Asserts that the test project has the required exposed ports, labels and volumes. @@ -57,7 +61,7 @@ private static void assertDockerInspect(String imageReference) } @Test - public void testBuild_defaultTarget() { + void testBuild_defaultTarget() { // Test error when 'to' is missing try { defaultTargetTestProject.build( @@ -74,8 +78,7 @@ public void testBuild_defaultTarget() { } @Test - public void testDockerDaemon_defaultTarget() - throws IOException, InterruptedException, DigestException { + void testDockerDaemon_defaultTarget() throws IOException, InterruptedException, DigestException { Assert.assertEquals( "Hello, world. An argument.\n", JibRunHelper.buildToDockerDaemonAndRun( diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/EmptyProjectIntegrationTest.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/EmptyProjectIntegrationTest.java index b6398856056..6e983b3534d 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/EmptyProjectIntegrationTest.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/EmptyProjectIntegrationTest.java @@ -22,18 +22,22 @@ import com.google.cloud.tools.jib.IntegrationTestingConfiguration; import com.google.cloud.tools.jib.api.InvalidImageReferenceException; import java.io.IOException; +import java.nio.file.Path; import java.security.DigestException; import java.time.Instant; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Integration tests for building empty project images. */ -public class EmptyProjectIntegrationTest { +class EmptyProjectIntegrationTest { - @ClassRule public static final TestProject emptyTestProject = new TestProject("empty"); + @TempDir Path tempDir; + + @ClassRule public final TestProject emptyTestProject = new TestProject("empty", tempDir); /** * Asserts that the test project has the required exposed ports and labels. @@ -59,7 +63,7 @@ private static void assertDockerInspect(String imageReference) } @Test - public void testBuild_empty() throws IOException, InterruptedException, DigestException { + void testBuild_empty() throws IOException, InterruptedException, DigestException { String targetImage = IntegrationTestingConfiguration.getTestRepositoryLocation() + "/emptyimage:gradle" @@ -70,7 +74,7 @@ public void testBuild_empty() throws IOException, InterruptedException, DigestEx } @Test - public void testBuild_multipleTags() + void testBuild_multipleTags() throws IOException, InterruptedException, InvalidImageReferenceException, DigestException { String targetImage = IntegrationTestingConfiguration.getTestRepositoryLocation() @@ -82,7 +86,7 @@ public void testBuild_multipleTags() } @Test - public void testDockerDaemon_empty() throws IOException, InterruptedException, DigestException { + void testDockerDaemon_empty() throws IOException, InterruptedException, DigestException { String targetImage = "emptyimage:gradle" + System.nanoTime(); Assert.assertEquals( "", JibRunHelper.buildToDockerDaemonAndRun(emptyTestProject, targetImage, "build.gradle")); @@ -91,8 +95,7 @@ public void testDockerDaemon_empty() throws IOException, InterruptedException, D } @Test - public void testDockerDaemon_userNumeric() - throws IOException, InterruptedException, DigestException { + void testDockerDaemon_userNumeric() throws IOException, InterruptedException, DigestException { String targetImage = "emptyimage:gradle" + System.nanoTime(); JibRunHelper.buildToDockerDaemon(emptyTestProject, targetImage, "build.gradle"); Assert.assertEquals( @@ -101,8 +104,7 @@ public void testDockerDaemon_userNumeric() } @Test - public void testDockerDaemon_userNames() - throws IOException, InterruptedException, DigestException { + void testDockerDaemon_userNames() throws IOException, InterruptedException, DigestException { String targetImage = "brokenuserimage:gradle" + System.nanoTime(); JibRunHelper.buildToDockerDaemon(emptyTestProject, targetImage, "build-broken-user.gradle"); Assert.assertEquals( diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/GradleLayerConfigurationIntegrationTest.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/GradleLayerConfigurationIntegrationTest.java index 8595883af52..92acee03185 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/GradleLayerConfigurationIntegrationTest.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/GradleLayerConfigurationIntegrationTest.java @@ -27,17 +27,22 @@ import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class GradleLayerConfigurationIntegrationTest { +class GradleLayerConfigurationIntegrationTest { + + @TempDir Path tempDir; + + @TempDir Path tempDirSimple; @ClassRule - public static final TestProject multiTestProject = new TestProject("all-local-multi-service"); + public final TestProject multiTestProject = new TestProject("all-local-multi-service", tempDir); - @ClassRule public static final TestProject configTestProject = new TestProject("simple"); + @ClassRule public final TestProject configTestProject = new TestProject("simple", tempDirSimple); @Test - public void testGradleLayerConfiguration_configurationName() throws IOException { + void testGradleLayerConfiguration_configurationName() throws IOException { configTestProject.build("jibBuildTar", "-b=build-configuration.gradle"); Path jibTar = configTestProject.getProjectRoot().resolve("build/jib-image.tar"); List> layers = getLayers(jibTar); @@ -54,7 +59,7 @@ public void testGradleLayerConfiguration_configurationName() throws IOException } @Test - public void testGradleLayerConfiguration_configurationName_prioritizeSystemProperty() + void testGradleLayerConfiguration_configurationName_prioritizeSystemProperty() throws IOException { configTestProject.build( "jibBuildTar", @@ -76,7 +81,7 @@ public void testGradleLayerConfiguration_configurationName_prioritizeSystemPrope } @Test - public void testGradleLayerConfiguration_multiModule() throws IOException { + void testGradleLayerConfiguration_multiModule() throws IOException { multiTestProject.build(":complex-service:jibBuildTar"); Path jibTar = multiTestProject.getProjectRoot().resolve("complex-service/build/jib-image.tar"); @@ -133,7 +138,7 @@ public void testGradleLayerConfiguration_multiModule() throws IOException { } @Test - public void testGradleLayerConfiguration_simpleModule() throws IOException { + void testGradleLayerConfiguration_simpleModule() throws IOException { multiTestProject.build(":simple-service:jibBuildTar"); Path jibTar = multiTestProject.getProjectRoot().resolve("simple-service/build/jib-image.tar"); diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/JibRunHelper.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/JibRunHelper.java index 70119236ed4..64f01f6a9be 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/JibRunHelper.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/JibRunHelper.java @@ -39,7 +39,7 @@ import org.junit.Assert; /** Helper class to run integration tests. */ -public class JibRunHelper { +class JibRunHelper { static String buildAndRun(TestProject testProject, String imageReference) throws IOException, InterruptedException, DigestException { @@ -70,8 +70,10 @@ static String buildAndRun( static String buildAndRunFromLocalBase(String target, String base) throws IOException, InterruptedException, DigestException { + SingleProjectIntegrationTest spi = new SingleProjectIntegrationTest(); + BuildResult buildResult = - SingleProjectIntegrationTest.simpleTestProject.build( + spi.simpleTestProject.build( "clean", "jib", "-Djib.useOnlyProjectCache=true", @@ -81,8 +83,7 @@ static String buildAndRunFromLocalBase(String target, String base) "-Djib.allowInsecureRegistries=" + target.startsWith("localhost"), "-b=" + "build-local-base.gradle"); assertBuildSuccess(buildResult, "jib", "Built and pushed image as "); - assertThatExpectedImageDigestAndIdReturned( - SingleProjectIntegrationTest.simpleTestProject.getProjectRoot()); + assertThatExpectedImageDigestAndIdReturned(spi.simpleTestProject.getProjectRoot()); MatcherAssert.assertThat(buildResult.getOutput(), CoreMatchers.containsString(target)); return pullAndRunBuiltImage(target); } diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SingleProjectIntegrationTest.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SingleProjectIntegrationTest.java index 7c53878dc50..2b85e582d87 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SingleProjectIntegrationTest.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SingleProjectIntegrationTest.java @@ -41,12 +41,11 @@ import org.hamcrest.MatcherAssert; import org.junit.Before; import org.junit.ClassRule; -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; /** Integration tests for building single project images. */ -public class SingleProjectIntegrationTest { +class SingleProjectIntegrationTest { @ClassRule public static final LocalRegistry localRegistry1 = @@ -56,9 +55,9 @@ public class SingleProjectIntegrationTest { public static final LocalRegistry localRegistry2 = new LocalRegistry(6000, "testuser", "testpassword"); - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @ClassRule public final TestProject simpleTestProject = new TestProject("simple", tempDir); private final String dockerHost = System.getenv("DOCKER_IP") != null ? System.getenv("DOCKER_IP") : "localhost"; @@ -123,7 +122,7 @@ private static String readDigestFile(Path digestPath) throws IOException, Digest return DescriptorDigest.fromDigest(digest).toString(); } - private static String buildAndRunComplex( + private String buildAndRunComplex( String imageReference, String username, String password, LocalRegistry targetRegistry) throws IOException, InterruptedException { Path baseCache = simpleTestProject.getProjectRoot().resolve("build/jib-base-cache"); @@ -166,13 +165,13 @@ private static String buildAndRunComplex( } @Before - public void setup() throws IOException, InterruptedException { + void setup() throws IOException, InterruptedException { // Pull distroless and push to local registry so we can test 'from' credentials localRegistry1.pullAndPushToLocal("gcr.io/distroless/java:latest", "distroless/java"); } @Test - public void testBuild_simple() + void testBuild_simple() throws IOException, InterruptedException, DigestException, InvalidImageReferenceException { String targetImage = IntegrationTestingConfiguration.getTestRepositoryLocation() @@ -227,8 +226,7 @@ public void testBuild_simple() } @Test - public void testBuild_dockerDaemonBase() - throws IOException, InterruptedException, DigestException { + void testBuild_dockerDaemonBase() throws IOException, InterruptedException, DigestException { String targetImage = IntegrationTestingConfiguration.getTestRepositoryLocation() + "/simplewithdockerdaemonbase:gradle" @@ -250,8 +248,8 @@ public void testBuild_dockerDaemonBase() } @Test - public void testBuild_tarBase() throws IOException, InterruptedException, DigestException { - Path path = temporaryFolder.getRoot().toPath().resolve("docker-save-distroless"); + void testBuild_tarBase() throws IOException, InterruptedException, DigestException { + Path path = tempDir.resolve("docker-save-distroless"); new Command("docker", "save", "gcr.io/distroless/java:latest", "-o", path.toString()).run(); String targetImage = IntegrationTestingConfiguration.getTestRepositoryLocation() @@ -272,7 +270,7 @@ public void testBuild_tarBase() throws IOException, InterruptedException, Digest } @Test - public void testBuild_failOffline() { + void testBuild_failOffline() { String targetImage = IntegrationTestingConfiguration.getTestRepositoryLocation() + "/simpleimageoffline:gradle" @@ -295,8 +293,7 @@ public void testBuild_failOffline() { } @Test - public void testDockerDaemon_simpleOnJava17() - throws DigestException, IOException, InterruptedException { + void testDockerDaemon_simpleOnJava17() throws DigestException, IOException, InterruptedException { assumeTrue(isJavaRuntimeAtLeast(17)); String targetImage = "simpleimage:gradle" + System.nanoTime(); @@ -309,8 +306,7 @@ public void testDockerDaemon_simpleOnJava17() } @Test - public void testDockerDaemon_simpleOnJava11() - throws DigestException, IOException, InterruptedException { + void testDockerDaemon_simpleOnJava11() throws DigestException, IOException, InterruptedException { assumeTrue(isJavaRuntimeAtLeast(11)); String targetImage = "simpleimage:gradle" + System.nanoTime(); @@ -323,7 +319,7 @@ public void testDockerDaemon_simpleOnJava11() } @Test - public void testDockerDaemon_simpleWithIncompatibleJava11() { + void testDockerDaemon_simpleWithIncompatibleJava11() { assumeTrue(isJavaRuntimeAtLeast(11)); Exception exception = @@ -341,7 +337,7 @@ public void testDockerDaemon_simpleWithIncompatibleJava11() { } @Test - public void testDockerDaemon_simple_multipleExtraDirectories() + void testDockerDaemon_simple_multipleExtraDirectories() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String output = @@ -362,7 +358,7 @@ public void testDockerDaemon_simple_multipleExtraDirectories() } @Test - public void testDockerDaemon_simple_multipleExtraDirectoriesWithAlternativeConfig() + void testDockerDaemon_simple_multipleExtraDirectoriesWithAlternativeConfig() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String output = @@ -383,7 +379,7 @@ public void testDockerDaemon_simple_multipleExtraDirectoriesWithAlternativeConfi } @Test - public void testDockerDaemon_simple_multipleExtraDirectoriesWithClosure() + void testDockerDaemon_simple_multipleExtraDirectoriesWithClosure() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String output = @@ -406,7 +402,7 @@ public void testDockerDaemon_simple_multipleExtraDirectoriesWithClosure() } @Test - public void testDockerDaemon_simple_extraDirectoriesFiltering() + void testDockerDaemon_simple_extraDirectoriesFiltering() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); JibRunHelper.buildToDockerDaemon( @@ -423,7 +419,7 @@ public void testDockerDaemon_simple_extraDirectoriesFiltering() } @Test - public void testBuild_complex() + void testBuild_complex() throws IOException, InterruptedException, DigestException, InvalidImageReferenceException { String targetImage = dockerHost + ":6000/compleximage:gradle" + System.nanoTime(); Instant beforeBuild = Instant.now(); @@ -448,7 +444,7 @@ public void testBuild_complex() } @Test - public void testBuild_complex_sameFromAndToRegistry() throws IOException, InterruptedException { + void testBuild_complex_sameFromAndToRegistry() throws IOException, InterruptedException { String targetImage = dockerHost + ":5000/compleximage:gradle" + System.nanoTime(); Instant beforeBuild = Instant.now(); buildAndRunComplex(targetImage, "testuser", "testpassword", localRegistry1); @@ -457,7 +453,7 @@ public void testBuild_complex_sameFromAndToRegistry() throws IOException, Interr } @Test - public void testDockerDaemon_simple() throws IOException, InterruptedException, DigestException { + void testDockerDaemon_simple() throws IOException, InterruptedException, DigestException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String output = JibRunHelper.buildToDockerDaemonAndRun(simpleTestProject, targetImage, "build.gradle"); @@ -478,7 +474,7 @@ public void testDockerDaemon_simple() throws IOException, InterruptedException, } @Test - public void testDockerDaemon_jarContainerization() + void testDockerDaemon_jarContainerization() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String output = @@ -490,7 +486,7 @@ public void testDockerDaemon_jarContainerization() } @Test - public void testBuild_skipDownloadingBaseImageLayers() throws IOException, InterruptedException { + void testBuild_skipDownloadingBaseImageLayers() throws IOException, InterruptedException { Path baseLayersCacheDirectory = simpleTestProject.getProjectRoot().resolve("build/jib-base-cache/layers"); String targetImage = dockerHost + ":6000/simpleimage:gradle" + System.nanoTime(); @@ -506,7 +502,7 @@ public void testBuild_skipDownloadingBaseImageLayers() throws IOException, Inter } @Test - public void testDockerDaemon_timestampCustom() + void testDockerDaemon_timestampCustom() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String output = @@ -520,7 +516,7 @@ public void testDockerDaemon_timestampCustom() } @Test - public void testBuild_dockerClient() throws IOException, InterruptedException, DigestException { + void testBuild_dockerClient() throws IOException, InterruptedException, DigestException { assumeFalse(System.getProperty("os.name").startsWith("Windows")); new Command( "chmod", "+x", simpleTestProject.getProjectRoot().resolve("mock-docker.sh").toString()) @@ -545,7 +541,7 @@ public void testBuild_dockerClient() throws IOException, InterruptedException, D } @Test - public void testBuildTar_simple() throws IOException, InterruptedException { + void testBuildTar_simple() throws IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); String outputPath = @@ -584,8 +580,7 @@ public void testBuildTar_simple() throws IOException, InterruptedException { } @Test - public void testCredHelperConfiguration() - throws DigestException, IOException, InterruptedException { + void testCredHelperConfiguration() throws DigestException, IOException, InterruptedException { String targetImage = "simpleimage:gradle" + System.nanoTime(); assertThat( JibRunHelper.buildToDockerDaemonAndRun( diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SpringBootProjectIntegrationTest.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SpringBootProjectIntegrationTest.java index dca766587b4..cbe97b3c32d 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SpringBootProjectIntegrationTest.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/SpringBootProjectIntegrationTest.java @@ -21,29 +21,33 @@ import com.google.cloud.tools.jib.api.HttpRequestTester; import java.io.IOException; import java.net.URL; +import java.nio.file.Path; import java.security.DigestException; import javax.annotation.Nullable; import org.junit.After; import org.junit.Assert; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Integration tests for building Spring Boot images. */ -public class SpringBootProjectIntegrationTest { +class SpringBootProjectIntegrationTest { - @ClassRule public static final TestProject springBootProject = new TestProject("spring-boot"); + @TempDir Path tempDir; + + @ClassRule public final TestProject springBootProject = new TestProject("spring-boot", tempDir); @Nullable private String containerName; @After - public void tearDown() throws IOException, InterruptedException { + void tearDown() throws IOException, InterruptedException { if (containerName != null) { new Command("docker", "stop", containerName).run(); } } @Test - public void testBuild_packagedMode() throws IOException, InterruptedException, DigestException { + void testBuild_packagedMode() throws IOException, InterruptedException, DigestException { buildAndRunWebApp("springboot:gradle", "build.gradle"); String output = diff --git a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/WarProjectIntegrationTest.java b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/WarProjectIntegrationTest.java index dbcf72940ba..650c7cee5c4 100644 --- a/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/WarProjectIntegrationTest.java +++ b/jib-gradle-plugin/src/integration-test/java/com/google/cloud/tools/jib/gradle/WarProjectIntegrationTest.java @@ -21,34 +21,37 @@ import com.google.cloud.tools.jib.api.HttpRequestTester; import java.io.IOException; import java.net.URL; +import java.nio.file.Path; import java.security.DigestException; import javax.annotation.Nullable; import org.junit.After; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Integration tests for building WAR images. */ -public class WarProjectIntegrationTest { +class WarProjectIntegrationTest { - @ClassRule public static final TestProject servlet25Project = new TestProject("war_servlet25"); + @TempDir Path tempDir; + + @ClassRule public final TestProject servlet25Project = new TestProject("war_servlet25", tempDir); @Nullable private String containerName; @After - public void tearDown() throws IOException, InterruptedException { + void tearDown() throws IOException, InterruptedException { if (containerName != null) { new Command("docker", "stop", containerName).run(); } } @Test - public void testBuild_jettyServlet25() throws IOException, InterruptedException, DigestException { + void testBuild_jettyServlet25() throws IOException, InterruptedException, DigestException { verifyBuildAndRun(servlet25Project, "war_jetty_servlet25:gradle", "build.gradle"); } @Test - public void testBuild_tomcatServlet25() - throws IOException, InterruptedException, DigestException { + void testBuild_tomcatServlet25() throws IOException, InterruptedException, DigestException { verifyBuildAndRun(servlet25Project, "war_tomcat_servlet25:gradle", "build-tomcat.gradle"); } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildDockerTask.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildDockerTask.java index 692449db037..86f29eef12d 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildDockerTask.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildDockerTask.java @@ -44,6 +44,7 @@ import javax.annotation.Nullable; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; +import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.options.Option; @@ -54,6 +55,7 @@ public class BuildDockerTask extends DefaultTask implements JibTask { private static final String HELPFUL_SUGGESTIONS_PREFIX = "Build to Docker daemon failed"; @Nullable private JibExtension jibExtension; + @Nullable private GradleProjectProperties projectProperties; /** * This will call the property {@code "jib"} so that it is the same name as the extension. This @@ -63,10 +65,17 @@ public class BuildDockerTask extends DefaultTask implements JibTask { */ @Nested @Nullable + @SuppressWarnings("java:S106") public JibExtension getJib() { return jibExtension; } + @Nullable + @Internal + public GradleProjectProperties getProjectProperties() { + return projectProperties; + } + /** * The target image can be overridden with the {@code --image} command line option. * @@ -91,6 +100,7 @@ public void buildDocker() throws IOException, BuildStepsExecutionException, CacheDirectoryCreationException, MainClassInferenceException, InvalidGlobalConfigException { Preconditions.checkNotNull(jibExtension); + Preconditions.checkNotNull(projectProperties); // Check deprecated parameters Path dockerExecutable = jibExtension.getDockerClient().getExecutablePath(); @@ -104,23 +114,16 @@ public void buildDocker() } TaskCommon.disableHttpLogging(); - TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider(); - GradleProjectProperties projectProperties = - GradleProjectProperties.getForProject( - getProject(), - getLogger(), - tempDirectoryProvider, - jibExtension.getConfigurationName().get()); GlobalConfig globalConfig = GlobalConfig.readConfig(); Future> updateCheckFuture = - TaskCommon.newUpdateChecker(projectProperties, globalConfig, getLogger()); - try { + TaskCommon.newUpdateChecker(this.projectProperties, globalConfig, getLogger()); + try (TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider()) { PluginConfigurationProcessor.createJibBuildRunnerForDockerDaemonImage( new GradleRawConfiguration(jibExtension), ignored -> java.util.Optional.empty(), - projectProperties, + this.projectProperties, globalConfig, new GradleHelpfulSuggestions(HELPFUL_SUGGESTIONS_PREFIX)) .runBuild(); @@ -187,8 +190,7 @@ public void buildDocker() + ex.getPath(), ex); } finally { - tempDirectoryProvider.close(); - TaskCommon.finishUpdateChecker(projectProperties, updateCheckFuture); + TaskCommon.finishUpdateChecker(this.projectProperties, updateCheckFuture); projectProperties.waitForLoggingThread(); } } @@ -196,6 +198,12 @@ public void buildDocker() @Override public BuildDockerTask setJibExtension(JibExtension jibExtension) { this.jibExtension = jibExtension; + this.projectProperties = + GradleProjectProperties.getForProject( + getProject(), + getLogger(), + new TempDirectoryProvider(), + jibExtension.getConfigurationName().get()); return this; } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildImageTask.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildImageTask.java index 49265559a61..2aef54bbef4 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildImageTask.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildImageTask.java @@ -43,6 +43,7 @@ import javax.annotation.Nullable; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; +import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.options.Option; @@ -54,6 +55,8 @@ public class BuildImageTask extends DefaultTask implements JibTask { @Nullable private JibExtension jibExtension; + @Nullable private GradleProjectProperties projectProperties; + /** * This will call the property {@code "jib"} so that it is the same name as the extension. This * way, the user would see error messages for missing configuration with the prefix {@code jib.}. @@ -66,6 +69,12 @@ public JibExtension getJib() { return jibExtension; } + @Nullable + @Internal + public GradleProjectProperties getProjectProperties() { + return projectProperties; + } + /** * The target image can be overridden with the {@code --image} command line option. * @@ -91,15 +100,9 @@ public void buildImage() MainClassInferenceException, InvalidGlobalConfigException { // Asserts required @Input parameters are not null. Preconditions.checkNotNull(jibExtension); + Preconditions.checkNotNull(projectProperties); TaskCommon.disableHttpLogging(); - TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider(); - GradleProjectProperties projectProperties = - GradleProjectProperties.getForProject( - getProject(), - getLogger(), - tempDirectoryProvider, - jibExtension.getConfigurationName().get()); GlobalConfig globalConfig = GlobalConfig.readConfig(); Future> updateCheckFuture = TaskCommon.newUpdateChecker(projectProperties, globalConfig, getLogger()); @@ -182,15 +185,28 @@ public void buildImage() + ex.getPath(), ex); } finally { - tempDirectoryProvider.close(); - TaskCommon.finishUpdateChecker(projectProperties, updateCheckFuture); - projectProperties.waitForLoggingThread(); + + if (projectProperties != null) { + TempDirectoryProvider tempDirectoryProvider = projectProperties.getTempDirectoryProvider(); + if (tempDirectoryProvider != null) { + tempDirectoryProvider.close(); + } + TaskCommon.finishUpdateChecker(projectProperties, updateCheckFuture); + projectProperties.waitForLoggingThread(); + } } } @Override public BuildImageTask setJibExtension(JibExtension jibExtension) { this.jibExtension = jibExtension; + this.projectProperties = + GradleProjectProperties.getForProject( + getProject(), + getLogger(), + new TempDirectoryProvider(), + jibExtension.getConfigurationName().get()); + return this; } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildTarTask.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildTarTask.java index 1a77856b6b0..4f4219da378 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildTarTask.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/BuildTarTask.java @@ -47,6 +47,7 @@ import org.gradle.api.GradleException; import org.gradle.api.file.FileCollection; import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; @@ -71,6 +72,8 @@ public JibExtension getJib() { return jibExtension; } + @Nullable private GradleProjectProperties projectProperties; + /** * The target image can be overridden with the {@code --image} command line option. * @@ -81,6 +84,12 @@ public void setTargetImage(String targetImage) { Preconditions.checkNotNull(jibExtension).getTo().setImage(targetImage); } + @Nullable + @Internal + public GradleProjectProperties getProjectProperties() { + return projectProperties; + } + /** * Returns a collection of all the files that jib includes in the image. Only used to calculate * UP-TO-DATE. @@ -122,23 +131,19 @@ public void buildTar() MainClassInferenceException, InvalidGlobalConfigException { // Asserts required @Input parameters are not null. Preconditions.checkNotNull(jibExtension); + Preconditions.checkNotNull(projectProperties); TaskCommon.disableHttpLogging(); - TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider(); - GradleProjectProperties projectProperties = - GradleProjectProperties.getForProject( - getProject(), - getLogger(), - tempDirectoryProvider, - jibExtension.getConfigurationName().get()); GlobalConfig globalConfig = GlobalConfig.readConfig(); Future> updateCheckFuture = - TaskCommon.newUpdateChecker(projectProperties, globalConfig, getLogger()); - try { + TaskCommon.newUpdateChecker(this.projectProperties, globalConfig, getLogger()); + + try (TempDirectoryProvider tempDirectoryProvider = new TempDirectoryProvider()) { + PluginConfigurationProcessor.createJibBuildRunnerForTarImage( new GradleRawConfiguration(jibExtension), ignored -> Optional.empty(), - projectProperties, + this.projectProperties, globalConfig, new GradleHelpfulSuggestions(HELPFUL_SUGGESTIONS_PREFIX)) .runBuild(); @@ -204,7 +209,6 @@ public void buildTar() + ex.getPath(), ex); } finally { - tempDirectoryProvider.close(); TaskCommon.finishUpdateChecker(projectProperties, updateCheckFuture); projectProperties.waitForLoggingThread(); } @@ -213,6 +217,12 @@ public void buildTar() @Override public BuildTarTask setJibExtension(JibExtension jibExtension) { this.jibExtension = jibExtension; + this.projectProperties = + GradleProjectProperties.getForProject( + getProject(), + getLogger(), + new TempDirectoryProvider(), + jibExtension.getConfigurationName().get()); return this; } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoriesParameters.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoriesParameters.java index 30dc526e89b..c74ea7e8894 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoriesParameters.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoriesParameters.java @@ -19,6 +19,7 @@ import com.google.cloud.tools.jib.plugins.common.ConfigurationPropertyValidator; import com.google.cloud.tools.jib.plugins.common.PropertyNames; import java.io.File; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; @@ -33,14 +34,15 @@ import org.gradle.api.provider.MapProperty; import org.gradle.api.provider.Provider; import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.Internal; +import org.gradle.api.tasks.Nested; +import org.gradle.api.tasks.Optional; /** Object in {@link JibExtension} that configures the extra directories. */ public class ExtraDirectoriesParameters { private final ObjectFactory objects; - private final Project project; - + private final Path projectPath; + private final Provider extraDirPaths; private ListProperty paths; private ExtraDirectoryParametersSpec spec; private MapProperty permissions; @@ -48,10 +50,12 @@ public class ExtraDirectoriesParameters { @Inject public ExtraDirectoriesParameters(ObjectFactory objects, Project project) { this.objects = objects; - this.project = project; paths = objects.listProperty(ExtraDirectoryParameters.class).empty(); spec = objects.newInstance(ExtraDirectoryParametersSpec.class, project, paths); permissions = objects.mapProperty(String.class, String.class).empty(); + this.projectPath = project.getProjectDir().toPath(); + this.extraDirPaths = + project.getProviders().systemProperty(PropertyNames.EXTRA_DIRECTORIES_PATHS); } public void paths(Action action) { @@ -59,32 +63,26 @@ public void paths(Action action) { } @Input - public List getPathStrings() { - // Gradle warns about @Input annotations on File objects, so we have to expose a getter for a - // String to make them go away. - return getPaths().stream() - .map(extraDirectoryParameters -> extraDirectoryParameters.getFrom().toString()) - .collect(Collectors.toList()); + @Optional + public Provider getExtraDirPaths() { + return extraDirPaths; } - @Internal + @Nested public List getPaths() { // Gradle warns about @Input annotations on File objects, so we have to expose a getter for a // String to make them go away. - String property = System.getProperty(PropertyNames.EXTRA_DIRECTORIES_PATHS); - if (property != null) { - List pathStrings = ConfigurationPropertyValidator.parseListProperty(property); + if (this.extraDirPaths.isPresent()) { + List pathStrings = + ConfigurationPropertyValidator.parseListProperty(this.extraDirPaths.get()); return pathStrings.stream() - .map(path -> new ExtraDirectoryParameters(objects, project, Paths.get(path), "/")) + .map(path -> new ExtraDirectoryParameters(objects, Paths.get(path), "/")) .collect(Collectors.toList()); } if (paths.get().isEmpty()) { return Collections.singletonList( new ExtraDirectoryParameters( - objects, - project, - project.getProjectDir().toPath().resolve("src").resolve("main").resolve("jib"), - "/")); + objects, projectPath.resolve("src").resolve("main").resolve("jib"), "/")); } return paths.get(); } @@ -115,8 +113,8 @@ public void setPaths(Provider paths) { */ @Nonnull private List convertToExtraDirectoryParametersList(Object obj) { - return project.files(obj).getFiles().stream() - .map(file -> new ExtraDirectoryParameters(objects, project, file.toPath(), "/")) + return this.objects.fileCollection().from(obj).getFiles().stream() + .map(file -> new ExtraDirectoryParameters(objects, file.toPath(), "/")) .collect(Collectors.toList()); } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParameters.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParameters.java index 537b51f085d..934d04859f9 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParameters.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParameters.java @@ -18,60 +18,47 @@ import com.google.cloud.tools.jib.plugins.common.RawConfiguration.ExtraDirectoriesConfiguration; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import javax.inject.Inject; -import org.gradle.api.Project; +import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.Property; import org.gradle.api.provider.Provider; import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; /** Configuration of an extra directory. */ public class ExtraDirectoryParameters implements ExtraDirectoriesConfiguration { - private Project project; - private Property from; + ConfigurableFileCollection from; private Property into; private ListProperty includes; private ListProperty excludes; @Inject - public ExtraDirectoryParameters(ObjectFactory objects, Project project) { - this.project = project; - this.from = objects.property(Path.class).value(Paths.get("")); + public ExtraDirectoryParameters(ObjectFactory objects) { + this.from = objects.fileCollection(); this.into = objects.property(String.class).value("/"); this.includes = objects.listProperty(String.class).empty(); this.excludes = objects.listProperty(String.class).empty(); } - ExtraDirectoryParameters(ObjectFactory objects, Project project, Path from, String into) { - this(objects, project); - this.from = objects.property(Path.class).value(from); + ExtraDirectoryParameters(ObjectFactory objects, Path from, String into) { + this(objects); + this.from = objects.fileCollection().from(from); this.into = objects.property(String.class).value(into); } - @Input - public String getFromString() { - // Gradle warns about @Input annotations on File objects, so we have to expose a getter for a - // String to make them go away. - return from.get().toString(); - } - @Override - @Internal + @InputFiles public Path getFrom() { - return from.get(); + return from.getSingleFile().toPath(); } public void setFrom(Object from) { - this.from.set(project.file(from).toPath()); - } - - public void setFrom(Provider from) { - this.from.set(from.map(obj -> project.file(obj).toPath())); + this.from.from(from); } @Override diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParametersSpec.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParametersSpec.java index 53c57779c67..72dd4c2c21a 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParametersSpec.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/ExtraDirectoryParametersSpec.java @@ -19,18 +19,27 @@ import javax.inject.Inject; import org.gradle.api.Action; import org.gradle.api.Project; +import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.ListProperty; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Nested; /** Allows to add {@link ExtraDirectoryParameters} objects to the list property of the same type. */ public class ExtraDirectoryParametersSpec { - private final Project project; private final ListProperty paths; + private final ObjectFactory objectFactory; + /** + * Spec init. + * + * @param project Project handle + * @param paths Provider for extra dirs + */ @Inject public ExtraDirectoryParametersSpec( Project project, ListProperty paths) { - this.project = project; + this.objectFactory = project.getObjects(); this.paths = paths; } @@ -41,8 +50,14 @@ public ExtraDirectoryParametersSpec( */ public void path(Action action) { ExtraDirectoryParameters extraDirectory = - project.getObjects().newInstance(ExtraDirectoryParameters.class, project); + objectFactory.newInstance(ExtraDirectoryParameters.class); action.execute(extraDirectory); paths.add(extraDirectory); } + + @Input + @Nested + public ListProperty getPaths() { + return paths; + } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/GradleProjectProperties.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/GradleProjectProperties.java index 6a1978fe192..8ea8615f066 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/GradleProjectProperties.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/GradleProjectProperties.java @@ -69,10 +69,16 @@ import org.gradle.api.artifacts.ResolvedArtifact; import org.gradle.api.artifacts.component.ProjectComponentIdentifier; import org.gradle.api.file.FileCollection; +import org.gradle.api.file.RegularFile; import org.gradle.api.logging.Logger; +import org.gradle.api.model.ObjectFactory; import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.plugins.WarPlugin; +import org.gradle.api.provider.Property; import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.Classpath; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.TaskProvider; @@ -98,6 +104,35 @@ public class GradleProjectProperties implements ProjectProperties { private static final String MAIN_SOURCE_SET_NAME = "main"; private static final Duration LOGGING_THREAD_SHUTDOWN_TIMEOUT = Duration.ofSeconds(1); + private final ObjectFactory objectFactory; + private final Logger logger; + private Path defaultCacheDirectory; + private Boolean warProject; + private Integer majorJavaVersion; + private Boolean offline; + private String name; + private String version; + private String warFilePath = ""; + + private Provider jarArchive; + private Property jarManifestMainClass; + + FileCollection classesOutputDirectories; + + Path resourcesOutputDirectory; + private Property progressFooterEnabled; + + @Input + @Classpath + public Path getResourcesOutputDirectory() { + return resourcesOutputDirectory; + } + + @Input + @Classpath + public FileCollection getClassesOutputDirectories() { + return classesOutputDirectories; + } /** * Generate an instance for a gradle project. @@ -127,7 +162,7 @@ public static GradleProjectProperties getForProject( project, logger, tempDirectoryProvider, extensionLoader, configurationName); } - String getWarFilePath() { + String getWarFilePath(Project project) { TaskProvider bootWarTask = TaskCommon.getBootWarTaskProvider(project); if (bootWarTask != null && bootWarTask.get().getEnabled()) { return bootWarTask.get().getOutputs().getFiles().getAsPath(); @@ -138,7 +173,7 @@ String getWarFilePath() { } private static boolean isProgressFooterEnabled(Project project) { - if ("plain".equals(System.getProperty(PropertyNames.CONSOLE))) { + if ("plain".equals(project.getProviders().systemProperty(PropertyNames.CONSOLE).getOrNull())) { return false; } @@ -157,12 +192,18 @@ private static boolean isProgressFooterEnabled(Project project) { } } - private final Project project; - private final SingleThreadedExecutor singleThreadedExecutor = new SingleThreadedExecutor(); - private final ConsoleLogger consoleLogger; + @VisibleForTesting + transient SingleThreadedExecutor singleThreadedExecutor = new SingleThreadedExecutor(); + + @Nullable private transient ConsoleLogger consoleLogger; + private final TempDirectoryProvider tempDirectoryProvider; private final Supplier>> extensionLoader; - private final String configurationName; + + private static final Object lock = new Object(); + FileCollection projectDependencies; + FileCollection allFiles; + FileCollection runtimeClasspath; @VisibleForTesting GradleProjectProperties( @@ -171,47 +212,72 @@ private static boolean isProgressFooterEnabled(Project project) { TempDirectoryProvider tempDirectoryProvider, Supplier>> extensionLoader, String configurationName) { - this.project = project; + JavaPluginExtension javaPluginExtension = + project.getExtensions().getByType(JavaPluginExtension.class); this.tempDirectoryProvider = tempDirectoryProvider; this.extensionLoader = extensionLoader; - this.configurationName = configurationName; - ConsoleLoggerBuilder consoleLoggerBuilder = - (isProgressFooterEnabled(project) - ? ConsoleLoggerBuilder.rich(singleThreadedExecutor, false) - : ConsoleLoggerBuilder.plain(singleThreadedExecutor).progress(logger::lifecycle)) - .lifecycle(logger::lifecycle); - if (logger.isDebugEnabled()) { - consoleLoggerBuilder.debug(logger::debug); + this.warProject = project.getPlugins().hasPlugin(WarPlugin.class); + this.defaultCacheDirectory = project.getBuildDir().toPath().resolve(CACHE_DIRECTORY_NAME); + this.offline = project.getGradle().getStartParameter().isOffline(); + this.version = project.getVersion() != null ? project.getVersion().toString() : ""; + this.objectFactory = project.getObjects(); + this.jarArchive = this.objectFactory.fileProperty(); + this.jarManifestMainClass = this.objectFactory.property(String.class); + this.logger = logger; + this.progressFooterEnabled = project.getObjects().property(Boolean.class); + this.progressFooterEnabled.set(isProgressFooterEnabled(project)); + this.projectDependencies = + project.files( + project.getConfigurations().getByName(configurationName).getResolvedConfiguration() + .getResolvedArtifacts().stream() + .filter( + artifact -> + artifact.getId().getComponentIdentifier() + instanceof ProjectComponentIdentifier) + .map(ResolvedArtifact::getFile) + .collect(Collectors.toList())); + + this.allFiles = project.getConfigurations().getByName(configurationName).filter(File::exists); + this.runtimeClasspath = project.getConfigurations().getByName(configurationName); + Task jarTask = project.getTasks().findByName("jar"); + if (jarTask != null) { + this.jarArchive = ((Jar) jarTask).getArchiveFile(); + this.jarManifestMainClass.set(computeMainClassFromJarPlugin((Jar) jarTask)); } - if (logger.isInfoEnabled()) { - consoleLoggerBuilder.info(logger::info); - } - if (logger.isWarnEnabled()) { - consoleLoggerBuilder.warn(logger::warn); + + SourceSet mainSourceSet = javaPluginExtension.getSourceSets().getByName(MAIN_SOURCE_SET_NAME); + this.classesOutputDirectories = mainSourceSet.getOutput().getClassesDirs().filter(File::exists); + this.resourcesOutputDirectory = mainSourceSet.getOutput().getResourcesDir().toPath(); + + this.name = project.getName(); + JavaVersion ver = javaPluginExtension.getTargetCompatibility(); + + this.majorJavaVersion = Integer.valueOf(ver.getMajorVersion()); + + if (isWarProject()) { + this.warFilePath = getWarFilePath(project); } - if (logger.isErrorEnabled()) { - consoleLoggerBuilder.error(logger::error); + } + + public TempDirectoryProvider getTempDirectoryProvider() { + return tempDirectoryProvider; + } + + @Internal + @VisibleForTesting + synchronized SingleThreadedExecutor getSingleThreadedExecutor() { + if (singleThreadedExecutor == null) { + this.singleThreadedExecutor = new SingleThreadedExecutor(); } - consoleLogger = consoleLoggerBuilder.build(); + return this.singleThreadedExecutor; } @Override public JibContainerBuilder createJibContainerBuilder( JavaContainerBuilder javaContainerBuilder, ContainerizingMode containerizingMode) { try { - FileCollection projectDependencies = - project.files( - project.getConfigurations().getByName(configurationName).getResolvedConfiguration() - .getResolvedArtifacts().stream() - .filter( - artifact -> - artifact.getId().getComponentIdentifier() - instanceof ProjectComponentIdentifier) - .map(ResolvedArtifact::getFile) - .collect(Collectors.toList())); if (isWarProject()) { - String warFilePath = getWarFilePath(); log(LogEvent.info("WAR project identified, creating WAR image from: " + warFilePath)); Path explodedWarPath = tempDirectoryProvider.newDirectory(); ZipUtil.unzip(Paths.get(warFilePath), explodedWarPath); @@ -221,13 +287,6 @@ public JibContainerBuilder createJibContainerBuilder( projectDependencies.getFiles().stream().map(File::getName).collect(Collectors.toSet())); } - SourceSet mainSourceSet = getMainSourceSet(); - FileCollection classesOutputDirectories = - mainSourceSet.getOutput().getClassesDirs().filter(File::exists); - Path resourcesOutputDirectory = mainSourceSet.getOutput().getResourcesDir().toPath(); - FileCollection allFiles = - project.getConfigurations().getByName(configurationName).filter(File::exists); - FileCollection nonProjectDependencies = allFiles .minus(classesOutputDirectories) @@ -269,10 +328,7 @@ public JibContainerBuilder createJibContainerBuilder( case PACKAGED: // Add a JAR - Jar jarTask = (Jar) project.getTasks().findByName("jar"); - Path jarPath = jarTask.getArchiveFile().get().getAsFile().toPath(); - log(LogEvent.debug("Using JAR: " + jarPath)); - javaContainerBuilder.addToClasspath(jarPath); + extractedJar(javaContainerBuilder); break; default: @@ -286,11 +342,15 @@ public JibContainerBuilder createJibContainerBuilder( } } + private void extractedJar(JavaContainerBuilder javaContainerBuilder) throws IOException { + Path jarPath = this.jarArchive.get().getAsFile().toPath(); + log(LogEvent.debug("Using JAR: " + jarPath)); + javaContainerBuilder.addToClasspath(jarPath); + } + @Override public List getClassFiles() throws IOException { // TODO: Consolidate with createJibContainerBuilder - FileCollection classesOutputDirectories = - getMainSourceSet().getOutput().getClassesDirs().filter(File::exists); List classFiles = new ArrayList<>(); for (File classesOutputDirectory : classesOutputDirectories) { classFiles.addAll(new DirectoryWalker(classesOutputDirectory.toPath()).walk()); @@ -301,7 +361,7 @@ public List getClassFiles() throws IOException { @Override public List getDependencies() { List dependencies = new ArrayList<>(); - FileCollection runtimeClasspath = project.getConfigurations().getByName(configurationName); + // To be on the safe side with the order, calling "forEach" first (no filtering operations). runtimeClasspath.forEach( file -> { @@ -316,7 +376,7 @@ public List getDependencies() { @Override public void waitForLoggingThread() { - singleThreadedExecutor.shutDownAndAwaitTermination(LOGGING_THREAD_SHUTDOWN_TIMEOUT); + getSingleThreadedExecutor().shutDownAndAwaitTermination(LOGGING_THREAD_SHUTDOWN_TIMEOUT); } @Override @@ -333,13 +393,43 @@ TimerEvent.class, new TimerEventHandler(message -> log(LogEvent.debug(message))) ProgressDisplayGenerator.generateProgressDisplay( update.getProgress(), update.getUnfinishedLeafTasks()); footer.add(""); - consoleLogger.setFooter(footer); + getConsoleLogger().setFooter(footer); })); } @Override public void log(LogEvent logEvent) { - consoleLogger.log(logEvent.getLevel(), logEvent.getMessage()); + getConsoleLogger().log(logEvent.getLevel(), logEvent.getMessage()); + } + + @Internal + @VisibleForTesting + ConsoleLogger getConsoleLogger() { + synchronized (lock) { + if (this.consoleLogger == null) { + ConsoleLoggerBuilder consoleLoggerBuilder = + (Boolean.TRUE.equals(this.progressFooterEnabled.get()) + ? ConsoleLoggerBuilder.rich(getSingleThreadedExecutor(), false) + : ConsoleLoggerBuilder.plain(getSingleThreadedExecutor()) + .progress(logger::lifecycle)) + .lifecycle(logger::lifecycle); + if (logger.isDebugEnabled()) { + consoleLoggerBuilder.debug(logger::debug); + } + if (logger.isInfoEnabled()) { + consoleLoggerBuilder.info(logger::info); + } + if (logger.isWarnEnabled()) { + consoleLoggerBuilder.warn(logger::warn); + } + if (logger.isErrorEnabled()) { + consoleLoggerBuilder.error(logger::error); + } + this.consoleLogger = consoleLoggerBuilder.build(); + } + } + + return consoleLogger; } @Override @@ -360,12 +450,19 @@ public String getPluginName() { @Nullable @Override public String getMainClassFromJarPlugin() { - Jar jarTask = (Jar) project.getTasks().findByName("jar"); - if (jarTask == null) { + if (!this.jarArchive.isPresent()) { + return null; + } + return this.jarManifestMainClass.getOrNull(); + } + + @Nullable + private String computeMainClassFromJarPlugin(Jar task) { + if (!this.jarArchive.isPresent()) { return null; } - Object value = jarTask.getManifest().getAttributes().get("Main-Class"); + Object value = task.getManifest().getAttributes().get("Main-Class"); if (value instanceof Provider) { value = ((Provider) value).getOrNull(); @@ -384,7 +481,7 @@ public String getMainClassFromJarPlugin() { @Override public Path getDefaultCacheDirectory() { - return project.getBuildDir().toPath().resolve(CACHE_DIRECTORY_NAME); + return this.defaultCacheDirectory; } @Override @@ -394,7 +491,7 @@ public String getJarPluginName() { @Override public boolean isWarProject() { - return project.getPlugins().hasPlugin(WarPlugin.class); + return this.warProject; } /** @@ -430,34 +527,29 @@ static FileCollection getInputFiles( @Override public String getName() { - return project.getName(); + return this.name; } @Override public String getVersion() { - return project.getVersion().toString(); + return this.version; } @Override public int getMajorJavaVersion() { - JavaVersion version = JavaVersion.current(); - JavaPluginExtension javaPluginExtension = - project.getExtensions().findByType(JavaPluginExtension.class); - if (javaPluginExtension != null) { - version = javaPluginExtension.getTargetCompatibility(); - } - return Integer.valueOf(version.getMajorVersion()); + return this.majorJavaVersion; } @Override public boolean isOffline() { - return project.getGradle().getStartParameter().isOffline(); + return this.offline; } @Override public JibContainerBuilder runPluginExtensions( List extensionConfigs, - JibContainerBuilder jibContainerBuilder) + JibContainerBuilder jibContainerBuilder, + Optional project) throws JibPluginExtensionException { if (extensionConfigs.isEmpty()) { log(LogEvent.debug("No Jib plugin extensions configured to load")); @@ -472,8 +564,9 @@ public JibContainerBuilder runPluginExtensions( extension = findConfiguredExtension(loadedExtensions, config); log(LogEvent.lifecycle("Running extension: " + config.getExtensionClass())); + Project proj = (Project) project.orElseThrow(IllegalStateException::new); buildPlan = - runPluginExtension(extension.getExtraConfigType(), extension, config, buildPlan); + runPluginExtension(extension.getExtraConfigType(), extension, config, buildPlan, proj); ImageReference.parse(buildPlan.getBaseImage()); // to validate image reference } return jibContainerBuilder.applyContainerBuildPlan(buildPlan); @@ -494,7 +587,8 @@ private ContainerBuildPlan runPluginExtension( Optional> extraConfigType, JibGradlePluginExtension extension, ExtensionConfiguration config, - ContainerBuildPlan buildPlan) + ContainerBuildPlan buildPlan, + Project project) throws JibPluginExtensionException { T extraConfig = null; Optional configs = config.getExtraConfiguration(); @@ -509,7 +603,7 @@ private ContainerBuildPlan runPluginExtension( // configs.get() is of type Action, so this cast always succeeds. // (Note generic is erased at runtime.) Action action = (Action) configs.get(); - extraConfig = project.getObjects().newInstance(extraConfigType.get(), project); + extraConfig = this.objectFactory.newInstance(extraConfigType.get(), project); action.execute(extraConfig); } } @@ -543,10 +637,4 @@ private JibGradlePluginExtension findConfiguredExtension( } return found.get(); } - - private SourceSet getMainSourceSet() { - SourceSetContainer sourceSetContainer = - project.getExtensions().getByType(SourceSetContainer.class); - return sourceSetContainer.getByName(MAIN_SOURCE_SET_NAME); - } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/JibPlugin.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/JibPlugin.java index 6f2d9d16d17..a1eacfbaa38 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/JibPlugin.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/JibPlugin.java @@ -16,6 +16,8 @@ package com.google.cloud.tools.jib.gradle; +import static org.gradle.api.tasks.SourceSet.MAIN_SOURCE_SET_NAME; + import com.google.cloud.tools.jib.gradle.skaffold.CheckJibVersionTask; import com.google.cloud.tools.jib.gradle.skaffold.FilesTaskV2; import com.google.cloud.tools.jib.gradle.skaffold.InitTask; @@ -30,8 +32,8 @@ import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.Task; +import org.gradle.api.plugins.JavaPluginExtension; import org.gradle.api.tasks.SourceSet; -import org.gradle.api.tasks.SourceSetContainer; import org.gradle.api.tasks.TaskContainer; import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.bundling.Jar; @@ -39,7 +41,7 @@ public class JibPlugin implements Plugin { - @VisibleForTesting static final GradleVersion GRADLE_MIN_VERSION = GradleVersion.version("5.1"); + @VisibleForTesting static final GradleVersion GRADLE_MIN_VERSION = GradleVersion.version("8.0"); public static final String JIB_EXTENSION_NAME = "jib"; public static final String BUILD_IMAGE_TASK_NAME = "jib"; @@ -101,6 +103,7 @@ public void apply(Project project) { BuildImageTask.class, task -> { task.setGroup("Jib"); + task.setDescription("Builds a container image to a registry."); task.setJibExtension(jibExtension); }); @@ -182,11 +185,11 @@ public void apply(Project project) { } } + JavaPluginExtension javaPluginExtension = + project.getExtensions().getByType(JavaPluginExtension.class); SourceSet mainSourceSet = - projectAfterEvaluation - .getExtensions() - .getByType(SourceSetContainer.class) - .getByName(SourceSet.MAIN_SOURCE_SET_NAME); + javaPluginExtension.getSourceSets().getByName(MAIN_SOURCE_SET_NAME); + jibDependencies.add(mainSourceSet.getRuntimeClasspath()); jibDependencies.add( projectAfterEvaluation diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/OutputPathsParameters.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/OutputPathsParameters.java index 46b4b6e608b..abab4ba801f 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/OutputPathsParameters.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/OutputPathsParameters.java @@ -27,8 +27,7 @@ /** Object that configures where Jib should create its build output files. */ public class OutputPathsParameters { - private final Project project; - + private final Path projectDir; private Path digest; private Path tar; private Path imageId; @@ -36,7 +35,7 @@ public class OutputPathsParameters { @Inject public OutputPathsParameters(Project project) { - this.project = project; + this.projectDir = project.getProjectDir().toPath(); digest = project.getBuildDir().toPath().resolve("jib-image.digest"); imageId = project.getBuildDir().toPath().resolve("jib-image.id"); imageJson = project.getBuildDir().toPath().resolve("jib-image.json"); @@ -102,6 +101,6 @@ public void setTar(String tar) { private Path getRelativeToProjectRoot(Path configuration, String propertyName) { String property = System.getProperty(propertyName); Path path = property != null ? Paths.get(property) : configuration; - return path.isAbsolute() ? path : project.getProjectDir().toPath().resolve(path); + return path.isAbsolute() ? path : this.projectDir.resolve(path); } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2.java index fc15b021cf1..05e4f34aa41 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2.java @@ -139,10 +139,7 @@ private void addGradleFiles(Project project) { skaffoldFilesOutput.addBuild(project.getBuildFile().toPath()); // Add settings.gradle - if (project.getGradle().getStartParameter().getSettingsFile() != null) { - skaffoldFilesOutput.addBuild( - project.getGradle().getStartParameter().getSettingsFile().toPath()); - } else if (Files.exists(projectPath.resolve(Settings.DEFAULT_SETTINGS_FILE))) { + if (Files.exists(projectPath.resolve(Settings.DEFAULT_SETTINGS_FILE))) { skaffoldFilesOutput.addBuild(projectPath.resolve(Settings.DEFAULT_SETTINGS_FILE)); } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldSyncParameters.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldSyncParameters.java index ceeca5d1721..2383230a6e5 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldSyncParameters.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldSyncParameters.java @@ -17,23 +17,21 @@ package com.google.cloud.tools.jib.gradle.skaffold; import java.io.File; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Set; -import java.util.stream.Collectors; import javax.inject.Inject; import org.gradle.api.Project; -import org.gradle.api.tasks.Internal; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.tasks.InputFiles; /** Skaffold specific JibExtension parameters for configuring files to sync. */ public class SkaffoldSyncParameters { - private final Project project; - private Set excludes = Collections.emptySet(); + private final ConfigurableFileCollection fileCollection; + private ConfigurableFileCollection excludes; @Inject public SkaffoldSyncParameters(Project project) { - this.project = project; + this.fileCollection = project.getObjects().fileCollection(); + this.excludes = project.getObjects().fileCollection(); } /** @@ -41,8 +39,8 @@ public SkaffoldSyncParameters(Project project) { * * @return a set of absolute paths */ - @Internal - public Set getExcludes() { + @InputFiles + public ConfigurableFileCollection getExcludes() { return excludes; } @@ -53,10 +51,11 @@ public Set getExcludes() { * @param paths paths to set on excludes */ public void setExcludes(Object paths) { - this.excludes = - project.files(paths).getFiles().stream() - .map(File::toPath) - .map(Path::toAbsolutePath) - .collect(Collectors.toSet()); + this.excludes.from(paths); + } + + @InputFiles + public ConfigurableFileCollection getFileCollection() { + return fileCollection; } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldWatchParameters.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldWatchParameters.java index 5f294100b53..e14081a9682 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldWatchParameters.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SkaffoldWatchParameters.java @@ -17,26 +17,25 @@ package com.google.cloud.tools.jib.gradle.skaffold; import java.io.File; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Set; -import java.util.stream.Collectors; import javax.inject.Inject; import org.gradle.api.Project; -import org.gradle.api.tasks.Internal; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.tasks.InputFiles; /** Skaffold specific JibExtension parameters for configuring files to watch. */ public class SkaffoldWatchParameters { - private final Project project; - - private Set buildIncludes = Collections.emptySet(); - private Set includes = Collections.emptySet(); - private Set excludes = Collections.emptySet(); + private final ConfigurableFileCollection fileCollection; + private ConfigurableFileCollection buildIncludes; + private ConfigurableFileCollection includes; + private ConfigurableFileCollection excludes; @Inject public SkaffoldWatchParameters(Project project) { - this.project = project; + this.fileCollection = project.getObjects().fileCollection(); + this.buildIncludes = project.getObjects().fileCollection(); + this.includes = project.getObjects().fileCollection(); + this.excludes = project.getObjects().fileCollection(); } /** @@ -44,8 +43,8 @@ public SkaffoldWatchParameters(Project project) { * * @return a set of absolute paths */ - @Internal - public Set getBuildIncludes() { + @InputFiles + public ConfigurableFileCollection getBuildIncludes() { return buildIncludes; } @@ -56,11 +55,7 @@ public Set getBuildIncludes() { * @param paths paths to set on includes */ public void setBuildIncludes(Object paths) { - this.buildIncludes = - project.files(paths).getFiles().stream() - .map(File::toPath) - .map(Path::toAbsolutePath) - .collect(Collectors.toSet()); + this.buildIncludes.from(paths); } /** @@ -68,8 +63,8 @@ public void setBuildIncludes(Object paths) { * * @return a set of absolute paths */ - @Internal - public Set getIncludes() { + @InputFiles + public ConfigurableFileCollection getIncludes() { return includes; } @@ -80,11 +75,7 @@ public Set getIncludes() { * @param paths paths to set on includes */ public void setIncludes(Object paths) { - this.includes = - project.files(paths).getFiles().stream() - .map(File::toPath) - .map(Path::toAbsolutePath) - .collect(Collectors.toSet()); + this.includes.from(paths); } /** @@ -92,11 +83,9 @@ public void setIncludes(Object paths) { * * @return a set of absolute paths */ - @Internal - public Set getExcludes() { - // Gradle warns about @Input annotations on File objects, so we have to expose a getter for a - // String to make them go away. - return excludes; + @InputFiles + public ConfigurableFileCollection getExcludes() { + return this.excludes; } /** @@ -106,10 +95,11 @@ public Set getExcludes() { * @param paths paths to set on excludes */ public void setExcludes(Object paths) { - this.excludes = - project.files(paths).getFiles().stream() - .map(File::toPath) - .map(Path::toAbsolutePath) - .collect(Collectors.toSet()); + this.excludes.from(paths); + } + + @InputFiles + public ConfigurableFileCollection getFileCollection() { + return fileCollection; } } diff --git a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTask.java b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTask.java index 7d8d9e4b029..c43f36179d6 100644 --- a/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTask.java +++ b/jib-gradle-plugin/src/main/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTask.java @@ -24,6 +24,8 @@ import com.google.cloud.tools.jib.plugins.common.InvalidContainerizingModeException; import com.google.cloud.tools.jib.plugins.common.PluginConfigurationProcessor; import com.google.common.base.Preconditions; +import java.io.File; +import java.util.stream.Collectors; import javax.annotation.Nullable; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; @@ -85,7 +87,9 @@ public void listFilesAndTargets() { PluginConfigurationProcessor.getSkaffoldSyncMap( configuration, projectProperties, - jibExtension.getSkaffold().getSync().getExcludes()); + jibExtension.getSkaffold().getSync().getExcludes().getFiles().stream() + .map(File::toPath) + .collect(Collectors.toSet())); System.out.println(); System.out.println("BEGIN JIB JSON: SYNCMAP/1"); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildDockerTaskTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildDockerTaskTest.java new file mode 100644 index 00000000000..228e43ea267 --- /dev/null +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildDockerTaskTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.cloud.tools.jib.gradle; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +import com.google.cloud.tools.jib.docker.CliDockerClient; +import com.google.cloud.tools.jib.plugins.common.JibBuildRunner; +import com.google.cloud.tools.jib.plugins.common.PluginConfigurationProcessor; +import org.gradle.api.Project; +import org.gradle.api.provider.Property; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +/** Tests for {@link TaskCommon}. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildDockerTaskTest { + + @Mock JibExtension mockJibExtension; + + @Mock GradleProjectProperties mockProjectProperties; + @Mock private TargetImageParameters mockTargetImage; + @Mock private JibBuildRunner mockJibBuildRunner; + @Mock private DockerClientParameters mockDockerClientParams; + + @Test + void testBuildDockerTask() { + Project project = ProjectBuilder.builder().build(); + BuildDockerTask task = project.getTasks().register("test", BuildDockerTask.class).get(); + assertNull(task.getJib()); + assertNull(task.getProjectProperties()); + + Property property = project.getObjects().property(String.class); + property.set("test"); + + try (MockedStatic gpp = + Mockito.mockStatic(GradleProjectProperties.class)) { + gpp.when(() -> GradleProjectProperties.getForProject(any(), any(), any(), anyString())) + .thenReturn(mockProjectProperties); + when(mockJibExtension.getConfigurationName()).thenReturn(property); + when(mockTargetImage.getImage()).thenReturn("test"); + when(mockJibExtension.getDockerClient()).thenReturn(mockDockerClientParams); + when(mockDockerClientParams.getExecutablePath()).thenReturn(null); + + try (MockedStatic cdc = Mockito.mockStatic(CliDockerClient.class)) { + cdc.when(() -> CliDockerClient.isDefaultDockerInstalled()).thenReturn(true); + + task.setJibExtension(mockJibExtension); + assertNotNull(task.getJib()); + assertNotNull(task.getProjectProperties()); + + try (MockedStatic pcp = + Mockito.mockStatic(PluginConfigurationProcessor.class)) { + pcp.when( + () -> + PluginConfigurationProcessor.createJibBuildRunnerForDockerDaemonImage( + any(), any(), any(), any(), any())) + .thenReturn(mockJibBuildRunner); + + try { + task.buildDocker(); + pcp.verify( + () -> + PluginConfigurationProcessor.createJibBuildRunnerForDockerDaemonImage( + any(), any(), any(), any(), any()), + times(1)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } + } +} diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildImageTaskTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildImageTaskTest.java new file mode 100644 index 00000000000..af5f32e192f --- /dev/null +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildImageTaskTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.cloud.tools.jib.gradle; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +import com.google.cloud.tools.jib.plugins.common.JibBuildRunner; +import com.google.cloud.tools.jib.plugins.common.PluginConfigurationProcessor; +import org.gradle.api.Project; +import org.gradle.api.provider.Property; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +/** Tests for {@link TaskCommon}. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildImageTaskTest { + + @Mock JibExtension mockJibExtension; + + @Mock GradleProjectProperties mockProjectProperties; + @Mock private TargetImageParameters mockTargetImage; + @Mock private JibBuildRunner mockJibBuildRunner; + + @Test + void testCoverageGetter() { + Project project = ProjectBuilder.builder().build(); + BuildImageTask task = project.getTasks().register("test", BuildImageTask.class).get(); + assertNull(task.getJib()); + assertNull(task.getProjectProperties()); + + Property property = project.getObjects().property(String.class); + property.set("test"); + + try (MockedStatic gpp = + Mockito.mockStatic(GradleProjectProperties.class)) { + gpp.when(() -> GradleProjectProperties.getForProject(any(), any(), any(), anyString())) + .thenReturn(mockProjectProperties); + when(mockJibExtension.getConfigurationName()).thenReturn(property); + when(mockTargetImage.getImage()).thenReturn("test"); + when(mockJibExtension.getTo()).thenReturn(mockTargetImage); + task.setJibExtension(mockJibExtension); + assertNotNull(task.getJib()); + assertNotNull(task.getProjectProperties()); + + try (MockedStatic pcp = + Mockito.mockStatic(PluginConfigurationProcessor.class)) { + pcp.when( + () -> + PluginConfigurationProcessor.createJibBuildRunnerForRegistryImage( + any(), any(), any(), any(), any())) + .thenReturn(mockJibBuildRunner); + + try { + task.buildImage(); + pcp.verify( + () -> + PluginConfigurationProcessor.createJibBuildRunnerForRegistryImage( + any(), any(), any(), any(), any()), + times(1)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } +} diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildTarTaskTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildTarTaskTest.java new file mode 100644 index 00000000000..93bd140807b --- /dev/null +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/BuildTarTaskTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2019 Google LLC. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.cloud.tools.jib.gradle; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +import com.google.cloud.tools.jib.plugins.common.JibBuildRunner; +import com.google.cloud.tools.jib.plugins.common.PluginConfigurationProcessor; +import org.gradle.api.Project; +import org.gradle.api.provider.Property; +import org.gradle.testfixtures.ProjectBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +/** Tests for {@link TaskCommon}. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BuildTarTaskTest { + + @Mock JibExtension mockJibExtension; + + @Mock GradleProjectProperties mockProjectProperties; + @Mock private TargetImageParameters mockTargetImage; + @Mock private JibBuildRunner mockJibBuildRunner; + + @Test + void testBuildTarTask() { + Project project = ProjectBuilder.builder().build(); + BuildTarTask task = project.getTasks().register("test", BuildTarTask.class).get(); + assertNull(task.getJib()); + assertNull(task.getProjectProperties()); + + Property property = project.getObjects().property(String.class); + property.set("test"); + + try (MockedStatic gpp = + Mockito.mockStatic(GradleProjectProperties.class)) { + gpp.when(() -> GradleProjectProperties.getForProject(any(), any(), any(), anyString())) + .thenReturn(mockProjectProperties); + when(mockJibExtension.getConfigurationName()).thenReturn(property); + when(mockTargetImage.getImage()).thenReturn("test"); + when(mockJibExtension.getTo()).thenReturn(mockTargetImage); + task.setJibExtension(mockJibExtension); + assertNotNull(task.getJib()); + assertNotNull(task.getProjectProperties()); + + try (MockedStatic pcp = + Mockito.mockStatic(PluginConfigurationProcessor.class)) { + pcp.when( + () -> + PluginConfigurationProcessor.createJibBuildRunnerForTarImage( + any(), any(), any(), any(), any())) + .thenReturn(mockJibBuildRunner); + + try { + task.buildTar(); + pcp.verify( + () -> + PluginConfigurationProcessor.createJibBuildRunnerForTarImage( + any(), any(), any(), any(), any()), + times(1)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } +} diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesExtensionTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesExtensionTest.java index 63718ce0e55..33cbb1058b5 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesExtensionTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesExtensionTest.java @@ -16,6 +16,8 @@ package com.google.cloud.tools.jib.gradle; +import static org.gradle.api.tasks.SourceSet.MAIN_SOURCE_SET_NAME; + import com.google.cloud.tools.jib.api.InvalidImageReferenceException; import com.google.cloud.tools.jib.api.Jib; import com.google.cloud.tools.jib.api.JibContainerBuilder; @@ -35,25 +37,38 @@ import java.util.Map; import java.util.Optional; import org.gradle.api.Action; +import org.gradle.api.JavaVersion; import org.gradle.api.Project; +import org.gradle.api.file.RegularFile; +import org.gradle.api.internal.provider.DefaultProperty; import org.gradle.api.logging.Logger; import org.gradle.api.logging.configuration.ConsoleOutput; import org.gradle.api.model.ObjectFactory; +import org.gradle.api.plugins.ExtensionContainer; import org.gradle.api.plugins.JavaPlugin; +import org.gradle.api.plugins.JavaPluginExtension; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.SourceSet; +import org.gradle.api.tasks.SourceSetContainer; +import org.gradle.api.tasks.TaskContainer; +import org.gradle.jvm.tasks.Jar; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.Answers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Plugin extension test for {@link GradleProjectProperties}. */ -@RunWith(MockitoJUnitRunner.class) -public class GradleProjectPropertiesExtensionTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class GradleProjectPropertiesExtensionTest { // Interface to conveniently provide the main extension body using lambda. @FunctionalInterface @@ -205,6 +220,21 @@ private ExtensionDefinedBarConfig(String barParam) { @Mock private Logger mockLogger; @Mock private ObjectFactory mockObjectFactory; + @Mock private JavaPluginExtension mockJavaPluginExtension; + @Mock private SourceSetContainer mockSourceSetContainer; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private SourceSet mockSourceSet; + + @Mock private TaskContainer mockReturnContainer; + + @Mock private ExtensionContainer mockExtensionContainer; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Jar mockJarTask; + + @Mock private Provider mockProviderFile; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Project mockProject; @@ -213,13 +243,30 @@ private ExtensionDefinedBarConfig(String barParam) { private GradleProjectProperties gradleProjectProperties; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(mockLogger.isDebugEnabled()).thenReturn(true); Mockito.when(mockLogger.isInfoEnabled()).thenReturn(true); Mockito.when(mockLogger.isWarnEnabled()).thenReturn(true); Mockito.when(mockLogger.isErrorEnabled()).thenReturn(true); - + Mockito.when(mockProject.getExtensions()).thenReturn(mockExtensionContainer); + Mockito.when(mockProject.getTasks()).thenReturn(mockReturnContainer); + Mockito.when(mockReturnContainer.findByName("jar")).thenReturn(mockJarTask); + Mockito.when(mockJarTask.getArchiveFile()).thenReturn(mockProviderFile); + Mockito.when(mockProviderFile.isPresent()).thenReturn(true); + + Mockito.when(mockExtensionContainer.getByType(JavaPluginExtension.class)) + .thenReturn(mockJavaPluginExtension); + Mockito.when(mockJavaPluginExtension.getSourceSets()).thenReturn(mockSourceSetContainer); + Mockito.when(mockJavaPluginExtension.getTargetCompatibility()) + .thenReturn(JavaVersion.VERSION_1_8); + Mockito.when(mockSourceSetContainer.getByName(MAIN_SOURCE_SET_NAME)).thenReturn(mockSourceSet); + + Mockito.when(mockObjectFactory.property(String.class)) + .thenReturn(new DefaultProperty<>(null, String.class)); + // Mockito.when(mockObjectFactory.fileProperty()).thenReturn(new DefaultRegularFileVar()); + Mockito.when(mockObjectFactory.property(Boolean.class)) + .thenReturn(new DefaultProperty<>(null, Boolean.class)); Mockito.when(mockProject.getGradle().getStartParameter().getConsoleOutput()) .thenReturn(ConsoleOutput.Plain); Mockito.when(mockProject.getObjects()).thenReturn(mockObjectFactory); @@ -242,13 +289,14 @@ public void setUp() { } @Test - public void testRunPluginExtensions_noExtensionsConfigured() throws JibPluginExtensionException { + void testRunPluginExtensions_noExtensionsConfigured() throws JibPluginExtensionException { FooExtension extension = new FooExtension((buildPlan, properties, extraConfig, gradleData, logger) -> buildPlan); loadedExtensions = Arrays.asList(extension); JibContainerBuilder extendedBuilder = - gradleProjectProperties.runPluginExtensions(Collections.emptyList(), containerBuilder); + gradleProjectProperties.runPluginExtensions( + Collections.emptyList(), containerBuilder, Optional.of(mockProject)); Assert.assertSame(extendedBuilder, containerBuilder); gradleProjectProperties.waitForLoggingThread(); @@ -256,10 +304,10 @@ public void testRunPluginExtensions_noExtensionsConfigured() throws JibPluginExt } @Test - public void testRunPluginExtensions_configuredExtensionNotFound() { + void testRunPluginExtensions_configuredExtensionNotFound() { try { gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig()), containerBuilder, Optional.of(mockProject)); Assert.fail(); } catch (JibPluginExtensionException ex) { Assert.assertEquals( @@ -270,7 +318,7 @@ public void testRunPluginExtensions_configuredExtensionNotFound() { } @Test - public void testRunPluginExtensions() throws JibPluginExtensionException { + void testRunPluginExtensions() throws JibPluginExtensionException { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, gradleData, logger) -> { @@ -281,7 +329,7 @@ public void testRunPluginExtensions() throws JibPluginExtensionException { JibContainerBuilder extendedBuilder = gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig()), containerBuilder, Optional.of(mockProject)); Assert.assertEquals("user from extension", extendedBuilder.toContainerBuildPlan().getUser()); gradleProjectProperties.waitForLoggingThread(); @@ -293,7 +341,7 @@ public void testRunPluginExtensions() throws JibPluginExtensionException { } @Test - public void testRunPluginExtensions_exceptionFromExtension() { + void testRunPluginExtensions_exceptionFromExtension() { FileNotFoundException fakeException = new FileNotFoundException(); FooExtension extension = new FooExtension( @@ -305,7 +353,7 @@ public void testRunPluginExtensions_exceptionFromExtension() { try { gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig()), containerBuilder, Optional.of(mockProject)); Assert.fail(); } catch (JibPluginExtensionException ex) { Assert.assertEquals("exception from extension", ex.getMessage()); @@ -314,7 +362,7 @@ public void testRunPluginExtensions_exceptionFromExtension() { } @Test - public void testRunPluginExtensions_invalidBaseImageFromExtension() { + void testRunPluginExtensions_invalidBaseImageFromExtension() { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, gradleData, logger) -> @@ -323,7 +371,7 @@ public void testRunPluginExtensions_invalidBaseImageFromExtension() { try { gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig()), containerBuilder, Optional.of(mockProject)); Assert.fail(); } catch (JibPluginExtensionException ex) { Assert.assertEquals("invalid base image reference: in*val+id", ex.getMessage()); @@ -333,7 +381,7 @@ public void testRunPluginExtensions_invalidBaseImageFromExtension() { } @Test - public void testRunPluginExtensions_extensionOrder() throws JibPluginExtensionException { + void testRunPluginExtensions_extensionOrder() throws JibPluginExtensionException { FooExtension fooExtension = new FooExtension( (buildPlan, properties, extraConfig, gradleData, logger) -> @@ -346,17 +394,21 @@ public void testRunPluginExtensions_extensionOrder() throws JibPluginExtensionEx JibContainerBuilder extendedBuilder1 = gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig(), new BarExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig(), new BarExtensionConfig()), + containerBuilder, + Optional.of(mockProject)); Assert.assertEquals("bar", extendedBuilder1.toContainerBuildPlan().getBaseImage()); JibContainerBuilder extendedBuilder2 = gradleProjectProperties.runPluginExtensions( - Arrays.asList(new BarExtensionConfig(), new FooExtensionConfig()), containerBuilder); + Arrays.asList(new BarExtensionConfig(), new FooExtensionConfig()), + containerBuilder, + Optional.of(mockProject)); Assert.assertEquals("foo", extendedBuilder2.toContainerBuildPlan().getBaseImage()); } @Test - public void testRunPluginExtensions_customProperties() throws JibPluginExtensionException { + void testRunPluginExtensions_customProperties() throws JibPluginExtensionException { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, gradleData, logger) -> @@ -366,12 +418,13 @@ public void testRunPluginExtensions_customProperties() throws JibPluginExtension JibContainerBuilder extendedBuilder = gradleProjectProperties.runPluginExtensions( Arrays.asList(new FooExtensionConfig(ImmutableMap.of("user", "65432"))), - containerBuilder); + containerBuilder, + Optional.of(mockProject)); Assert.assertEquals("65432", extendedBuilder.toContainerBuildPlan().getUser()); } @Test - public void testRunPluginExtensions_extensionDefinedConfigurations_emptyConfig() + void testRunPluginExtensions_extensionDefinedConfigurations_emptyConfig() throws JibPluginExtensionException { FooExtension fooExtension = new FooExtension( @@ -388,12 +441,13 @@ public void testRunPluginExtensions_extensionDefinedConfigurations_emptyConfig() loadedExtensions = Arrays.asList(fooExtension, barExtension); gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig(), new BarExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig(), new BarExtensionConfig()), + containerBuilder, + Optional.of(mockProject)); } @Test - public void testRunPluginExtensions_extensionDefinedConfigurations() - throws JibPluginExtensionException { + void testRunPluginExtensions_extensionDefinedConfigurations() throws JibPluginExtensionException { FooExtension fooExtension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> { @@ -412,12 +466,12 @@ public void testRunPluginExtensions_extensionDefinedConfigurations() Arrays.asList( new FooExtensionConfig(new ExtensionDefinedFooConfig("fooParamValue")), new BarExtensionConfig(new ExtensionDefinedBarConfig("barParamValue"))), - containerBuilder); + containerBuilder, + Optional.of(mockProject)); } @Test - public void testRunPluginExtensions_ignoreUnexpectedExtraConfig() - throws JibPluginExtensionException { + void testRunPluginExtensions_ignoreUnexpectedExtraConfig() throws JibPluginExtensionException { BaseExtension extension = new BaseExtension<>( (buildPlan, properties, extraConfig, mavenData, logger) -> buildPlan, null); @@ -427,7 +481,8 @@ public void testRunPluginExtensions_ignoreUnexpectedExtraConfig() new BaseExtensionConfig<>( BaseExtension.class.getName(), Collections.emptyMap(), (ignored) -> {}); try { - gradleProjectProperties.runPluginExtensions(Arrays.asList(extensionConfig), containerBuilder); + gradleProjectProperties.runPluginExtensions( + Arrays.asList(extensionConfig), containerBuilder, Optional.of(mockProject)); Assert.fail(); } catch (IllegalArgumentException ex) { Assert.assertEquals( @@ -438,7 +493,7 @@ public void testRunPluginExtensions_ignoreUnexpectedExtraConfig() } @Test - public void testRunPluginExtensions_runtimeExceptionFromExtension() { + void testRunPluginExtensions_runtimeExceptionFromExtension() { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> { @@ -448,7 +503,7 @@ public void testRunPluginExtensions_runtimeExceptionFromExtension() { try { gradleProjectProperties.runPluginExtensions( - Arrays.asList(new FooExtensionConfig()), containerBuilder); + Arrays.asList(new FooExtensionConfig()), containerBuilder, Optional.of(mockProject)); Assert.fail(); } catch (JibPluginExtensionException ex) { Assert.assertEquals(FooExtension.class, ex.getExtensionClass()); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesTest.java index 7698228ab0e..002719be076 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleProjectPropertiesTest.java @@ -17,6 +17,8 @@ package com.google.cloud.tools.jib.gradle; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -74,17 +76,19 @@ import org.gradle.testfixtures.ProjectBuilder; import org.hamcrest.CoreMatchers; import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Test for {@link GradleProjectProperties}. */ -@RunWith(MockitoJUnitRunner.class) -public class GradleProjectPropertiesTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class GradleProjectPropertiesTest { private static final Correspondence SOURCE_FILE_OF = Correspondence.transforming(FileEntry::getSourceFile, "has sourceFile of"); @@ -121,7 +125,7 @@ private static Path getResource(String path) throws URISyntaxException { return Paths.get(Resources.getResource(path).toURI()); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock private TempDirectoryProvider mockTempDirectoryProvider; @Mock private Supplier>> mockExtensionLoader; @@ -130,23 +134,28 @@ private static Path getResource(String path) throws URISyntaxException { private GradleProjectProperties gradleProjectProperties; private Project project; - @Before - public void setUp() throws URISyntaxException, IOException { + @BeforeEach + void setUp() throws URISyntaxException, IOException { when(mockLogger.isDebugEnabled()).thenReturn(true); when(mockLogger.isInfoEnabled()).thenReturn(true); when(mockLogger.isWarnEnabled()).thenReturn(true); when(mockLogger.isErrorEnabled()).thenReturn(true); + Path tmpDir = Files.createTempDirectory(temporaryFolder, "jib"); + Path projectDir = getResource("gradle/application"); project = ProjectBuilder.builder() .withName("my-app") .withProjectDir(projectDir.toFile()) - .withGradleUserHomeDir(temporaryFolder.newFolder()) + .withGradleUserHomeDir(tmpDir.toFile()) .build(); - project.getPlugins().apply("java"); + project.getRepositories().add(project.getRepositories().mavenCentral()); + + project.getPlugins().apply("java"); DependencyHandler dependencies = project.getDependencies(); + dependencies.add( "implementation", project.files( @@ -161,59 +170,61 @@ public void setUp() throws URISyntaxException, IOException { // We can't commit an empty directory in Git, so create (if not exist). Path emptyDirectory = getResource("gradle/webapp").resolve("WEB-INF/classes/empty_dir"); Files.createDirectories(emptyDirectory); - - gradleProjectProperties = - new GradleProjectProperties( - project, - mockLogger, - mockTempDirectoryProvider, - mockExtensionLoader, - JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); } @Test - public void testGetMainClassFromJar_success() { + void testGetMainClassFromJar_success() { + Jar jar = project.getTasks().withType(Jar.class).getByName("jar"); jar.setManifest( new DefaultManifest(null).attributes(ImmutableMap.of("Main-Class", "some.main.class"))); + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getMainClassFromJarPlugin()).isEqualTo("some.main.class"); } @Test - public void testGetMainClassFromJar_missing() { + void testGetMainClassFromJar_missing() { + setupGradleProjectPropertiesInstance(); + assertThat(gradleProjectProperties.getMainClassFromJarPlugin()).isNull(); } @Test - public void testGetMainClassFromJarAsProperty_success() { + void testGetMainClassFromJarAsProperty_success() { + Property mainClass = project.getObjects().property(String.class).value("some.main.class"); Jar jar = project.getTasks().withType(Jar.class).getByName("jar"); jar.setManifest(new DefaultManifest(null).attributes(ImmutableMap.of("Main-Class", mainClass))); + setupGradleProjectPropertiesInstance(); + assertThat(gradleProjectProperties.getMainClassFromJarPlugin()).isEqualTo("some.main.class"); } @Test - public void testGetMainClassFromJarAsPropertyWithValueNull_missing() { + void testGetMainClassFromJarAsPropertyWithValueNull_missing() { + Property mainClass = project.getObjects().property(String.class).value((String) null); Jar jar = project.getTasks().withType(Jar.class).getByName("jar"); jar.setManifest(new DefaultManifest(null).attributes(ImmutableMap.of("Main-Class", mainClass))); - + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getMainClassFromJarPlugin()).isNull(); } @Test - public void testIsWarProject() { + void testIsWarProject() { project.getPlugins().apply("war"); + setupGradleProjectPropertiesInstance(); + assertThat(gradleProjectProperties.isWarProject()).isTrue(); } @Test - public void testGetInputFiles() throws URISyntaxException { + void testGetInputFiles() throws URISyntaxException { Path applicationDirectory = getResource("gradle/application"); List extraDirectories = Arrays.asList(applicationDirectory.resolve("extra-directory")); @@ -237,7 +248,7 @@ public void testGetInputFiles() throws URISyntaxException { } @Test - public void testConvertPermissionsMap() { + void testConvertPermissionsMap() { Map map = ImmutableMap.of("/test/folder/file1", "123", "/test/file2", "456"); assertThat(TaskCommon.convertPermissionsMap(map)) .containsExactly( @@ -257,36 +268,42 @@ public void testConvertPermissionsMap() { } @Test - public void testGetMajorJavaVersion() { - JavaPluginExtension extension = project.getExtensions().findByType(JavaPluginExtension.class); + void testGetMajorJavaVersion() { + JavaPluginExtension convention = project.getExtensions().findByType(JavaPluginExtension.class); + + convention.setTargetCompatibility(JavaVersion.VERSION_1_3); + setupGradleProjectPropertiesInstance(); - extension.setTargetCompatibility(JavaVersion.VERSION_1_3); assertThat(gradleProjectProperties.getMajorJavaVersion()).isEqualTo(3); - extension.setTargetCompatibility(JavaVersion.VERSION_11); + convention.setTargetCompatibility(JavaVersion.VERSION_11); + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getMajorJavaVersion()).isEqualTo(11); - extension.setTargetCompatibility(JavaVersion.VERSION_1_9); + convention.setTargetCompatibility(JavaVersion.VERSION_1_9); + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getMajorJavaVersion()).isEqualTo(9); } @Test - public void testGetMajorJavaVersion_jvm8() { + void testGetMajorJavaVersion_jvm8() { Assume.assumeThat(JavaVersion.current(), CoreMatchers.is(JavaVersion.VERSION_1_8)); - + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getMajorJavaVersion()).isEqualTo(8); } @Test - public void testGetMajorJavaVersion_jvm11() { + void testGetMajorJavaVersion_jvm11() { Assume.assumeThat(JavaVersion.current(), CoreMatchers.is(JavaVersion.VERSION_11)); - + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getMajorJavaVersion()).isEqualTo(11); } @Test - public void testCreateContainerBuilder_correctSourceFiles() + void testCreateContainerBuilder_correctSourceFiles() throws URISyntaxException, InvalidImageReferenceException, CacheDirectoryCreationException { + setupGradleProjectPropertiesInstance(); + ContainerBuilderLayers layers = new ContainerBuilderLayers(setupBuildContext()); Path applicationDirectory = getResource("gradle/application"); @@ -326,12 +343,15 @@ public void testCreateContainerBuilder_correctSourceFiles() } @Test - public void testCreateContainerBuilder_noClassesFiles() + void testCreateContainerBuilder_noClassesFiles() throws InvalidImageReferenceException, IOException { + Path tmpDir = Files.createTempDirectory(temporaryFolder, "jib"); + Path tmpDir2 = Files.createTempDirectory(temporaryFolder, "jib"); + Project project = ProjectBuilder.builder() - .withProjectDir(temporaryFolder.newFolder()) - .withGradleUserHomeDir(temporaryFolder.newFolder()) + .withProjectDir(tmpDir.toFile()) + .withGradleUserHomeDir(tmpDir2.toFile()) .build(); project.getPlugins().apply("java"); @@ -350,8 +370,9 @@ public void testCreateContainerBuilder_noClassesFiles() } @Test - public void testCreateContainerBuilder_correctExtractionPaths() + void testCreateContainerBuilder_correctExtractionPaths() throws InvalidImageReferenceException, CacheDirectoryCreationException { + setupGradleProjectPropertiesInstance(); ContainerBuilderLayers layers = new ContainerBuilderLayers(setupBuildContext()); assertThat(layers.dependenciesLayer.getEntries()) @@ -378,10 +399,12 @@ public void testCreateContainerBuilder_correctExtractionPaths() } @Test - public void testCreateContainerBuilder_war() + void testCreateContainerBuilder_war() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { + Path unzipTarget = setUpWarProject(getResource("gradle/webapp")); + setupGradleProjectPropertiesInstance(); ContainerBuilderLayers layers = new ContainerBuilderLayers(setupBuildContext()); assertThat(layers.dependenciesLayer.getEntries()) @@ -440,10 +463,16 @@ public void testCreateContainerBuilder_war() } @Test - public void testCreateContainerBuilder_noErrorIfWebInfClassesDoesNotExist() + void testCreateContainerBuilder_noErrorIfWebInfClassesDoesNotExist() throws IOException, InvalidImageReferenceException { - temporaryFolder.newFolder("WEB-INF", "lib"); - setUpWarProject(temporaryFolder.getRoot().toPath()); + + File f = new File(temporaryFolder.toFile(), "WEB-INF"); + f.mkdirs(); + f = new File(temporaryFolder.toFile(), "lib"); + f.mkdirs(); + + setUpWarProject(temporaryFolder); + setupGradleProjectPropertiesInstance(); assertThat( gradleProjectProperties.createJibContainerBuilder( @@ -452,10 +481,16 @@ public void testCreateContainerBuilder_noErrorIfWebInfClassesDoesNotExist() } @Test - public void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() + void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() throws IOException, InvalidImageReferenceException { - temporaryFolder.newFolder("WEB-INF", "classes"); - setUpWarProject(temporaryFolder.getRoot().toPath()); + File f = new File(temporaryFolder.toFile(), "WEB-INF"); + f.mkdirs(); + + f = new File(temporaryFolder.toFile(), "classes"); + f.mkdirs(); + + setUpWarProject(temporaryFolder); + setupGradleProjectPropertiesInstance(); assertThat( gradleProjectProperties.createJibContainerBuilder( @@ -464,44 +499,67 @@ public void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() } @Test - public void testCreateContainerBuilder_noErrorIfWebInfDoesNotExist() + void testCreateContainerBuilder_noErrorIfWebInfDoesNotExist() throws IOException, InvalidImageReferenceException { - setUpWarProject(temporaryFolder.getRoot().toPath()); - + setUpWarProject(temporaryFolder); + setupGradleProjectPropertiesInstance(); assertThat( gradleProjectProperties.createJibContainerBuilder( JavaContainerBuilder.from("ignored"), ContainerizingMode.EXPLODED)) .isNotNull(); } + private void setupGradleProjectPropertiesInstance() { + gradleProjectProperties = + new GradleProjectProperties( + project, + mockLogger, + mockTempDirectoryProvider, + mockExtensionLoader, + JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); + } + @Test - public void testGetWarFilePath() throws IOException { - Path outputDir = temporaryFolder.newFolder("output").toPath(); + void testGetWarFilePath() throws IOException { + File f = new File(temporaryFolder.toFile(), "output"); + f.mkdirs(); + + Path outputDir = f.toPath(); project.getPlugins().apply("war"); + setupGradleProjectPropertiesInstance(); + War war = project.getTasks().withType(War.class).getByName("war"); war.getDestinationDirectory().set(outputDir.toFile()); - assertThat(gradleProjectProperties.getWarFilePath()) + assertThat(gradleProjectProperties.getWarFilePath(project)) .isEqualTo(outputDir.resolve("my-app.war").toString()); } @Test - public void testGetWarFilePath_bootWar() throws IOException { - Path outputDir = temporaryFolder.newFolder("output").toPath(); + void testGetWarFilePath_bootWar() throws IOException { + File f = new File(temporaryFolder.toFile(), "output"); + f.mkdirs(); + + Path outputDir = f.toPath(); project.getPlugins().apply("war"); project.getPlugins().apply("org.springframework.boot"); + War bootWar = project.getTasks().withType(War.class).getByName("bootWar"); bootWar.getDestinationDirectory().set(outputDir.toFile()); + setupGradleProjectPropertiesInstance(); - assertThat(gradleProjectProperties.getWarFilePath()) + assertThat(gradleProjectProperties.getWarFilePath(project)) .isEqualTo(outputDir.resolve("my-app.war").toString()); } @Test - public void testGetWarFilePath_bootWarDisabled() throws IOException { - Path outputDir = temporaryFolder.newFolder("output").toPath(); + void testGetWarFilePath_bootWarDisabled() throws IOException { + File f = new File(temporaryFolder.toFile(), "output"); + f.mkdirs(); + + Path outputDir = f.toPath(); project.getPlugins().apply("war"); War war = project.getTasks().withType(War.class).getByName("war"); @@ -510,12 +568,65 @@ public void testGetWarFilePath_bootWarDisabled() throws IOException { project.getPlugins().apply("org.springframework.boot"); project.getTasks().getByName("bootWar").setEnabled(false); - assertThat(gradleProjectProperties.getWarFilePath()) - .isEqualTo(outputDir.resolve("my-app.war").toString()); + setupGradleProjectPropertiesInstance(); + assertThat(gradleProjectProperties.getWarFilePath(project)) + .isEqualTo(outputDir.resolve("my-app-plain.war").toString()); + } + + @Test + void testGetSingleThreadedExecutor() { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getSingleThreadedExecutor()); + gradleProjectProperties.singleThreadedExecutor = null; // pretend running from cache + assertNotNull(gradleProjectProperties.getSingleThreadedExecutor()); + } + + @Test + void testGetConsoleLogger() { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getConsoleLogger()); + } + + @Test + void testGetClassesOutputDirectory() { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getClassesOutputDirectories()); + assertFalse(gradleProjectProperties.getClassesOutputDirectories().getFiles().isEmpty()); + } + + @Test + void testGetResourcesOutputDirectory() { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getResourcesOutputDirectory()); + } + + @Test + void testGetClassFiles() throws IOException { + setupGradleProjectPropertiesInstance(); + assertFalse(gradleProjectProperties.getClassFiles().isEmpty()); + } + + @Test + void testGetDefaultCacheDir() throws IOException { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getDefaultCacheDirectory()); } @Test - public void testGetDependencies() throws URISyntaxException { + void testGetJarPluginName() throws IOException { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getJarPluginName()); + } + + @Test + void testGetTempProvider() { + setupGradleProjectPropertiesInstance(); + assertNotNull(gradleProjectProperties.getTempDirectoryProvider()); + } + + @Test + void testGetDependencies() throws URISyntaxException { + setupGradleProjectPropertiesInstance(); assertThat(gradleProjectProperties.getDependencies()) .containsExactly( getResource("gradle/application/dependencies/library.jarC.jar"), @@ -542,7 +653,10 @@ private BuildContext setupBuildContext() } private Path setUpWarProject(Path webAppDirectory) throws IOException { - File warOutputDir = temporaryFolder.newFolder("output"); + File f = new File(temporaryFolder.toFile(), "output"); + f.mkdirs(); + + File warOutputDir = f; zipUpDirectory(webAppDirectory, warOutputDir.toPath().resolve("my-app.war")); project.getPlugins().apply("war"); @@ -550,7 +664,10 @@ private Path setUpWarProject(Path webAppDirectory) throws IOException { war.getDestinationDirectory().set(warOutputDir); // Make "GradleProjectProperties" use this folder to explode the WAR into. - Path unzipTarget = temporaryFolder.newFolder("exploded").toPath(); + f = new File(temporaryFolder.toFile(), "exploded"); + f.mkdirs(); + + Path unzipTarget = f.toPath(); when(mockTempDirectoryProvider.newDirectory()).thenReturn(unzipTarget); return unzipTarget; } diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleRawConfigurationTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleRawConfigurationTest.java index 86552415531..08448a6f85c 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleRawConfigurationTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/GradleRawConfigurationTest.java @@ -28,20 +28,24 @@ import org.gradle.api.provider.MapProperty; import org.gradle.api.provider.Property; import org.junit.Assert; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Test for {@link GradleRawConfiguration}. */ -@RunWith(MockitoJUnitRunner.class) -public class GradleRawConfigurationTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class GradleRawConfigurationTest { @Mock private MapProperty labels; @Test - public void testGetters() { + @SuppressWarnings("java:S5961") + void testGetters() { JibExtension jibExtension = Mockito.mock(JibExtension.class); AuthParameters authParameters = Mockito.mock(AuthParameters.class); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibExtensionTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibExtensionTest.java index 440ae177792..b37ca3ee068 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibExtensionTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibExtensionTest.java @@ -32,26 +32,37 @@ import java.util.HashSet; import java.util.List; import java.util.Properties; +import java.util.stream.Collectors; import org.gradle.api.Project; import org.gradle.api.provider.Property; import org.gradle.api.provider.Provider; import org.gradle.api.provider.ProviderFactory; import org.gradle.testfixtures.ProjectBuilder; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.contrib.java.lang.system.RestoreSystemProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; /** Tests for {@link JibExtension}. */ -public class JibExtensionTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(SystemStubsExtension.class) +class JibExtensionTest { - @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); + @SystemStub + @SuppressWarnings("unused") + private SystemProperties restoreSystemProperties = new SystemProperties(); private JibExtension testJibExtension; private Project fakeProject; - @Before - public void setUp() { + @BeforeEach + void setUp() { fakeProject = ProjectBuilder.builder().build(); testJibExtension = fakeProject @@ -60,7 +71,7 @@ public void setUp() { } @Test - public void testFrom() { + void testFrom() { assertThat(testJibExtension.getFrom().getImage()).isNull(); assertThat(testJibExtension.getFrom().getCredHelper().getHelper()).isNull(); @@ -96,7 +107,7 @@ public void testFrom() { } @Test - public void testFromCredHelperClosure() { + void testFromCredHelperClosure() { assertThat(testJibExtension.getFrom().getImage()).isNull(); assertThat(testJibExtension.getFrom().getCredHelper().getHelper()).isNull(); @@ -116,7 +127,7 @@ public void testFromCredHelperClosure() { } @Test - public void testTo() { + void testTo() { assertThat(testJibExtension.getTo().getImage()).isNull(); assertThat(testJibExtension.getTo().getCredHelper().getHelper()).isNull(); @@ -134,7 +145,7 @@ public void testTo() { } @Test - public void testToCredHelperClosure() { + void testToCredHelperClosure() { assertThat(testJibExtension.getTo().getImage()).isNull(); assertThat(testJibExtension.getTo().getCredHelper().getHelper()).isNull(); @@ -153,12 +164,12 @@ public void testToCredHelperClosure() { } @Test - public void testToTags_noTagsPropertySet() { + void testToTags_noTagsPropertySet() { assertThat(testJibExtension.getTo().getTags()).isEmpty(); } @Test - public void testToTags_containsNullTag() { + void testToTags_containsNullTag() { TargetImageParameters testToParameters = generateTargetImageParametersWithTags(null, "tag1"); Exception exception = assertThrows(IllegalArgumentException.class, () -> testToParameters.getTags()); @@ -166,7 +177,7 @@ public void testToTags_containsNullTag() { } @Test - public void testToTags_containsEmptyTag() { + void testToTags_containsEmptyTag() { TargetImageParameters testToParameters = generateTargetImageParametersWithTags("", "tag1"); Exception exception = assertThrows(IllegalArgumentException.class, () -> testToParameters.getTags()); @@ -174,7 +185,8 @@ public void testToTags_containsEmptyTag() { } @Test - public void testContainer() { + @SuppressWarnings("java:S5961") + void testContainer() { assertThat(testJibExtension.getContainer().getJvmFlags()).isEmpty(); assertThat(testJibExtension.getContainer().getEnvironment()).isEmpty(); assertThat(testJibExtension.getContainer().getExtraClasspath()).isEmpty(); @@ -230,7 +242,7 @@ public void testContainer() { } @Test - public void testSetFormat() { + void testSetFormat() { testJibExtension.container( container -> { container.setFormat("OCI"); @@ -240,17 +252,17 @@ public void testSetFormat() { } @Test - public void testContainerizingMode() { + void testContainerizingMode() { assertThat(testJibExtension.getContainerizingMode()).isEqualTo("exploded"); } @Test - public void testConfigurationName() { + void testConfigurationName() { assertThat(testJibExtension.getConfigurationName().get()).isEqualTo("runtimeClasspath"); } @Test - public void testExtraDirectories_default() { + void testExtraDirectories_default() { assertThat(testJibExtension.getExtraDirectories().getPaths()).hasSize(1); assertThat(testJibExtension.getExtraDirectories().getPaths().get(0).getFrom()) .isEqualTo(fakeProject.getProjectDir().toPath().resolve("src/main/jib")); @@ -258,7 +270,7 @@ public void testExtraDirectories_default() { } @Test - public void testExtraDirectories() { + void testExtraDirectories() { testJibExtension.extraDirectories( extraDirectories -> { extraDirectories.setPaths("test/path"); @@ -270,7 +282,7 @@ public void testExtraDirectories() { } @Test - public void testExtraDirectories_lazyEvaluation_setFromInto() { + void testExtraDirectories_lazyEvaluation_setFromInto() { testJibExtension.extraDirectories( extraDirectories -> extraDirectories.paths( @@ -293,7 +305,7 @@ public void testExtraDirectories_lazyEvaluation_setFromInto() { } @Test - public void testExtraDirectories_withTarget() { + void testExtraDirectories_withTarget() { testJibExtension.extraDirectories( extraDirectories -> extraDirectories.paths( @@ -321,7 +333,7 @@ public void testExtraDirectories_withTarget() { } @Test - public void testExtraDirectories_fileForPaths() { + void testExtraDirectories_fileForPaths() { testJibExtension.extraDirectories( extraDirectories -> extraDirectories.setPaths(Paths.get("test/path").toFile())); assertThat(testJibExtension.getExtraDirectories().getPaths()).hasSize(1); @@ -330,7 +342,7 @@ public void testExtraDirectories_fileForPaths() { } @Test - public void testExtraDirectories_stringListForPaths() { + void testExtraDirectories_stringListForPaths() { testJibExtension.extraDirectories( extraDirectories -> extraDirectories.setPaths(Arrays.asList("test/path", "another/path"))); @@ -342,7 +354,7 @@ public void testExtraDirectories_stringListForPaths() { } @Test - public void testExtraDirectories_lazyEvaluation_StringListForPaths() { + void testExtraDirectories_lazyEvaluation_StringListForPaths() { testJibExtension.extraDirectories( extraDirectories -> { ProviderFactory providerFactory = fakeProject.getProviders(); @@ -359,7 +371,7 @@ public void testExtraDirectories_lazyEvaluation_StringListForPaths() { } @Test - public void testExtraDirectories_fileListForPaths() { + void testExtraDirectories_fileListForPaths() { testJibExtension.extraDirectories( extraDirectories -> extraDirectories.setPaths( @@ -374,7 +386,7 @@ public void testExtraDirectories_fileListForPaths() { } @Test - public void testDockerClient() { + void testDockerClient() { testJibExtension.dockerClient( dockerClient -> { dockerClient.setExecutable("test-executable"); @@ -389,7 +401,7 @@ public void testDockerClient() { } @Test - public void testOutputFiles() { + void testOutputFiles() { testJibExtension.outputPaths( outputFiles -> { outputFiles.setDigest("/path/to/digest"); @@ -406,7 +418,7 @@ public void testOutputFiles() { } @Test - public void testSkaffold() { + void testSkaffold() { testJibExtension.skaffold( skaffold -> { skaffold.sync(sync -> sync.setExcludes(fakeProject.files("sync1", "sync2"))); @@ -418,20 +430,33 @@ public void testSkaffold() { }); }); Path root = fakeProject.getRootDir().toPath(); - assertThat(testJibExtension.getSkaffold().getSync().getExcludes()) + assertThat( + testJibExtension.getSkaffold().getSync().getExcludes().getFiles().stream() + .map(File::toPath) + .collect(Collectors.toSet())) .containsExactly( root.resolve("sync1").toAbsolutePath(), root.resolve("sync2").toAbsolutePath()); - assertThat(testJibExtension.getSkaffold().getWatch().getBuildIncludes()) + assertThat( + testJibExtension.getSkaffold().getWatch().getBuildIncludes().getFiles().stream() + .map(File::toPath) + .collect(Collectors.toSet())) .containsExactly( root.resolve("watch1").toAbsolutePath(), root.resolve("watch2").toAbsolutePath()); - assertThat(testJibExtension.getSkaffold().getWatch().getIncludes()) + assertThat( + testJibExtension.getSkaffold().getWatch().getIncludes().getFiles().stream() + .map(File::toPath) + .collect(Collectors.toSet())) .containsExactly(root.resolve("watch3").toAbsolutePath()); - assertThat(testJibExtension.getSkaffold().getWatch().getExcludes()) + assertThat( + testJibExtension.getSkaffold().getWatch().getExcludes().getFiles().stream() + .map(File::toPath) + .collect(Collectors.toSet())) .containsExactly(root.resolve("watch4").toAbsolutePath()); } @Test - public void testProperties() { + @SuppressWarnings("java:S5961") + void testProperties() { System.setProperties(new Properties()); System.setProperty("jib.from.image", "fromImage"); @@ -527,7 +552,7 @@ public void testProperties() { } @Test - public void testLazyPropertiesFinalization() { + void testLazyPropertiesFinalization() { Property filesModificationTime = testJibExtension.getContainer().getFilesModificationTime(); filesModificationTime.set((String) null); @@ -543,13 +568,13 @@ public void testLazyPropertiesFinalization() { } @Test - public void testSystemPropertiesWithInvalidPlatform() { + void testSystemPropertiesWithInvalidPlatform() { System.setProperty("jib.from.platforms", "linux /amd64"); assertThrows(IllegalArgumentException.class, testJibExtension.getFrom()::getPlatforms); } @Test - public void testPropertiesOutputPaths() { + void testPropertiesOutputPaths() { System.setProperties(new Properties()); // Absolute paths System.setProperty("jib.outputPaths.digest", "/digest/path"); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibPluginTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibPluginTest.java index fe2829d0dd5..4ba7c93bf25 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibPluginTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/JibPluginTest.java @@ -38,14 +38,20 @@ import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.gradle.testkit.runner.UnexpectedBuildFailure; -import org.junit.After; import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link JibPlugin}. */ -public class JibPluginTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JibPluginTest { private static final ImmutableList KNOWN_JIB_TASKS = ImmutableList.of( @@ -63,27 +69,29 @@ private static boolean isJava8Runtime() { return System.getProperty("java.version").startsWith("1.8."); } - @Rule public final TemporaryFolder testProjectRoot = new TemporaryFolder(); - @Rule public final TestProject testProject = new TestProject("lazy-evaluation"); + @TempDir public Path testProjectRoot; - @After - public void tearDown() { + @RegisterExtension + public TestProject testProject = new TestProject("lazy-evaluation", testProjectRoot); + + @AfterEach + void tearDown() { System.clearProperty(JibPlugin.REQUIRED_VERSION_PROPERTY_NAME); } @Test - public void testCheckGradleVersion_pass() throws IOException { + void testCheckGradleVersion_pass() throws IOException { Assume.assumeTrue(isJava8Runtime()); // Copy build file to temp dir - Path buildFile = testProjectRoot.getRoot().toPath().resolve("build.gradle"); + Path buildFile = testProjectRoot.resolve("build.gradle"); InputStream buildFileContent = getClass().getClassLoader().getResourceAsStream("gradle/plugin-test/build.gradle"); Files.copy(buildFileContent, buildFile); BuildResult result = GradleRunner.create() - .withProjectDir(testProjectRoot.getRoot()) + .withProjectDir(testProjectRoot.toFile()) .withPluginClasspath() .withGradleVersion(JibPlugin.GRADLE_MIN_VERSION.getVersion()) .build(); @@ -91,18 +99,18 @@ public void testCheckGradleVersion_pass() throws IOException { } @Test - public void testCheckGradleVersion_fail() throws IOException { + void testCheckGradleVersion_fail() throws IOException { Assume.assumeTrue(isJava8Runtime()); // Copy build file to temp dir - Path buildFile = testProjectRoot.getRoot().toPath().resolve("build.gradle"); + Path buildFile = testProjectRoot.resolve("build.gradle"); InputStream buildFileContent = getClass().getClassLoader().getResourceAsStream("gradle/plugin-test/build.gradle"); Files.copy(buildFileContent, buildFile); GradleRunner gradleRunner = GradleRunner.create() - .withProjectDir(testProjectRoot.getRoot()) + .withProjectDir(testProjectRoot.toFile()) .withPluginClasspath() .withGradleVersion("4.3"); @@ -118,7 +126,7 @@ public void testCheckGradleVersion_fail() throws IOException { } @Test - public void testCheckJibVersionNames() { + void testCheckJibVersionNames() { // These identifiers will be baked into Skaffold and should not be changed assertThat(JibPlugin.REQUIRED_VERSION_PROPERTY_NAME).isEqualTo("jib.requiredVersion"); assertThat(JibPlugin.SKAFFOLD_CHECK_REQUIRED_VERSION_TASK_NAME) @@ -126,7 +134,7 @@ public void testCheckJibVersionNames() { } @Test - public void testCheckJibVersionInvoked() { + void testCheckJibVersionInvoked() { Project project = createProject(); System.setProperty(JibPlugin.REQUIRED_VERSION_PROPERTY_NAME, "10000.0"); // not here yet @@ -144,7 +152,7 @@ public void testCheckJibVersionInvoked() { } @Test - public void testWebAppProject() { + void testWebAppProject() { Project project = createProject("java", "war", "com.google.cloud.tools.jib"); TaskContainer tasks = project.getTasks(); @@ -158,7 +166,7 @@ public void testWebAppProject() { } @Test - public void testWebAppProject_bootWar() { + void testWebAppProject_bootWar() { Project project = createProject("java", "war", "org.springframework.boot", "com.google.cloud.tools.jib"); @@ -177,7 +185,7 @@ public void testWebAppProject_bootWar() { } @Test - public void testWebAppProject_bootWarDisabled() { + void testWebAppProject_bootWarDisabled() { Project project = createProject("java", "war", "org.springframework.boot", "com.google.cloud.tools.jib"); TaskContainer tasks = project.getTasks(); @@ -198,17 +206,19 @@ public void testWebAppProject_bootWarDisabled() { } @Test - public void testSpringBootJarProject_nonPackagedMode() { + void testSpringBootJarProject_nonPackagedMode() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); Jar jar = (Jar) project.getTasks().getByPath(":jar"); + jar.setEnabled(false); // Spring boot >2.5.0 no longer sets this as disabled by default assertThat(jar.getEnabled()).isFalse(); - assertThat(jar.getArchiveClassifier().get()).isEmpty(); + assertThat(jar.getArchiveClassifier().get()) + .isEqualTo("plain"); // >2.5.0 generates "plain" instead of empty } @Test - public void testSpringBootJarProject_packagedMode() { + void testSpringBootJarProject_packagedMode() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -216,11 +226,11 @@ public void testSpringBootJarProject_packagedMode() { Jar jar = (Jar) project.getTasks().getByPath(":jar"); assertThat(jar.getEnabled()).isTrue(); - assertThat(jar.getArchiveClassifier().get()).isEqualTo("original"); + assertThat(jar.getArchiveClassifier().get()).isEqualTo("plain"); } @Test - public void testSpringBootJarProject_packagedMode_jarClassifierSet() { + void testSpringBootJarProject_packagedMode_jarClassifierSet() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -234,7 +244,7 @@ public void testSpringBootJarProject_packagedMode_jarClassifierSet() { } @Test - public void testSpringBootJarProject_packagedMode_bootJarClassifierSet() { + void testSpringBootJarProject_packagedMode_bootJarClassifierSet() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -244,16 +254,23 @@ public void testSpringBootJarProject_packagedMode_bootJarClassifierSet() { Jar jar = (Jar) project.getTasks().getByPath(":jar"); assertThat(jar.getEnabled()).isTrue(); - assertThat(jar.getArchiveClassifier().get()).isEmpty(); + assertThat(jar.getArchiveClassifier().get()).isEqualTo("plain"); } @Test - public void testSpringBootJarProject_packagedMode_jarEnabled() { + void testSpringBootJarProject_packagedMode_jarEnabled() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); jibExtension.setContainerizingMode("packaged"); - project.getTasks().named("jar").configure(task -> task.setEnabled(true)); + project + .getTasks() + .named("jar") + .configure( + task -> { + task.setEnabled(true); + ((Jar) task).getArchiveClassifier().set(""); // pre spring boot 2.5.0 behaviour + }); TaskContainer tasks = project.getTasks(); Exception exception = assertThrows(GradleException.class, () -> tasks.getByPath(":jar")); @@ -268,7 +285,7 @@ public void testSpringBootJarProject_packagedMode_jarEnabled() { } @Test - public void testSpringBootJarProject_packagedMode_jarEnabledAndClassifierSet() { + void testSpringBootJarProject_packagedMode_jarEnabledAndClassifierSet() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -283,7 +300,7 @@ public void testSpringBootJarProject_packagedMode_jarEnabledAndClassifierSet() { } @Test - public void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarClassifierSet() { + void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarClassifierSet() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -293,11 +310,11 @@ public void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarClassifier Jar jar = (Jar) project.getTasks().getByPath(":jar"); assertThat(jar.getEnabled()).isTrue(); - assertThat(jar.getArchiveClassifier().get()).isEmpty(); + assertThat(jar.getArchiveClassifier().get()).isEqualTo("plain"); } @Test - public void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarDisabled() { + void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarDisabled() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -308,12 +325,11 @@ public void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarDisabled() Jar jar = (Jar) project.getTasks().getByPath(":jar"); assertThat(jar.getEnabled()).isTrue(); assertThat(project.getTasks().getByPath(":bootJar").getEnabled()).isFalse(); - assertThat(jar.getArchiveClassifier().get()).isEmpty(); + assertThat(jar.getArchiveClassifier().get()).isEqualTo("plain"); } @Test - public void - testSpringBootJarProject_packagedMode_jarEnabledAndBootJarDisabledAndJarClassifierSet() { + void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarDisabledAndJarClassifierSet() { Project project = createProject("java", "org.springframework.boot", "com.google.cloud.tools.jib"); JibExtension jibExtension = (JibExtension) project.getExtensions().getByName("jib"); @@ -330,7 +346,7 @@ public void testSpringBootJarProject_packagedMode_jarEnabledAndBootJarDisabled() } @Test - public void testNonWebAppProject() { + void testNonWebAppProject() { Project project = createProject("java", "com.google.cloud.tools.jib"); TaskContainer tasks = project.getTasks(); @@ -339,7 +355,7 @@ public void testNonWebAppProject() { } @Test - public void testJibTaskGroupIsSet() { + void testJibTaskGroupIsSet() { Project project = createProject("java", "com.google.cloud.tools.jib"); TaskContainer tasks = project.getTasks(); @@ -348,7 +364,7 @@ public void testJibTaskGroupIsSet() { } @Test - public void testLazyEvalForImageAndTags() { + void testLazyEvalForImageAndTags() { UnexpectedBuildFailure exception = assertThrows( UnexpectedBuildFailure.class, @@ -361,7 +377,7 @@ public void testLazyEvalForImageAndTags() { } @Test - public void testLazyEvalForLabels() { + void testLazyEvalForLabels() { BuildResult showLabels = testProject.build("showlabels", "-Djib.console=plain"); assertThat(showLabels.getOutput()) .contains( @@ -369,13 +385,13 @@ public void testLazyEvalForLabels() { } @Test - public void testLazyEvalForEntryPoint() { + void testLazyEvalForEntryPoint() { BuildResult showEntrypoint = testProject.build("showentrypoint", "-Djib.console=plain"); assertThat(showEntrypoint.getOutput()).contains("entrypoint contains updated"); } @Test - public void testLazyEvalForExtraDirectories() { + void testLazyEvalForExtraDirectories() { BuildResult checkExtraDirectories = testProject.build("check-extra-directories", "-Djib.console=plain"); assertThat(checkExtraDirectories.getOutput()).contains("[/updated:755]"); @@ -383,7 +399,7 @@ public void testLazyEvalForExtraDirectories() { } @Test - public void testLazyEvalForExtraDirectories_individualPaths() throws IOException { + void testLazyEvalForExtraDirectories_individualPaths() throws IOException { BuildResult checkExtraDirectories = testProject.build( "check-extra-directories", "-b=build-extra-dirs.gradle", "-Djib.console=plain"); @@ -406,7 +422,7 @@ public void testLazyEvalForExtraDirectories_individualPaths() throws IOException } @Test - public void testLazyEvalForContainerCreationAndFileModificationTimes() { + void testLazyEvalForContainerCreationAndFileModificationTimes() { BuildResult showTimes = testProject.build("showtimes", "-Djib.console=plain"); String output = showTimes.getOutput(); assertThat(output).contains("creationTime=2022-07-19T10:23:42Z"); @@ -414,20 +430,20 @@ public void testLazyEvalForContainerCreationAndFileModificationTimes() { } @Test - public void testLazyEvalForMainClass() { + void testLazyEvalForMainClass() { BuildResult showLabels = testProject.build("showMainClass"); assertThat(showLabels.getOutput()).contains("mainClass value updated"); } @Test - public void testLazyEvalForJvmFlags() { + void testLazyEvalForJvmFlags() { BuildResult showLabels = testProject.build("showJvmFlags"); assertThat(showLabels.getOutput()).contains("jvmFlags value [updated]"); } private Project createProject(String... plugins) { Project project = - ProjectBuilder.builder().withProjectDir(testProjectRoot.getRoot()).withName("root").build(); + ProjectBuilder.builder().withProjectDir(testProjectRoot.toFile()).withName("root").build(); Arrays.asList(plugins).forEach(project.getPluginManager()::apply); return project; } diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TaskCommonTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TaskCommonTest.java index aa76ba76532..dc030145cfa 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TaskCommonTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TaskCommonTest.java @@ -33,31 +33,34 @@ import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.bundling.War; import org.gradle.testfixtures.ProjectBuilder; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.boot.gradle.plugin.SpringBootPlugin; import org.springframework.boot.gradle.tasks.bundling.BootWar; /** Tests for {@link TaskCommon}. */ -@RunWith(MockitoJUnitRunner.class) -public class TaskCommonTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class TaskCommonTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); @Mock private ProjectProperties mockProjectProperties; - @Before - public void setUp() { + @BeforeEach + void setUp() { System.clearProperty("jib.extraDirectories.paths"); System.clearProperty("jib.extraDirectories.permissions"); } @Test - public void testGetWarTask_normalJavaProject() { + void testGetWarTask_normalJavaProject() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(JavaPlugin.class); @@ -66,7 +69,7 @@ public void testGetWarTask_normalJavaProject() { } @Test - public void testGetWarTask_normalWarProject() { + void testGetWarTask_normalWarProject() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(WarPlugin.class); @@ -76,7 +79,7 @@ public void testGetWarTask_normalWarProject() { } @Test - public void testGetBootWarTask_bootWarProject() { + void testGetBootWarTask_bootWarProject() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(WarPlugin.class); project.getPlugins().apply(SpringBootPlugin.class); @@ -87,7 +90,7 @@ public void testGetBootWarTask_bootWarProject() { } @Test - public void testFinishUpdateChecker_correctMessageLogged() { + void testFinishUpdateChecker_correctMessageLogged() { when(mockProjectProperties.getToolName()).thenReturn("tool-name"); when(mockProjectProperties.getToolVersion()).thenReturn("2.0.0"); Future> updateCheckFuture = Futures.immediateFuture(Optional.of("2.1.0")); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TestProject.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TestProject.java index ca3f6aed787..4ca3e96dc76 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TestProject.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/TestProject.java @@ -18,7 +18,6 @@ import com.google.cloud.tools.jib.filesystem.DirectoryWalker; import com.google.common.io.Resources; -import java.io.Closeable; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; @@ -27,14 +26,17 @@ import java.util.List; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; // TODO: Consolidate with TestProject in jib-maven-plugin. /** Works with the test Gradle projects in the {@code resources/projects} directory. */ -public class TestProject extends TemporaryFolder implements Closeable { +public class TestProject implements BeforeEachCallback { private static final String PROJECTS_PATH_IN_RESOURCES = "gradle/projects/"; + Path temporaryDir; + /** Copies test project {@code projectName} to {@code destination} folder. */ private static void copyProject(String projectName, Path destination) throws IOException, URISyntaxException { @@ -61,27 +63,9 @@ private static void copyProject(String projectName, Path destination) private Path projectRoot; /** Initialize with a specific project directory. */ - public TestProject(String testProjectName) { + public TestProject(String testProjectName, Path temporaryDir) { this.testProjectName = testProjectName; - } - - @Override - public void close() { - after(); - } - - @Override - protected void before() throws Throwable { - super.before(); - - projectRoot = newFolder().toPath(); - copyProject(testProjectName, projectRoot); - - gradleRunner = - GradleRunner.create() - .withGradleVersion(gradleVersion) - .withProjectDir(projectRoot.toFile()) - .withPluginClasspath(); + this.temporaryDir = temporaryDir; } public TestProject withGradleVersion(String version) { @@ -100,4 +84,16 @@ public BuildResult build(List gradleArguments) { public Path getProjectRoot() { return projectRoot; } + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + projectRoot = Files.createTempDirectory("jib"); // temporaryDir; + copyProject(testProjectName, projectRoot); + + gradleRunner = + GradleRunner.create() + .withGradleVersion(gradleVersion) + .withProjectDir(projectRoot.toFile()) + .withPluginClasspath(); + } } diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2Test.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2Test.java index 3df3a861543..3f84f58aede 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2Test.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/FilesTaskV2Test.java @@ -33,22 +33,39 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link FilesTaskV2}. */ -public class FilesTaskV2Test { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class FilesTaskV2Test { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; - @ClassRule - public static final TestProject skaffoldTestProject = new TestProject("skaffold-config"); + @TempDir Path tempDirSkaffoldTestProject; - @ClassRule public static final TestProject multiTestProject = new TestProject("multi-service"); + @TempDir Path tempDirMulti; - @ClassRule - public static final TestProject platformProject = - new TestProject("platform").withGradleVersion("5.2"); + @TempDir Path tempDirPlatform; + + @RegisterExtension public TestProject simpleTestProject = new TestProject("simple", tempDir); + + @RegisterExtension + public TestProject skaffoldTestProject = + new TestProject("skaffold-config", tempDirSkaffoldTestProject); + + @RegisterExtension + public TestProject multiTestProject = new TestProject("multi-service", tempDirMulti); + + @RegisterExtension + public TestProject platformProject = + new TestProject("platform", tempDirPlatform).withGradleVersion("8.2"); /** * Verifies that the files task succeeded and returns the list of paths it prints out. @@ -60,7 +77,8 @@ public class FilesTaskV2Test { private static String verifyTaskSuccess(TestProject project, @Nullable String moduleName) { String taskName = ":" + (moduleName == null ? "" : moduleName + ":") + JibPlugin.SKAFFOLD_FILES_TASK_V2_NAME; - BuildResult buildResult = project.build(taskName, "-q", "-D_TARGET_IMAGE=ignored"); + BuildResult buildResult = + project.build(taskName, "-q", "-D_TARGET_IMAGE=ignored", "--stacktrace"); BuildTask jibTask = buildResult.task(taskName); Assert.assertNotNull(jibTask); Assert.assertEquals(TaskOutcome.SUCCESS, jibTask.getOutcome()); @@ -89,7 +107,7 @@ private static void assertPathListsAreEqual(List expected, List ac } @Test - public void testFilesTask_singleProject() throws IOException { + void testFilesTask_singleProject() throws IOException { Path projectRoot = simpleTestProject.getProjectRoot(); SkaffoldFilesOutput result = new SkaffoldFilesOutput(verifyTaskSuccess(simpleTestProject, null)); @@ -105,7 +123,7 @@ public void testFilesTask_singleProject() throws IOException { } @Test - public void testFilesTask_multiProjectSimpleService() throws IOException { + void testFilesTask_multiProjectSimpleService() throws IOException { Path projectRoot = multiTestProject.getProjectRoot(); Path simpleServiceRoot = projectRoot.resolve("simple-service"); SkaffoldFilesOutput result = @@ -123,7 +141,7 @@ public void testFilesTask_multiProjectSimpleService() throws IOException { } @Test - public void testFilesTask_multiProjectComplexService() throws IOException { + void testFilesTask_multiProjectComplexService() throws IOException { Path projectRoot = multiTestProject.getProjectRoot(); Path complexServiceRoot = projectRoot.resolve("complex-service"); Path libRoot = projectRoot.resolve("lib"); @@ -152,7 +170,7 @@ public void testFilesTask_multiProjectComplexService() throws IOException { } @Test - public void testFilesTask_platformProject() throws IOException { + void testFilesTask_platformProject() throws IOException { Path projectRoot = platformProject.getProjectRoot(); Path platformRoot = projectRoot.resolve("platform"); Path serviceRoot = projectRoot.resolve("service"); @@ -171,7 +189,7 @@ public void testFilesTask_platformProject() throws IOException { } @Test - public void testFilesTast_withConfigModifiers() throws IOException { + void testFilesTast_withConfigModifiers() throws IOException { Path projectRoot = skaffoldTestProject.getProjectRoot(); SkaffoldFilesOutput result = new SkaffoldFilesOutput(verifyTaskSuccess(skaffoldTestProject, null)); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/InitTaskTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/InitTaskTest.java index 9aa3e8fe726..580e37034e2 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/InitTaskTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/InitTaskTest.java @@ -20,6 +20,7 @@ import com.google.cloud.tools.jib.gradle.TestProject; import com.google.cloud.tools.jib.plugins.common.SkaffoldInitOutput; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -30,15 +31,21 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; /** Tests for {@link InitTask}. */ -public class InitTaskTest { +class InitTaskTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; - @ClassRule public static final TestProject multiTestProject = new TestProject("multi-service"); + @TempDir Path tempDirMulti; + + @RegisterExtension public TestProject simpleTestProject = new TestProject("simple", tempDir); + + @RegisterExtension + public final TestProject multiTestProject = new TestProject("multi-service", tempDirMulti); /** * Verifies that the files task succeeded and returns the list of JSON strings printed by the @@ -68,7 +75,7 @@ private static List getJsons(TestProject project) { } @Test - public void testFilesTask_singleProject() throws IOException { + void testFilesTask_singleProject() throws IOException { List outputs = getJsons(simpleTestProject); Assert.assertEquals(1, outputs.size()); @@ -78,7 +85,7 @@ public void testFilesTask_singleProject() throws IOException { } @Test - public void testFilesTask_multiProject() throws IOException { + void testFilesTask_multiProject() throws IOException { List outputs = getJsons(multiTestProject); Assert.assertEquals(2, outputs.size()); diff --git a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTaskTest.java b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTaskTest.java index 837b5dd081a..c576dc78859 100644 --- a/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTaskTest.java +++ b/jib-gradle-plugin/src/test/java/com/google/cloud/tools/jib/gradle/skaffold/SyncMapTaskTest.java @@ -33,16 +33,27 @@ import org.gradle.testkit.runner.TaskOutcome; import org.gradle.testkit.runner.UnexpectedBuildFailure; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; /** Tests for {@link SyncMapTask}. */ -public class SyncMapTaskTest { +class SyncMapTaskTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); - @ClassRule public static final TestProject skaffoldProject = new TestProject("skaffold-config"); - @ClassRule public static final TestProject multiTestProject = new TestProject("multi-service"); - @ClassRule public static final TestProject warProject = new TestProject("war_servlet25"); + @TempDir Path tempDir1; + @TempDir Path tempDir2; + @TempDir Path tempDir3; + @TempDir Path tempDir4; + + @RegisterExtension public TestProject simpleTestProject = new TestProject("simple", tempDir1); + + @RegisterExtension + public TestProject skaffoldProject = new TestProject("skaffold-config", tempDir2); + + @RegisterExtension + public TestProject multiTestProject = new TestProject("multi-service", tempDir3); + + @RegisterExtension public TestProject warProject = new TestProject("war_servlet25", tempDir4); /** * Verifies that the sync map task succeeded and returns the parsed json. @@ -53,7 +64,7 @@ public class SyncMapTaskTest { * @return the list of paths printed by the task * @throws IOException if the json parser fails */ - private static SkaffoldSyncMapTemplate generateTemplate( + private SkaffoldSyncMapTemplate generateTemplate( TestProject project, @Nullable String moduleName, @Nullable List params) throws IOException { String taskName = @@ -85,7 +96,7 @@ private static void assertFilePaths(Path src, AbsoluteUnixPath dest, FileTemplat } @Test - public void testSyncMapTask_singleProject() throws IOException { + void testSyncMapTask_singleProject() throws IOException { Path projectRoot = simpleTestProject.getProjectRoot(); SkaffoldSyncMapTemplate parsed = generateTemplate(simpleTestProject, null, null); @@ -113,7 +124,7 @@ public void testSyncMapTask_singleProject() throws IOException { } @Test - public void testSyncMapTask_multiProjectOutput() throws IOException { + void testSyncMapTask_multiProjectOutput() throws IOException { Path projectRoot = multiTestProject.getProjectRoot(); Path complexServiceRoot = projectRoot.resolve("complex-service"); Path libRoot = projectRoot.resolve("lib"); @@ -152,7 +163,7 @@ public void testSyncMapTask_multiProjectOutput() throws IOException { } @Test - public void testSyncMapTask_withSkaffoldConfig() throws IOException { + void testSyncMapTask_withSkaffoldConfig() throws IOException { Path projectRoot = skaffoldProject.getProjectRoot(); SkaffoldSyncMapTemplate parsed = generateTemplate(skaffoldProject, null, null); @@ -178,7 +189,7 @@ public void testSyncMapTask_withSkaffoldConfig() throws IOException { } @Test - public void testSyncMapTask_failIfWar() throws IOException { + void testSyncMapTask_failIfWar() throws IOException { Path projectRoot = warProject.getProjectRoot(); try { generateTemplate(warProject, null, null); @@ -194,7 +205,7 @@ public void testSyncMapTask_failIfWar() throws IOException { } @Test - public void testSyncMapTask_failIfJarContainerizationMode() throws IOException { + void testSyncMapTask_failIfJarContainerizationMode() throws IOException { Path projectRoot = simpleTestProject.getProjectRoot(); try { generateTemplate( diff --git a/jib-gradle-plugin/src/test/resources/gradle/projects/multi-service/lib/src/test/java/com/lib/LibTest.java b/jib-gradle-plugin/src/test/resources/gradle/projects/multi-service/lib/src/test/java/com/lib/LibTest.java index ab7425f896c..8d9e9bf49cc 100644 --- a/jib-gradle-plugin/src/test/resources/gradle/projects/multi-service/lib/src/test/java/com/lib/LibTest.java +++ b/jib-gradle-plugin/src/test/resources/gradle/projects/multi-service/lib/src/test/java/com/lib/LibTest.java @@ -17,7 +17,7 @@ package com.lib; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Unit test for simple App. */ public class LibTest { diff --git a/jib-maven-plugin-extension-api/build.gradle b/jib-maven-plugin-extension-api/build.gradle index aa4b6ce45f3..9c36739c870 100644 --- a/jib-maven-plugin-extension-api/build.gradle +++ b/jib-maven-plugin-extension-api/build.gradle @@ -44,7 +44,7 @@ publishing { release { tagTemplate = 'v$version-maven-extension' git { - requireBranch = /^maven-extension-release-v\d+.*$/ //regex + requireBranch.set(/^maven-extension-release-v\d+.*$/) //regex } } /* RELEASE */ diff --git a/jib-maven-plugin/build.gradle b/jib-maven-plugin/build.gradle index f8ead158cd3..1505d8f80ff 100644 --- a/jib-maven-plugin/build.gradle +++ b/jib-maven-plugin/build.gradle @@ -27,7 +27,9 @@ dependencies { testImplementation dependencyStrings.SISU_PLEXUS testImplementation dependencyStrings.MAVEN_TESTING_HARNESS - testImplementation dependencyStrings.JUNIT + testImplementation dependencyStrings.SYSTEM_RULES_STUB + testImplementation dependencyStrings.JUNIT_API + testRuntimeOnly dependencyStrings.JUNIT_ENGINE testImplementation dependencyStrings.TRUTH testImplementation dependencyStrings.TRUTH8 testImplementation dependencyStrings.MOCKITO_CORE @@ -37,6 +39,7 @@ dependencies { testImplementation dependencyStrings.MAVEN_VERIFIER testImplementation dependencyStrings.MAVEN_COMPAT testImplementation dependencyStrings.SLF4J_SIMPLE + testImplementation dependencyStrings.JUNIT_PARAM_TESTS integrationTestImplementation dependencyStrings.JBCRYPT @@ -71,7 +74,7 @@ release { 'com.google.cloud.tools:jib-plugins-common', ] git { - requireBranch = /^maven-release-v\d+.*$/ //regex + requireBranch.set(/^maven-release-v\d+.*$/) //regex } } /* RELEASE */ diff --git a/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildDockerMojoIntegrationTest.java b/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildDockerMojoIntegrationTest.java index 7d3be1d8c51..8b6284d5418 100644 --- a/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildDockerMojoIntegrationTest.java +++ b/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildDockerMojoIntegrationTest.java @@ -20,6 +20,7 @@ import com.google.cloud.tools.jib.Command; import java.io.IOException; +import java.nio.file.Path; import java.security.DigestException; import java.util.Arrays; import org.apache.maven.it.VerificationException; @@ -28,18 +29,28 @@ import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.junit.Assume; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Integration tests for {@link BuildDockerMojo}. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class BuildDockerMojoIntegrationTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; - @ClassRule public static final TestProject emptyTestProject = new TestProject("empty"); + @RegisterExtension + public final TestProject simpleTestProject = new TestProject("simple", tempDir); - @ClassRule - public static final TestProject defaultTargetTestProject = new TestProject("default-target"); + @RegisterExtension public final TestProject emptyTestProject = new TestProject("empty", tempDir); + + @RegisterExtension + public final TestProject defaultTargetTestProject = new TestProject("default-target", tempDir); private static void buildToDockerDaemon(TestProject project, String imageReference, String pomXml) throws VerificationException, DigestException, IOException { @@ -72,7 +83,6 @@ private static String buildToDockerDaemonAndRun(TestProject project, String imag .run(); String dockerInspectLabels = new Command("docker", "inspect", "-f", "'{{json .Config.Labels}}'", imageReference).run(); - String history = new Command("docker", "history", imageReference).run(); MatcherAssert.assertThat( dockerInspectVolumes, CoreMatchers.containsString("\"/var/log\":{},\"/var/log2\":{}")); diff --git a/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildImageMojoIntegrationTest.java b/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildImageMojoIntegrationTest.java index 52675002c20..21d7510a3ba 100644 --- a/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildImageMojoIntegrationTest.java +++ b/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildImageMojoIntegrationTest.java @@ -58,34 +58,47 @@ import org.hamcrest.MatcherAssert; import org.junit.After; import org.junit.Assume; -import org.junit.Before; -import org.junit.ClassRule; 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.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; import org.junit.rules.TemporaryFolder; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Integration tests for {@link BuildImageMojo}. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class BuildImageMojoIntegrationTest { - @ClassRule + @RegisterExtension public static final LocalRegistry localRegistry = new LocalRegistry(5000, "testuser", "testpassword"); private static final String dockerHost = System.getenv("DOCKER_IP") != null ? System.getenv("DOCKER_IP") : "localhost"; - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; - @ClassRule public static final TestProject emptyTestProject = new TestProject("empty"); + @RegisterExtension + public final TestProject simpleTestProject = new TestProject("simple", tempDir); - @ClassRule public static final TestProject skippedTestProject = new TestProject("empty"); + @RegisterExtension public final TestProject emptyTestProject = new TestProject("empty", tempDir); - @ClassRule - public static final TestProject defaultTargetTestProject = new TestProject("default-target"); + @RegisterExtension + public final TestProject skippedTestProject = new TestProject("empty", tempDir); - @ClassRule public static final TestProject servlet25Project = new TestProject("war_servlet25"); + @RegisterExtension + public final TestProject defaultTargetTestProject = new TestProject("default-target", tempDir); - @ClassRule public static final TestProject springBootProject = new TestProject("spring-boot"); + @RegisterExtension + public final TestProject servlet25Project = new TestProject("war_servlet25", tempDir); + + @RegisterExtension + public final TestProject springBootProject = new TestProject("spring-boot", tempDir); private static String getTestImageReference(String label) { String nameBase = IntegrationTestingConfiguration.getTestRepositoryLocation() + '/'; @@ -230,7 +243,7 @@ private static String buildAndRunAdditionalTag( return output; } - private static String buildAndRunComplex(String imageReference, String pomFile) + private String buildAndRunComplex(String imageReference, String pomFile) throws VerificationException, IOException, InterruptedException { Verifier verifier = new Verifier(simpleTestProject.getProjectRoot().toString()); verifier.setSystemProperty("jib.useOnlyProjectCache", "true"); @@ -334,7 +347,7 @@ private static int getLayerSize(String imageReference) throws IOException, Inter @Nullable private String detachedContainerName; - @Before + @BeforeEach public void setUp() throws IOException, InterruptedException { // Pull distroless to local registry so we can test 'from' credentials localRegistry.pullAndPushToLocal("gcr.io/distroless/java:latest", "distroless/java"); diff --git a/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildTarMojoIntegrationTest.java b/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildTarMojoIntegrationTest.java index 08503a24d52..9f998ce7b55 100644 --- a/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildTarMojoIntegrationTest.java +++ b/jib-maven-plugin/src/integration-test/java/com/google/cloud/tools/jib/maven/BuildTarMojoIntegrationTest.java @@ -18,6 +18,7 @@ import com.google.cloud.tools.jib.Command; import java.io.IOException; +import java.nio.file.Path; import java.security.DigestException; import java.util.Arrays; import org.apache.maven.it.VerificationException; @@ -25,14 +26,25 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; - +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class BuildTarMojoIntegrationTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; + + @RegisterExtension + public final TestProject simpleTestProject = new TestProject("simple", tempDir); - @ClassRule public static final TestProject skippedTestProject = new TestProject("empty"); + @RegisterExtension + public final TestProject skippedTestProject = new TestProject("empty", tempDir); @Test public void testExecute_simple() diff --git a/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/MavenProjectProperties.java b/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/MavenProjectProperties.java index 7b457951c6a..edaa2e044e2 100644 --- a/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/MavenProjectProperties.java +++ b/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/MavenProjectProperties.java @@ -597,7 +597,8 @@ Optional getSpringBootRepackageConfiguration() { @Override public JibContainerBuilder runPluginExtensions( List extensionConfigs, - JibContainerBuilder jibContainerBuilder) + JibContainerBuilder jibContainerBuilder, + Optional unusedForMaven) throws JibPluginExtensionException { if (extensionConfigs.isEmpty()) { log(LogEvent.debug("No Jib plugin extensions configured to load")); diff --git a/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/skaffold/SkaffoldConfiguration.java b/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/skaffold/SkaffoldConfiguration.java index f02572253f7..67d998422ae 100644 --- a/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/skaffold/SkaffoldConfiguration.java +++ b/jib-maven-plugin/src/main/java/com/google/cloud/tools/jib/maven/skaffold/SkaffoldConfiguration.java @@ -36,10 +36,7 @@ public static class Sync { @Parameter List excludes = Collections.emptyList(); } - /** - * Watch is unused, but left here to define how to parse it. See {@link - * FilesMojoV2#collectWatchParameters} - */ + /** Watch is unused, but left here to define how to parse it. */ @Parameter Watch watch = new Watch(); @Parameter Sync sync = new Sync(); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/JibPluginConfigurationTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/JibPluginConfigurationTest.java index e6d0b7bdef5..2accb011389 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/JibPluginConfigurationTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/JibPluginConfigurationTest.java @@ -32,15 +32,20 @@ import org.apache.maven.model.Build; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; -import org.junit.Before; -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.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link JibPluginConfiguration}. */ -@RunWith(MockitoJUnitRunner.class) -public class JibPluginConfigurationTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JibPluginConfigurationTest { private final MavenProject project = new MavenProject(); private final Properties sessionProperties = new Properties(); @@ -49,8 +54,8 @@ public class JibPluginConfigurationTest { @Mock private Build build; private JibPluginConfiguration testPluginConfiguration; - @Before - public void setup() { + @BeforeEach + void setup() { when(session.getSystemProperties()).thenReturn(sessionProperties); when(build.getDirectory()).thenReturn("/test/directory"); testPluginConfiguration = @@ -70,7 +75,7 @@ public Log getLog() { } @Test - public void testDefaults() { + void testDefaults() { assertThat(testPluginConfiguration.getPlatforms().get(0).getOsName()).hasValue("linux"); assertThat(testPluginConfiguration.getPlatforms().get(0).getArchitectureName()) .hasValue("amd64"); @@ -92,7 +97,8 @@ public void testDefaults() { } @Test - public void testSystemProperties() { + @SuppressWarnings("java:S5961") + void testSystemProperties() { sessionProperties.put("jib.from.image", "fromImage"); assertThat(testPluginConfiguration.getBaseImage()).isEqualTo("fromImage"); sessionProperties.put("jib.from.credHelper", "credHelper"); @@ -176,13 +182,13 @@ public void testSystemProperties() { } @Test - public void testSystemPropertiesWithInvalidPlatform() { + void testSystemPropertiesWithInvalidPlatform() { sessionProperties.put("jib.from.platforms", "linux /amd64"); assertThrows(IllegalArgumentException.class, testPluginConfiguration::getPlatforms); } @Test - public void testSystemPropertiesExtraDirectories() { + void testSystemPropertiesExtraDirectories() { sessionProperties.put("jib.extraDirectories.paths", "custom-jib"); assertThat(testPluginConfiguration.getExtraDirectories()).hasSize(1); assertThat(testPluginConfiguration.getExtraDirectories().get(0).getFrom()) @@ -198,7 +204,7 @@ public void testSystemPropertiesExtraDirectories() { } @Test - public void testSystemPropertiesOutputPaths() { + void testSystemPropertiesOutputPaths() { // Absolute paths sessionProperties.put("jib.outputPaths.digest", "/digest/path"); assertThat(testPluginConfiguration.getDigestOutputPath()).isEqualTo(Paths.get("/digest/path")); @@ -222,7 +228,7 @@ public void testSystemPropertiesOutputPaths() { } @Test - public void testPomProperties() { + void testPomProperties() { project.getProperties().setProperty("jib.from.image", "fromImage"); assertThat(testPluginConfiguration.getBaseImage()).isEqualTo("fromImage"); project.getProperties().setProperty("jib.from.credHelper", "credHelper"); @@ -299,7 +305,7 @@ public void testPomProperties() { } @Test - public void testPomPropertiesExtraDirectories() { + void testPomPropertiesExtraDirectories() { project.getProperties().setProperty("jib.extraDirectories.paths", "custom-jib"); assertThat(testPluginConfiguration.getExtraDirectories()).hasSize(1); assertThat(testPluginConfiguration.getExtraDirectories().get(0).getFrom()) @@ -317,7 +323,7 @@ public void testPomPropertiesExtraDirectories() { } @Test - public void testPomPropertiesOutputPaths() { + void testPomPropertiesOutputPaths() { project.getProperties().setProperty("jib.outputPaths.digest", "/digest/path"); assertThat(testPluginConfiguration.getDigestOutputPath()).isEqualTo(Paths.get("/digest/path")); project.getProperties().setProperty("jib.outputPaths.imageId", "/id/path"); @@ -330,7 +336,7 @@ public void testPomPropertiesOutputPaths() { } @Test - public void testEmptyOrNullTags() { + void testEmptyOrNullTags() { // https://github.com/GoogleContainerTools/jib/issues/1534 // Maven turns empty tags into null entries, and its possible to have empty tags in jib.to.tags sessionProperties.put("jib.to.tags", "a,,b"); @@ -342,7 +348,7 @@ public void testEmptyOrNullTags() { } @Test - public void testIsContainerizable_noProperty() { + void testIsContainerizable_noProperty() { Properties projectProperties = project.getProperties(); projectProperties.remove("jib.containerize"); @@ -352,42 +358,17 @@ public void testIsContainerizable_noProperty() { assertThat(testPluginConfiguration.isContainerizable()).isTrue(); } - @Test - public void testIsContainerizable_artifactId() { - project.setGroupId("group"); - project.setArtifactId("artifact"); - - Properties projectProperties = project.getProperties(); - projectProperties.setProperty("jib.containerize", ":artifact"); - assertThat(testPluginConfiguration.isContainerizable()).isTrue(); - - projectProperties.setProperty("jib.containerize", ":artifact2"); - assertThat(testPluginConfiguration.isContainerizable()).isFalse(); - } - - @Test - public void testIsContainerizable_groupAndArtifactId() { - project.setGroupId("group"); - project.setArtifactId("artifact"); - - Properties projectProperties = project.getProperties(); - projectProperties.setProperty("jib.containerize", "group:artifact"); - assertThat(testPluginConfiguration.isContainerizable()).isTrue(); - - projectProperties.setProperty("jib.containerize", "group:artifact2"); - assertThat(testPluginConfiguration.isContainerizable()).isFalse(); - } - - @Test - public void testIsContainerizable_directory() { + @ParameterizedTest + @CsvSource({":artifact, :artifact2", "group:artifact, group:artifact2", "project, project2"}) + void testIsContainerizable(String artifact1, String artifact2) { project.setGroupId("group"); project.setArtifactId("artifact"); Properties projectProperties = project.getProperties(); - projectProperties.setProperty("jib.containerize", "project"); + projectProperties.setProperty("jib.containerize", artifact1); assertThat(testPluginConfiguration.isContainerizable()).isTrue(); - projectProperties.setProperty("jib.containerize", "project2"); + projectProperties.setProperty("jib.containerize", artifact2); assertThat(testPluginConfiguration.isContainerizable()).isFalse(); } } diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesExtensionTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesExtensionTest.java index 4c958b1f8a0..b8a8fb9d0aa 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesExtensionTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesExtensionTest.java @@ -42,16 +42,19 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Plugin extension test for {@link MavenProjectProperties}. */ -@RunWith(MockitoJUnitRunner.class) -public class MavenProjectPropertiesExtensionTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MavenProjectPropertiesExtensionTest { // Interface to conveniently provide the main extension body using lambda. @FunctionalInterface @@ -195,8 +198,8 @@ private ExtensionDefinedBarConfig(String barParam) { private MavenProjectProperties mavenProjectProperties; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(mockLog.isDebugEnabled()).thenReturn(true); Mockito.when(mockLog.isWarnEnabled()).thenReturn(true); Mockito.when(mockLog.isErrorEnabled()).thenReturn(true); @@ -214,7 +217,7 @@ public void setUp() { } @Test - public void testRunPluginExtensions_noExtensionsConfigured() throws JibPluginExtensionException { + void testRunPluginExtensions_noExtensionsConfigured() throws JibPluginExtensionException { FooExtension extension = new FooExtension((buildPlan, properties, extraConfig, mavenData, logger) -> buildPlan); loadedExtensions = Arrays.asList(extension); @@ -228,7 +231,7 @@ public void testRunPluginExtensions_noExtensionsConfigured() throws JibPluginExt } @Test - public void testRunPluginExtensions_configuredExtensionNotFound() { + void testRunPluginExtensions_configuredExtensionNotFound() { try { mavenProjectProperties.runPluginExtensions( Arrays.asList(new FooExtensionConfig()), containerBuilder); @@ -242,7 +245,7 @@ public void testRunPluginExtensions_configuredExtensionNotFound() { } @Test - public void testRunPluginExtensions() throws JibPluginExtensionException { + void testRunPluginExtensions() throws JibPluginExtensionException { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> { @@ -265,7 +268,7 @@ public void testRunPluginExtensions() throws JibPluginExtensionException { } @Test - public void testRunPluginExtensions_exceptionFromExtension() { + void testRunPluginExtensions_exceptionFromExtension() { FileNotFoundException fakeException = new FileNotFoundException(); FooExtension extension = new FooExtension( @@ -286,7 +289,7 @@ public void testRunPluginExtensions_exceptionFromExtension() { } @Test - public void testRunPluginExtensions_invalidBaseImageFromExtension() { + void testRunPluginExtensions_invalidBaseImageFromExtension() { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> @@ -305,7 +308,7 @@ public void testRunPluginExtensions_invalidBaseImageFromExtension() { } @Test - public void testRunPluginExtensions_extensionOrder() throws JibPluginExtensionException { + void testRunPluginExtensions_extensionOrder() throws JibPluginExtensionException { FooExtension fooExtension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> @@ -328,7 +331,7 @@ public void testRunPluginExtensions_extensionOrder() throws JibPluginExtensionEx } @Test - public void testRunPluginExtensions_customProperties() throws JibPluginExtensionException { + void testRunPluginExtensions_customProperties() throws JibPluginExtensionException { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> @@ -343,7 +346,7 @@ public void testRunPluginExtensions_customProperties() throws JibPluginExtension } @Test - public void testRunPluginExtensions_extensionDefinedConfigurations_emptyConfig() + void testRunPluginExtensions_extensionDefinedConfigurations_emptyConfig() throws JibPluginExtensionException { FooExtension fooExtension = new FooExtension( @@ -364,8 +367,7 @@ public void testRunPluginExtensions_extensionDefinedConfigurations_emptyConfig() } @Test - public void testRunPluginExtensions_extensionDefinedConfigurations() - throws JibPluginExtensionException { + void testRunPluginExtensions_extensionDefinedConfigurations() throws JibPluginExtensionException { FooExtension fooExtension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> { @@ -388,7 +390,7 @@ public void testRunPluginExtensions_extensionDefinedConfigurations() } @Test - public void testRunPluginExtensions_wrongExtraConfigType() { + void testRunPluginExtensions_wrongExtraConfigType() { FooExtension extension = new FooExtension((buildPlan, properties, extraConfig, mavenData, logger) -> buildPlan); loadedExtensions = Arrays.asList(extension); @@ -412,8 +414,7 @@ public void testRunPluginExtensions_wrongExtraConfigType() { } @Test - public void testRunPluginExtensions_ignoreUnexpectedExtraConfig() - throws JibPluginExtensionException { + void testRunPluginExtensions_ignoreUnexpectedExtraConfig() throws JibPluginExtensionException { BaseExtension extension = new BaseExtension<>( (buildPlan, properties, extraConfig, mavenData, logger) -> buildPlan, null); @@ -434,7 +435,7 @@ public void testRunPluginExtensions_ignoreUnexpectedExtraConfig() } @Test - public void testRunPluginExtensions_runtimeExceptionFromExtension() { + void testRunPluginExtensions_runtimeExceptionFromExtension() { FooExtension extension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> { @@ -453,7 +454,7 @@ public void testRunPluginExtensions_runtimeExceptionFromExtension() { } @Test - public void testRunPluginExtensions_injected() throws JibPluginExtensionException { + void testRunPluginExtensions_injected() throws JibPluginExtensionException { FooExtension injectedExtension = new FooExtension( (buildPlan, properties, extraConfig, mavenData, logger) -> { @@ -485,7 +486,7 @@ public void testRunPluginExtensions_injected() throws JibPluginExtensionExceptio } @Test - public void testRunPluginExtensions_preferInjectionOverServiceLoader() + void testRunPluginExtensions_preferInjectionOverServiceLoader() throws JibPluginExtensionException { FooExtension injectedExtension = new FooExtension( diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesTest.java index 5bbceaf3b9c..69906ff9e6f 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenProjectPropertiesTest.java @@ -77,18 +77,21 @@ import org.codehaus.plexus.archiver.zip.ZipEntry; import org.codehaus.plexus.archiver.zip.ZipOutputStream; import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Test for {@link MavenProjectProperties}. */ -@RunWith(MockitoJUnitRunner.class) -public class MavenProjectPropertiesTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MavenProjectPropertiesTest { private static final Correspondence SOURCE_FILE_OF = Correspondence.transforming(FileEntry::getSourceFile, "has sourceFile of"); @@ -173,8 +176,8 @@ private static Xpp3Dom addXpp3DomChild(Xpp3Dom parent, String name, String value return node; } - @Rule public final TestRepository testRepository = new TestRepository(); - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @RegisterExtension public TestRepository testRepository = new TestRepository(); + @TempDir public Path temporaryFolder; private final Xpp3Dom pluginConfiguration = new Xpp3Dom("configuration"); @@ -193,8 +196,8 @@ private static Xpp3Dom addXpp3DomChild(Xpp3Dom parent, String name, String value private MavenProjectProperties mavenProjectProperties; - @Before - public void setUp() throws IOException, URISyntaxException { + @BeforeEach + void setUpBefore() throws IOException, URISyntaxException { when(mockLog.isDebugEnabled()).thenReturn(true); when(mockLog.isWarnEnabled()).thenReturn(true); when(mockLog.isErrorEnabled()).thenReturn(true); @@ -237,7 +240,7 @@ public void setUp() throws IOException, URISyntaxException { } @Test - public void testGetMainClassFromJar_success() { + void testGetMainClassFromJar_success() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getConfiguration()).thenReturn(pluginConfiguration); @@ -251,7 +254,7 @@ public void testGetMainClassFromJar_success() { } @Test - public void testGetMainClassFromJar_missingMainClass() { + void testGetMainClassFromJar_missingMainClass() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getConfiguration()).thenReturn(pluginConfiguration); @@ -263,7 +266,7 @@ public void testGetMainClassFromJar_missingMainClass() { } @Test - public void testGetMainClassFromJar_missingManifest() { + void testGetMainClassFromJar_missingManifest() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getConfiguration()).thenReturn(pluginConfiguration); @@ -273,7 +276,7 @@ public void testGetMainClassFromJar_missingManifest() { } @Test - public void testGetMainClassFromJar_missingArchive() { + void testGetMainClassFromJar_missingArchive() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getConfiguration()).thenReturn(pluginConfiguration); @@ -282,7 +285,7 @@ public void testGetMainClassFromJar_missingArchive() { } @Test - public void testGetMainClassFromJar_missingConfiguration() { + void testGetMainClassFromJar_missingConfiguration() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-jar-plugin")) .thenReturn(mockPlugin); @@ -290,17 +293,17 @@ public void testGetMainClassFromJar_missingConfiguration() { } @Test - public void testGetMainClassFromJar_missingPlugin() { + void testGetMainClassFromJar_missingPlugin() { assertThat(mavenProjectProperties.getMainClassFromJarPlugin()).isNull(); } @Test - public void testIsWarProject() { + void testIsWarProject() { assertThat(mavenProjectProperties.isWarProject()).isFalse(); } @Test - public void testGetVersionFromString() { + void testGetVersionFromString() { assertThat(MavenProjectProperties.getVersionFromString("1.8")).isEqualTo(8); assertThat(MavenProjectProperties.getVersionFromString("1.8.0_123")).isEqualTo(8); assertThat(MavenProjectProperties.getVersionFromString("11")).isEqualTo(11); @@ -313,12 +316,12 @@ public void testGetVersionFromString() { } @Test - public void testGetMajorJavaVersion_undefinedDefaultsTo6() { + void testGetMajorJavaVersion_undefinedDefaultsTo6() { assertThat(mavenProjectProperties.getMajorJavaVersion()).isEqualTo(6); } @Test - public void testGetMajorJavaVersion_targetProperty() { + void testGetMajorJavaVersion_targetProperty() { when(mockMavenProperties.getProperty("maven.compiler.target")).thenReturn("1.8"); assertThat(mavenProjectProperties.getMajorJavaVersion()).isEqualTo(8); @@ -330,7 +333,7 @@ public void testGetMajorJavaVersion_targetProperty() { } @Test - public void testValidateBaseImageVersion_releaseProperty() { + void testValidateBaseImageVersion_releaseProperty() { when(mockMavenProperties.getProperty("maven.compiler.release")).thenReturn("1.8"); assertThat(mavenProjectProperties.getMajorJavaVersion()).isEqualTo(8); @@ -342,7 +345,7 @@ public void testValidateBaseImageVersion_releaseProperty() { } @Test - public void testValidateBaseImageVersion_compilerPluginTarget() { + void testValidateBaseImageVersion_compilerPluginTarget() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-compiler-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getConfiguration()).thenReturn(pluginConfiguration); @@ -360,7 +363,7 @@ public void testValidateBaseImageVersion_compilerPluginTarget() { } @Test - public void testValidateBaseImageVersion_compilerPluginRelease() { + void testValidateBaseImageVersion_compilerPluginRelease() { when(mockMavenProject.getPlugin("org.apache.maven.plugins:maven-compiler-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getConfiguration()).thenReturn(pluginConfiguration); @@ -375,13 +378,13 @@ public void testValidateBaseImageVersion_compilerPluginRelease() { } @Test - public void isProgressFooterEnabled() { + void isProgressFooterEnabled() { when(mockMavenRequest.isInteractiveMode()).thenReturn(false); assertThat(MavenProjectProperties.isProgressFooterEnabled(mockMavenSession)).isFalse(); } @Test - public void testCreateContainerBuilder_correctFiles() + void testCreateContainerBuilder_correctFiles() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { ContainerBuilderLayers layers = new ContainerBuilderLayers(setUpBuildContext()); @@ -430,11 +433,13 @@ public void testCreateContainerBuilder_correctFiles() } @Test - public void testCreateContainerBuilder_packagedMode() + void testCreateContainerBuilder_packagedMode() throws InvalidImageReferenceException, IOException, CacheDirectoryCreationException, URISyntaxException { - Path jar = temporaryFolder.newFile("final-name.jar").toPath(); - when(mockBuild.getDirectory()).thenReturn(temporaryFolder.getRoot().toString()); + File f = new File(temporaryFolder.toFile(), "final-name.jar"); + f.createNewFile(); + Path jar = f.toPath(); + when(mockBuild.getDirectory()).thenReturn(temporaryFolder.toString()); when(mockBuild.getFinalName()).thenReturn("final-name"); ContainerBuilderLayers layers = @@ -481,7 +486,7 @@ public void testCreateContainerBuilder_packagedMode() } @Test - public void testCreateContainerBuilder_war_correctSourceFilePaths() + void testCreateContainerBuilder_war_correctSourceFilePaths() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { Path unzipTarget = setUpWar(getResource("maven/webapp/final-name")); @@ -516,7 +521,7 @@ public void testCreateContainerBuilder_war_correctSourceFilePaths() } @Test - public void testCreateContainerBuilder_war_correctExtractionPaths() + void testCreateContainerBuilder_war_correctExtractionPaths() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { setUpWar(getResource("maven/webapp/final-name")); @@ -551,9 +556,11 @@ public void testCreateContainerBuilder_war_correctExtractionPaths() } @Test - public void testCreateContainerBuilder_noErrorIfWebInfDoesNotExist() + void testCreateContainerBuilder_noErrorIfWebInfDoesNotExist() throws IOException, InvalidImageReferenceException { - setUpWar(temporaryFolder.newFolder("final-name").toPath()); + File f = new File(temporaryFolder.toFile(), "final-name"); + f.mkdirs(); + setUpWar(f.toPath()); assertThat( mavenProjectProperties.createJibContainerBuilder( @@ -562,10 +569,13 @@ public void testCreateContainerBuilder_noErrorIfWebInfDoesNotExist() } @Test - public void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() + void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() throws IOException, InvalidImageReferenceException { - temporaryFolder.newFolder("final-name", "WEB-INF", "classes"); - setUpWar(temporaryFolder.getRoot().toPath()); + new File(temporaryFolder.toFile(), "final-name").mkdirs(); + new File(temporaryFolder.toFile(), "WEB-INF").mkdirs(); + new File(temporaryFolder.toFile(), "classes").mkdirs(); + + setUpWar(temporaryFolder); assertThat( mavenProjectProperties.createJibContainerBuilder( @@ -574,8 +584,11 @@ public void testCreateContainerBuilder_noErrorIfWebInfLibDoesNotExist() } @Test - public void testCreateContainerBuilder_exceptionMessageHasPackageSuggestionIfProjectIsWar() + void testCreateContainerBuilder_exceptionMessageHasPackageSuggestionIfProjectIsWar() throws IOException { + when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); + when(mockBuild.getFinalName()).thenReturn("helloworld-1"); + String expectedMessage = "Obtaining project build output files failed; make sure you have " + "packaged your project before trying to build the image. (Did you accidentally run \"mvn clean " @@ -596,9 +609,8 @@ public void testCreateContainerBuilder_exceptionMessageHasPackageSuggestionIfPro } @Test - public void - testCreateContainerBuilder_exceptionMessageHasCompileSuggestionIfProjectIsExplodedAndNotWar() - throws IOException { + void testCreateContainerBuilder_exceptionMessageHasCompileSuggestionIfProjectIsExplodedAndNotWar() + throws IOException { String expectedMessage = "Obtaining project build output files failed; make sure you have " + "compiled your project before trying to build the image. (Did you accidentally run \"mvn clean " @@ -617,10 +629,13 @@ public void testCreateContainerBuilder_exceptionMessageHasPackageSuggestionIfPro } @Test - public void testCreateContainerBuilder_noErrorIfWebInfClassesDoesNotExist() + void testCreateContainerBuilder_noErrorIfWebInfClassesDoesNotExist() throws IOException, InvalidImageReferenceException { - temporaryFolder.newFolder("final-name", "WEB-INF", "lib"); - setUpWar(temporaryFolder.getRoot().toPath()); + new File(temporaryFolder.toFile(), "final-name").mkdirs(); + new File(temporaryFolder.toFile(), "WEB-INF").mkdirs(); + new File(temporaryFolder.toFile(), "classes").mkdirs(); + + setUpWar(temporaryFolder); assertThat( mavenProjectProperties.createJibContainerBuilder( @@ -629,31 +644,31 @@ public void testCreateContainerBuilder_noErrorIfWebInfClassesDoesNotExist() } @Test - public void testIsWarProject_warPackagingIsWar() { + void testIsWarProject_warPackagingIsWar() { when(mockMavenProject.getPackaging()).thenReturn("war"); assertThat(mavenProjectProperties.isWarProject()).isTrue(); } @Test - public void testIsWarProject_gwtAppPackagingIsWar() { + void testIsWarProject_gwtAppPackagingIsWar() { when(mockMavenProject.getPackaging()).thenReturn("gwt-app"); assertThat(mavenProjectProperties.isWarProject()).isTrue(); } @Test - public void testIsWarProject_jarPackagingIsNotWar() { + void testIsWarProject_jarPackagingIsNotWar() { when(mockMavenProject.getPackaging()).thenReturn("jar"); assertThat(mavenProjectProperties.isWarProject()).isFalse(); } @Test - public void testIsWarProject_gwtLibPackagingIsNotWar() { + void testIsWarProject_gwtLibPackagingIsNotWar() { when(mockMavenProject.getPackaging()).thenReturn("gwt-lib"); assertThat(mavenProjectProperties.isWarProject()).isFalse(); } @Test - public void testClassifyDependencies() { + void testClassifyDependencies() { Set artifacts = ImmutableSet.of( newArtifact("com.test", "dependencyA", "1.0"), @@ -691,7 +706,7 @@ public void testClassifyDependencies() { } @Test - public void testGetProjectDependencies() { + void testGetProjectDependencies() { MavenProject rootPomProject = mock(MavenProject.class); MavenProject jibSubModule = mock(MavenProject.class); MavenProject sharedLibSubModule = mock(MavenProject.class); @@ -712,20 +727,20 @@ public void testGetProjectDependencies() { } @Test - public void testGetChildValue_null() { + void testGetChildValue_null() { assertThat(MavenProjectProperties.getChildValue(null)).isEmpty(); assertThat(MavenProjectProperties.getChildValue(null, "foo", "bar")).isEmpty(); } @Test - public void testGetChildValue_noPathGiven() { + void testGetChildValue_noPathGiven() { Xpp3Dom root = newXpp3Dom("root", "value"); assertThat(MavenProjectProperties.getChildValue(root)).isEqualTo(Optional.of("value")); } @Test - public void testGetChildValue_noChild() { + void testGetChildValue_noChild() { Xpp3Dom root = newXpp3Dom("root", "value"); assertThat(MavenProjectProperties.getChildValue(root, "foo")).isEmpty(); @@ -733,7 +748,7 @@ public void testGetChildValue_noChild() { } @Test - public void testGetChildValue_childPathMatched() { + void testGetChildValue_childPathMatched() { Xpp3Dom root = newXpp3Dom("root", "value"); Xpp3Dom foo = addXpp3DomChild(root, "foo", "foo"); addXpp3DomChild(foo, "bar", "bar"); @@ -745,7 +760,7 @@ public void testGetChildValue_childPathMatched() { } @Test - public void testGetChildValue_notFullyMatched() { + void testGetChildValue_notFullyMatched() { Xpp3Dom root = newXpp3Dom("root", "value"); Xpp3Dom foo = addXpp3DomChild(root, "foo", "foo"); @@ -755,7 +770,7 @@ public void testGetChildValue_notFullyMatched() { } @Test - public void testGetChildValue_nullValue() { + void testGetChildValue_nullValue() { Xpp3Dom root = new Xpp3Dom("root"); addXpp3DomChild(root, "foo", null); @@ -764,12 +779,12 @@ public void testGetChildValue_nullValue() { } @Test - public void testGetSpringBootRepackageConfiguration_pluginNotApplied() { + void testGetSpringBootRepackageConfiguration_pluginNotApplied() { assertThat(mavenProjectProperties.getSpringBootRepackageConfiguration()).isEmpty(); } @Test - public void testGetSpringBootRepackageConfiguration_noConfigurationBlock() { + void testGetSpringBootRepackageConfiguration_noConfigurationBlock() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution)); @@ -780,7 +795,7 @@ public void testGetSpringBootRepackageConfiguration_noConfigurationBlock() { } @Test - public void testGetSpringBootRepackageConfiguration_noExecutions() { + void testGetSpringBootRepackageConfiguration_noExecutions() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Collections.emptyList()); @@ -788,7 +803,7 @@ public void testGetSpringBootRepackageConfiguration_noExecutions() { } @Test - public void testGetSpringBootRepackageConfiguration_noRepackageGoal() { + void testGetSpringBootRepackageConfiguration_noRepackageGoal() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution)); @@ -797,7 +812,7 @@ public void testGetSpringBootRepackageConfiguration_noRepackageGoal() { } @Test - public void testGetSpringBootRepackageConfiguration_repackageGoal() { + void testGetSpringBootRepackageConfiguration_repackageGoal() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution)); @@ -808,7 +823,7 @@ public void testGetSpringBootRepackageConfiguration_repackageGoal() { } @Test - public void testGetSpringBootRepackageConfiguration_skipped() { + void testGetSpringBootRepackageConfiguration_skipped() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution)); @@ -819,7 +834,7 @@ public void testGetSpringBootRepackageConfiguration_skipped() { } @Test - public void testGetSpringBootRepackageConfiguration_skipNotTrue() { + void testGetSpringBootRepackageConfiguration_skipNotTrue() { when(mockMavenProject.getPlugin("org.springframework.boot:spring-boot-maven-plugin")) .thenReturn(mockPlugin); when(mockPlugin.getExecutions()).thenReturn(Arrays.asList(mockPluginExecution)); @@ -831,7 +846,7 @@ public void testGetSpringBootRepackageConfiguration_skipNotTrue() { } @Test - public void testGetJarArtifact() throws IOException { + void testGetJarArtifact() throws IOException { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -840,7 +855,7 @@ public void testGetJarArtifact() throws IOException { } @Test - public void testGetJarArtifact_outputDirectoryFromJarPlugin() throws IOException { + void testGetJarArtifact_outputDirectoryFromJarPlugin() throws IOException { when(mockMavenProject.getBasedir()).thenReturn(new File("/should/ignore")); when(mockBuild.getDirectory()).thenReturn("/should/ignore"); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -857,7 +872,7 @@ public void testGetJarArtifact_outputDirectoryFromJarPlugin() throws IOException } @Test - public void testGetJarArtifact_relativeOutputDirectoryFromJarPlugin() throws IOException { + void testGetJarArtifact_relativeOutputDirectoryFromJarPlugin() throws IOException { when(mockMavenProject.getBasedir()).thenReturn(new File("/base/dir")); when(mockBuild.getDirectory()).thenReturn(temporaryFolder.getRoot().toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -874,7 +889,7 @@ public void testGetJarArtifact_relativeOutputDirectoryFromJarPlugin() throws IOE } @Test - public void testGetJarArtifact_classifier() throws IOException { + void testGetJarArtifact_classifier() throws IOException { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -890,7 +905,7 @@ public void testGetJarArtifact_classifier() throws IOException { } @Test - public void testGetJarArtifact_executionIdNotMatched() throws IOException { + void testGetJarArtifact_executionIdNotMatched() throws IOException { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -907,13 +922,16 @@ public void testGetJarArtifact_executionIdNotMatched() throws IOException { } @Test - public void testGetJarArtifact_originalJarCopiedIfSpringBoot() throws IOException { - temporaryFolder.newFile("helloworld-1.jar.original"); - when(mockBuild.getDirectory()).thenReturn(temporaryFolder.getRoot().toString()); + void testGetJarArtifact_originalJarCopiedIfSpringBoot() throws IOException { + File f = new File(temporaryFolder.toFile(), "helloworld-1.jar.original"); + f.createNewFile(); + when(mockBuild.getDirectory()).thenReturn(temporaryFolder.toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); setUpSpringBootFatJar(); - Path tempDirectory = temporaryFolder.newFolder("tmp").toPath(); + File f2 = new File(temporaryFolder.toFile(), "tmp"); + f2.mkdirs(); + Path tempDirectory = f2.toPath(); when(mockTempDirectoryProvider.newDirectory()).thenReturn(tempDirectory); assertThat(mavenProjectProperties.getJarArtifact()) @@ -924,7 +942,7 @@ public void testGetJarArtifact_originalJarCopiedIfSpringBoot() throws IOExceptio } @Test - public void testGetJarArtifact_originalJarIfSpringBoot_differentDirectories() throws IOException { + void testGetJarArtifact_originalJarIfSpringBoot_differentDirectories() throws IOException { when(mockMavenProject.getBasedir()).thenReturn(new File("/should/ignore")); when(mockBuild.getDirectory()).thenReturn("/should/ignore"); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -946,10 +964,12 @@ public void testGetJarArtifact_originalJarIfSpringBoot_differentDirectories() th } @Test - public void testGetJarArtifact_originalJarIfSpringBoot_differentFinalNames() throws IOException { - Path buildDirectory = temporaryFolder.newFolder("target").toPath(); + void testGetJarArtifact_originalJarIfSpringBoot_differentFinalNames() throws IOException { + File f = new File(temporaryFolder.toFile(), "target"); + f.mkdirs(); + Path buildDirectory = f.toPath(); Files.createFile(buildDirectory.resolve("helloworld-1.jar")); - when(mockMavenProject.getBasedir()).thenReturn(temporaryFolder.getRoot()); + when(mockMavenProject.getBasedir()).thenReturn(temporaryFolder.toFile()); when(mockBuild.getDirectory()).thenReturn(buildDirectory.toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -971,10 +991,13 @@ public void testGetJarArtifact_originalJarIfSpringBoot_differentFinalNames() thr } @Test - public void testGetJarArtifact_originalJarIfSpringBoot_differentClassifier() throws IOException { - Path buildDirectory = temporaryFolder.newFolder("target").toPath(); + void testGetJarArtifact_originalJarIfSpringBoot_differentClassifier() throws IOException { + File f = new File(temporaryFolder.toFile(), "target"); + f.mkdirs(); + + Path buildDirectory = f.toPath(); Files.createFile(buildDirectory.resolve("helloworld-1.jar")); - when(mockMavenProject.getBasedir()).thenReturn(temporaryFolder.getRoot()); + when(mockMavenProject.getBasedir()).thenReturn(temporaryFolder.toFile()); when(mockBuild.getDirectory()).thenReturn(buildDirectory.toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -996,10 +1019,13 @@ public void testGetJarArtifact_originalJarIfSpringBoot_differentClassifier() thr } @Test - public void testGetJarArtifact_originalJarCopiedIfSpringBoot_sameDirectory() throws IOException { - Path buildDirectory = temporaryFolder.newFolder("target").toPath(); + void testGetJarArtifact_originalJarCopiedIfSpringBoot_sameDirectory() throws IOException { + File f = new File(temporaryFolder.toFile(), "target"); + f.mkdirs(); + + Path buildDirectory = f.toPath(); Files.createFile(buildDirectory.resolve("helloworld-1.jar.original")); - when(mockMavenProject.getBasedir()).thenReturn(temporaryFolder.getRoot()); + when(mockMavenProject.getBasedir()).thenReturn(temporaryFolder.toFile()); when(mockBuild.getDirectory()).thenReturn(buildDirectory.toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -1011,7 +1037,9 @@ public void testGetJarArtifact_originalJarCopiedIfSpringBoot_sameDirectory() thr addXpp3DomChild(pluginConfiguration, "outputDirectory", "target"); setUpSpringBootFatJar(); - Path tempDirectory = temporaryFolder.newFolder("tmp").toPath(); + f = new File(temporaryFolder.toFile(), "tmp"); + f.mkdirs(); + Path tempDirectory = f.toPath(); when(mockTempDirectoryProvider.newDirectory()).thenReturn(tempDirectory); assertThat(mavenProjectProperties.getJarArtifact()) @@ -1022,7 +1050,7 @@ public void testGetJarArtifact_originalJarCopiedIfSpringBoot_sameDirectory() thr } @Test - public void testGetWarArtifact() { + void testGetWarArtifact() { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -1031,7 +1059,7 @@ public void testGetWarArtifact() { } @Test - public void testGetWarArtifact_warNameProperty() { + void testGetWarArtifact_warNameProperty() { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -1046,7 +1074,7 @@ public void testGetWarArtifact_warNameProperty() { } @Test - public void testGetWarArtifact_noWarNameProperty() { + void testGetWarArtifact_noWarNameProperty() { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -1061,7 +1089,7 @@ public void testGetWarArtifact_noWarNameProperty() { } @Test - public void testGetWarArtifact_executionIdNotMatched() { + void testGetWarArtifact_executionIdNotMatched() { when(mockBuild.getDirectory()).thenReturn(Paths.get("/foo/bar").toString()); when(mockBuild.getFinalName()).thenReturn("helloworld-1"); @@ -1077,7 +1105,7 @@ public void testGetWarArtifact_executionIdNotMatched() { } @Test - public void testGetDependencies() throws URISyntaxException { + void testGetDependencies() throws URISyntaxException { assertThat(mavenProjectProperties.getDependencies()) .containsExactly( getResource("maven/application/dependencies/library.jarC.jar"), @@ -1107,7 +1135,7 @@ private BuildContext setUpBuildContext(ContainerizingMode containerizingMode) } private Path setUpWar(Path explodedWar) throws IOException { - Path fakeMavenBuildDirectory = temporaryFolder.getRoot().toPath(); + Path fakeMavenBuildDirectory = temporaryFolder; when(mockBuild.getDirectory()).thenReturn(fakeMavenBuildDirectory.toString()); when(mockBuild.getFinalName()).thenReturn("final-name"); when(mockMavenProject.getPackaging()).thenReturn("war"); @@ -1115,7 +1143,9 @@ private Path setUpWar(Path explodedWar) throws IOException { zipUpDirectory(explodedWar, fakeMavenBuildDirectory.resolve("final-name.war")); // Make "MavenProjectProperties" use this folder to explode the WAR into. - Path unzipTarget = temporaryFolder.newFolder("exploded").toPath(); + File f = new File(temporaryFolder.toFile(), "exploded"); + f.mkdirs(); + Path unzipTarget = f.toPath(); when(mockTempDirectoryProvider.newDirectory()).thenReturn(unzipTarget); return unzipTarget; } diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenRawConfigurationTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenRawConfigurationTest.java index 44798046e6b..5c7a5661d60 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenRawConfigurationTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenRawConfigurationTest.java @@ -32,14 +32,14 @@ import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** Test for {@link MavenRawConfiguration}. */ -public class MavenRawConfigurationTest { +class MavenRawConfigurationTest { @Test - public void testGetters() { + void testGetters() { JibPluginConfiguration jibPluginConfiguration = Mockito.mock(JibPluginConfiguration.class); EventHandlers eventHandlers = Mockito.mock(EventHandlers.class); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsProxyProviderTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsProxyProviderTest.java index b16e3b5c792..ad2f95a1520 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsProxyProviderTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsProxyProviderTest.java @@ -25,19 +25,28 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; /** Test for {@link MavenSettingsProxyProvider}. */ -@RunWith(MockitoJUnitRunner.class) -public class MavenSettingsProxyProviderTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(SystemStubsExtension.class) +class MavenSettingsProxyProviderTest { - @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); + @SystemStub + @SuppressWarnings("unused") + private SystemProperties restoreSystemProperties = new SystemProperties(); private static Settings noActiveProxiesSettings; private static Settings httpOnlyProxySettings; @@ -47,7 +56,7 @@ public class MavenSettingsProxyProviderTest { private static SettingsDecrypter settingsDecrypter; private static SettingsDecrypter emptySettingsDecrypter; - @BeforeClass + @BeforeAll public static void setUpTestFixtures() { noActiveProxiesSettings = SettingsFixture.newSettings( @@ -72,8 +81,8 @@ public static void setUpTestFixtures() { Paths.get("src/test/resources/maven/settings/settings-security.empty.xml")); } - @Before - public void setUp() { + @BeforeEach + void setUpBeforeEach() { Arrays.asList( "http.proxyHost", "http.proxyPort", @@ -88,76 +97,48 @@ public void setUp() { } @Test - public void testAreProxyPropertiesSet() { + void testAreProxyPropertiesSet() { Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); } @Test - public void testAreProxyPropertiesSet_httpHostSet() { + void testAreProxyPropertiesSet_httpHostSet() { System.setProperty("http.proxyHost", "host"); Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); } - @Test - public void testAreProxyPropertiesSet_httpsHostSet() { - System.setProperty("https.proxyHost", "host"); - Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); - Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); - } - - @Test - public void testAreProxyPropertiesSet_httpPortSet() { - System.setProperty("http.proxyPort", "port"); - Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); - Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); - } - - @Test - public void testAreProxyPropertiesSet_httpsPortSet() { - System.setProperty("https.proxyPort", "port"); - Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); - Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); - } - - @Test - public void testAreProxyPropertiesSet_httpUserSet() { - System.setProperty("http.proxyUser", "user"); - Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); - Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); - } - - @Test - public void testAreProxyPropertiesSet_httpsUserSet() { - System.setProperty("https.proxyUser", "user"); + @ParameterizedTest + @CsvSource({ + "https.proxyHost, host", + "https.proxyPort, port", + "https.proxyUser, user", + "https.proxyPassword, password" + }) + void testAreProxyPropertiesSet_httpsHostSet(String key, String value) { + System.setProperty(key, value); Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); } - @Test - public void testAreProxyPropertiesSet_httpPasswordSet() { - System.setProperty("http.proxyPassword", "password"); + @ParameterizedTest + @CsvSource({"http.proxyPort, port", "http.proxyUser, user", "http.proxyPassword, password"}) + void testAreProxyPropertiesSet_httpPortSet(String key, String value) { + System.setProperty(key, value); Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); } @Test - public void testAreProxyPropertiesSet_httpsPasswordSet() { - System.setProperty("https.proxyPassword", "password"); - Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); - Assert.assertTrue(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); - } - - @Test - public void testAreProxyPropertiesSet_ignoresHttpNonProxyHosts() { + void testAreProxyPropertiesSet_ignoresHttpNonProxyHosts() { System.setProperty("http.nonProxyHosts", "non proxy hosts"); Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("http")); Assert.assertFalse(MavenSettingsProxyProvider.areProxyPropertiesSet("https")); } @Test - public void testSetProxyProperties() { + void testSetProxyProperties() { Proxy httpProxy = new Proxy(); httpProxy.setProtocol("http"); httpProxy.setHost("host"); @@ -187,7 +168,7 @@ public void testSetProxyProperties() { } @Test - public void testSetProxyProperties_someValuesUndefined() { + void testSetProxyProperties_someValuesUndefined() { Proxy httpProxy = new Proxy(); httpProxy.setProtocol("http"); httpProxy.setHost("http://host"); @@ -209,7 +190,7 @@ public void testSetProxyProperties_someValuesUndefined() { } @Test - public void testActivateHttpAndHttpsProxies_noActiveProxy() throws MojoExecutionException { + void testActivateHttpAndHttpsProxies_noActiveProxy() throws MojoExecutionException { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( noActiveProxiesSettings, settingsDecrypter); @@ -219,7 +200,7 @@ public void testActivateHttpAndHttpsProxies_noActiveProxy() throws MojoExecution } @Test - public void testActivateHttpAndHttpsProxies_firstActiveHttpProxy() throws MojoExecutionException { + void testActivateHttpAndHttpsProxies_firstActiveHttpProxy() throws MojoExecutionException { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( httpOnlyProxySettings, settingsDecrypter); @@ -228,8 +209,7 @@ public void testActivateHttpAndHttpsProxies_firstActiveHttpProxy() throws MojoEx } @Test - public void testActivateHttpAndHttpsProxies_firstActiveHttpsProxy() - throws MojoExecutionException { + void testActivateHttpAndHttpsProxies_firstActiveHttpsProxy() throws MojoExecutionException { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( httpsOnlyProxySettings, settingsDecrypter); @@ -238,7 +218,7 @@ public void testActivateHttpAndHttpsProxies_firstActiveHttpsProxy() } @Test - public void testActivateHttpAndHttpsProxies_encryptedProxy() throws MojoExecutionException { + void testActivateHttpAndHttpsProxies_encryptedProxy() throws MojoExecutionException { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( mixedProxyEncryptedSettings, settingsDecrypter); @@ -247,8 +227,7 @@ public void testActivateHttpAndHttpsProxies_encryptedProxy() throws MojoExecutio } @Test - public void testActivateHttpAndHttpsProxies_dontOverwriteUserHttp() - throws MojoExecutionException { + void testActivateHttpAndHttpsProxies_dontOverwriteUserHttp() throws MojoExecutionException { System.setProperty("http.proxyHost", "host"); MavenSettingsProxyProvider.activateHttpAndHttpsProxies( mixedProxyEncryptedSettings, settingsDecrypter); @@ -258,8 +237,7 @@ public void testActivateHttpAndHttpsProxies_dontOverwriteUserHttp() } @Test - public void testActivateHttpAndHttpsProxies_dontOverwriteUserHttps() - throws MojoExecutionException { + void testActivateHttpAndHttpsProxies_dontOverwriteUserHttps() throws MojoExecutionException { System.setProperty("https.proxyHost", "host"); MavenSettingsProxyProvider.activateHttpAndHttpsProxies( mixedProxyEncryptedSettings, settingsDecrypter); @@ -269,7 +247,7 @@ public void testActivateHttpAndHttpsProxies_dontOverwriteUserHttps() } @Test - public void testActivateHttpAndHttpsProxies_decryptionFailure() { + void testActivateHttpAndHttpsProxies_decryptionFailure() { try { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( badProxyEncryptedSettings, settingsDecrypter); @@ -282,7 +260,7 @@ public void testActivateHttpAndHttpsProxies_decryptionFailure() { } @Test - public void testActivateHttpAndHttpsProxies_emptySettingsDecrypter() { + void testActivateHttpAndHttpsProxies_emptySettingsDecrypter() { try { MavenSettingsProxyProvider.activateHttpAndHttpsProxies( mixedProxyEncryptedSettings, emptySettingsDecrypter); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsServerCredentialsTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsServerCredentialsTest.java index fa2498035f9..911298b9153 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsServerCredentialsTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MavenSettingsServerCredentialsTest.java @@ -24,11 +24,11 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link MavenSettingsServerCredentials}. */ -public class MavenSettingsServerCredentialsTest { +class MavenSettingsServerCredentialsTest { private MavenSettingsServerCredentials mavenSettingsServerCredentialsNoMasterPassword; private MavenSettingsServerCredentials mavenSettingsServerCredentials; @@ -38,8 +38,8 @@ public class MavenSettingsServerCredentialsTest { private Path testSettingsSecurityEmpty = Paths.get("src/test/resources/maven/settings/settings-security.empty.xml"); - @Before - public void setUp() { + @BeforeEach + void setUp() { mavenSettingsServerCredentials = new MavenSettingsServerCredentials( SettingsFixture.newSettings(testSettings), @@ -51,7 +51,7 @@ public void setUp() { } @Test - public void testInferredAuth_decrypterFailure() { + void testInferredAuth_decrypterFailure() { try { mavenSettingsServerCredentials.inferAuth("badServer"); Assert.fail(); @@ -63,7 +63,7 @@ public void testInferredAuth_decrypterFailure() { } @Test - public void testInferredAuth_successEncrypted() throws InferredAuthException { + void testInferredAuth_successEncrypted() throws InferredAuthException { Optional auth = mavenSettingsServerCredentials.inferAuth("encryptedServer"); Assert.assertTrue(auth.isPresent()); Assert.assertEquals("encryptedUser", auth.get().getUsername()); @@ -71,7 +71,7 @@ public void testInferredAuth_successEncrypted() throws InferredAuthException { } @Test - public void testInferredAuth_successUnencrypted() throws InferredAuthException { + void testInferredAuth_successUnencrypted() throws InferredAuthException { Optional auth = mavenSettingsServerCredentials.inferAuth("simpleServer"); Assert.assertTrue(auth.isPresent()); Assert.assertEquals("simpleUser", auth.get().getUsername()); @@ -79,7 +79,7 @@ public void testInferredAuth_successUnencrypted() throws InferredAuthException { } @Test - public void testInferredAuth_successNoPasswordDoesNotBlowUp() throws InferredAuthException { + void testInferredAuth_successNoPasswordDoesNotBlowUp() throws InferredAuthException { Optional auth = mavenSettingsServerCredentialsNoMasterPassword.inferAuth("simpleServer"); Assert.assertTrue(auth.isPresent()); @@ -88,7 +88,7 @@ public void testInferredAuth_successNoPasswordDoesNotBlowUp() throws InferredAut } @Test - public void testInferredAuth_registryWithHostAndPort() throws InferredAuthException { + void testInferredAuth_registryWithHostAndPort() throws InferredAuthException { Optional auth = mavenSettingsServerCredentialsNoMasterPassword.inferAuth("docker.example.com:8080"); Assert.assertTrue(auth.isPresent()); @@ -97,7 +97,7 @@ public void testInferredAuth_registryWithHostAndPort() throws InferredAuthExcept } @Test - public void testInferredAuth_registryWithHostWithoutPort() throws InferredAuthException { + void testInferredAuth_registryWithHostWithoutPort() throws InferredAuthException { Optional auth = mavenSettingsServerCredentialsNoMasterPassword.inferAuth("docker.example.com"); Assert.assertTrue(auth.isPresent()); @@ -106,7 +106,7 @@ public void testInferredAuth_registryWithHostWithoutPort() throws InferredAuthEx } @Test - public void testInferredAuth_registrySettingsWithPort() throws InferredAuthException { + void testInferredAuth_registrySettingsWithPort() throws InferredAuthException { // Attempt to resolve WITHOUT the port. Should work as well. Optional auth = mavenSettingsServerCredentialsNoMasterPassword.inferAuth("docker.example.com:5432"); @@ -116,7 +116,7 @@ public void testInferredAuth_registrySettingsWithPort() throws InferredAuthExcep } @Test - public void testInferredAuth_notFound() throws InferredAuthException { + void testInferredAuth_notFound() throws InferredAuthException { Assert.assertFalse(mavenSettingsServerCredentials.inferAuth("serverUnknown").isPresent()); } } diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MojoCommonTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MojoCommonTest.java index 88e3901f39b..4a69c6b7555 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MojoCommonTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/MojoCommonTest.java @@ -25,18 +25,21 @@ import com.google.common.util.concurrent.Futures; import java.util.Optional; import java.util.concurrent.Future; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -@RunWith(MockitoJUnitRunner.class) -public class MojoCommonTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MojoCommonTest { @Mock private ProjectProperties mockProjectProperties; @Test - public void testFinishUpdateChecker_correctMessageLogged() { + void testFinishUpdateChecker_correctMessageLogged() { when(mockProjectProperties.getToolName()).thenReturn("tool-name"); when(mockProjectProperties.getToolVersion()).thenReturn("2.0.0"); Future> updateCheckFuture = Futures.immediateFuture(Optional.of("2.1.0")); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestProject.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestProject.java index e335e0b4774..dbbe6c2966b 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestProject.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestProject.java @@ -17,7 +17,6 @@ package com.google.cloud.tools.jib.maven; import com.google.cloud.tools.jib.filesystem.DirectoryWalker; -import java.io.Closeable; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -25,12 +24,14 @@ import java.nio.file.Paths; import java.util.Properties; import org.apache.maven.it.util.ResourceExtractor; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; /** Works with the test Maven projects in the {@code resources/projects} directory. */ -public class TestProject extends TemporaryFolder implements Closeable { +public class TestProject implements BeforeEachCallback { private static final String PROJECTS_PATH_IN_RESOURCES = "/maven/projects/"; + private final Path tempDir; private static boolean isPomXml(Path path) { String filename = path.getFileName().toString(); @@ -42,8 +43,9 @@ private static boolean isPomXml(Path path) { private Path projectRoot; /** Initialize to a specific project directory. */ - public TestProject(String projectDir) { + public TestProject(String projectDir, Path tempDir) { this.projectDir = projectDir; + this.tempDir = tempDir; } /** Gets the project root resolved as a real path. */ @@ -52,21 +54,18 @@ public Path getProjectRoot() throws IOException { } @Override - public void close() { - after(); - } - - @Override - protected void before() throws Throwable { - super.before(); - + public void beforeEach(ExtensionContext context) throws Exception { + projectRoot = this.tempDir; copyProject(); } private void copyProject() throws IOException { projectRoot = ResourceExtractor.extractResourcePath( - TestProject.class, PROJECTS_PATH_IN_RESOURCES + projectDir, newFolder(), true) + TestProject.class, + PROJECTS_PATH_IN_RESOURCES + projectDir, + Files.createTempDirectory("jib").toFile(), + true) .toPath(); // Puts the correct plugin version into the test project pom.xml. diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestRepository.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestRepository.java index 998be427eed..2adf8f40320 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestRepository.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/TestRepository.java @@ -17,8 +17,6 @@ package com.google.cloud.tools.jib.maven; import com.google.common.io.Resources; -import java.net.MalformedURLException; -import java.net.URISyntaxException; import java.nio.file.Path; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; @@ -31,12 +29,13 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.plugin.testing.MojoRule; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.junit.Assert; -import org.junit.rules.ExternalResource; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; /** A test helper to resolve artifacts from a local repository in test/resources. */ -public class TestRepository extends ExternalResource { +class TestRepository implements BeforeEachCallback, AfterEachCallback { private static final String TEST_M2 = "maven/testM2"; @@ -44,23 +43,6 @@ public class TestRepository extends ExternalResource { private ArtifactResolver artifactResolver; private ArtifactHandler jarHandler; - @Override - protected void before() - throws ComponentLookupException, URISyntaxException, MalformedURLException { - MojoRule testHarness = new MojoRule(); - ArtifactRepositoryFactory artifactRepositoryFactory = - testHarness.lookup(ArtifactRepositoryFactory.class); - artifactResolver = testHarness.lookup(ArtifactResolver.class); - jarHandler = testHarness.lookup(ArtifactHandlerManager.class).getArtifactHandler("jar"); - testLocalRepo = - artifactRepositoryFactory.createArtifactRepository( - "test", - Resources.getResource(TEST_M2).toURI().toURL().toString(), - new DefaultRepositoryLayout(), - null, - null); - } - Artifact findArtifact(String group, String artifact, String version) { ArtifactResolutionRequest artifactResolutionRequest = new ArtifactResolutionRequest(); artifactResolutionRequest.setLocalRepository(testLocalRepo); @@ -78,4 +60,23 @@ Artifact findArtifact(String group, String artifact, String version) { Path artifactPathOnDisk(String group, String artifact, String version) { return findArtifact(group, artifact, version).getFile().toPath(); } + + @Override + public void afterEach(ExtensionContext context) throws Exception {} + + @Override + public void beforeEach(ExtensionContext context) throws Exception { + MojoRule testHarness = new MojoRule(); + ArtifactRepositoryFactory artifactRepositoryFactory = + testHarness.lookup(ArtifactRepositoryFactory.class); + artifactResolver = testHarness.lookup(ArtifactResolver.class); + jarHandler = testHarness.lookup(ArtifactHandlerManager.class).getArtifactHandler("jar"); + testLocalRepo = + artifactRepositoryFactory.createArtifactRepository( + "test", + Resources.getResource(TEST_M2).toURI().toURL().toString(), + new DefaultRepositoryLayout(), + null, + null); + } } diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/CheckJibVersionMojoTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/CheckJibVersionMojoTest.java index 579d9b919ac..a7f741a7649 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/CheckJibVersionMojoTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/CheckJibVersionMojoTest.java @@ -19,26 +19,37 @@ import com.google.cloud.tools.jib.maven.MojoCommon; import com.google.cloud.tools.jib.maven.TestProject; import java.io.IOException; +import java.nio.file.Path; import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link CheckJibVersionMojo}. */ -public class CheckJibVersionMojoTest { +@ExtendWith({MockitoExtension.class}) +@MockitoSettings(strictness = Strictness.LENIENT) +class CheckJibVersionMojoTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; + + @RegisterExtension + public final TestProject simpleTestProject = new TestProject("simple", tempDir); @Test - public void testIdentifiers() { + void testIdentifiers() { // These identifiers will be baked into Skaffold and should not be changed Assert.assertEquals("_skaffold-fail-if-jib-out-of-date", CheckJibVersionMojo.GOAL_NAME); Assert.assertEquals("jib.requiredVersion", MojoCommon.REQUIRED_VERSION_PROPERTY_NAME); } @Test - public void testFailOnMissingProperty() throws VerificationException, IOException { + void testFailOnMissingProperty() throws VerificationException, IOException { Verifier verifier = new Verifier(simpleTestProject.getProjectRoot().toString()); try { verifier.executeGoal("jib:" + CheckJibVersionMojo.GOAL_NAME); @@ -49,7 +60,7 @@ public void testFailOnMissingProperty() throws VerificationException, IOExceptio } @Test - public void testFailOnOutOfDate() throws VerificationException, IOException { + void testFailOnOutOfDate() throws VerificationException, IOException { Verifier verifier = new Verifier(simpleTestProject.getProjectRoot().toString()); verifier.setSystemProperty(MojoCommon.REQUIRED_VERSION_PROPERTY_NAME, "[,1.0)"); try { @@ -61,7 +72,7 @@ public void testFailOnOutOfDate() throws VerificationException, IOException { } @Test - public void testSuccess() throws VerificationException, IOException { + void testSuccess() throws VerificationException, IOException { Verifier verifier = new Verifier(simpleTestProject.getProjectRoot().toString()); verifier.setSystemProperty(MojoCommon.REQUIRED_VERSION_PROPERTY_NAME, "[1.0,)"); verifier.executeGoal("jib:" + CheckJibVersionMojo.GOAL_NAME); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2KotlinTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2KotlinTest.java index 8eba9ce30b1..63481881c59 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2KotlinTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2KotlinTest.java @@ -26,16 +26,19 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Kotlin-related tests for {@link FilesMojoV2}. */ -@RunWith(MockitoJUnitRunner.class) -public class FilesMojoV2KotlinTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class FilesMojoV2KotlinTest { private final PluginExecution pluginExecution1 = new PluginExecution(); private final PluginExecution pluginExecution2 = new PluginExecution(); @@ -51,8 +54,8 @@ public class FilesMojoV2KotlinTest { @Mock private MavenProject mavenProject; @Mock private Plugin kotlinPlugin; - @Before - public void setUp() { + @BeforeEach + void setUp() { Mockito.when(mavenProject.getPlugin("org.jetbrains.kotlin:kotlin-maven-plugin")) .thenReturn(kotlinPlugin); Mockito.when(mavenProject.getBasedir()).thenReturn(new File("/base")); @@ -62,13 +65,13 @@ public void setUp() { } @Test - public void getKotlinSourceDirectories_noKotlinPlugin() { + void getKotlinSourceDirectories_noKotlinPlugin() { Mockito.when(mavenProject.getPlugin(Mockito.anyString())).thenReturn(null); Assert.assertEquals(ImmutableSet.of(), FilesMojoV2.getKotlinSourceDirectories(mavenProject)); } @Test - public void getKotlinSourceDirectories_noExecutions() { + void getKotlinSourceDirectories_noExecutions() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Collections.emptyList()); Assert.assertEquals( @@ -77,7 +80,7 @@ public void getKotlinSourceDirectories_noExecutions() { } @Test - public void getKotlinSourceDirectories_noConfiguration() { + void getKotlinSourceDirectories_noConfiguration() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); pluginExecution1.setConfiguration(null); @@ -87,7 +90,7 @@ public void getKotlinSourceDirectories_noConfiguration() { } @Test - public void getKotlinSourceDirectories_noSourceDirs() { + void getKotlinSourceDirectories_noSourceDirs() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); Assert.assertEquals( @@ -96,7 +99,7 @@ public void getKotlinSourceDirectories_noSourceDirs() { } @Test - public void getKotlinSourceDirectories_noSourceDirsChildren() { + void getKotlinSourceDirectories_noSourceDirsChildren() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); configuration1.addChild(sourceDirs1); @@ -106,7 +109,7 @@ public void getKotlinSourceDirectories_noSourceDirsChildren() { } @Test - public void getKotlinSourceDirectories_nullSourceDir() { + void getKotlinSourceDirectories_nullSourceDir() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); configuration1.addChild(sourceDirs1); sourceDirs1.addChild(sourceDir1); @@ -117,7 +120,7 @@ public void getKotlinSourceDirectories_nullSourceDir() { } @Test - public void getKotlinSourceDirectories_emptySourceDir() { + void getKotlinSourceDirectories_emptySourceDir() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); configuration1.addChild(sourceDirs1); sourceDirs1.addChild(sourceDir1); @@ -129,7 +132,7 @@ public void getKotlinSourceDirectories_emptySourceDir() { } @Test - public void getKotlinSourceDirectories_relativePath() { + void getKotlinSourceDirectories_relativePath() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); configuration1.addChild(sourceDirs1); sourceDirs1.addChild(sourceDir1); @@ -141,7 +144,7 @@ public void getKotlinSourceDirectories_relativePath() { } @Test - public void getKotlinSourceDirectories_absolutePath() { + void getKotlinSourceDirectories_absolutePath() { Mockito.when(kotlinPlugin.getExecutions()).thenReturn(Arrays.asList(pluginExecution1)); configuration1.addChild(sourceDirs1); sourceDirs1.addChild(sourceDir1); @@ -153,7 +156,7 @@ public void getKotlinSourceDirectories_absolutePath() { } @Test - public void getKotlinSourceDirectories_complex() { + void getKotlinSourceDirectories_complex() { Mockito.when(kotlinPlugin.getExecutions()) .thenReturn(Arrays.asList(pluginExecution1, pluginExecution2)); configuration1.addChild(sourceDirs1); @@ -178,7 +181,7 @@ public void getKotlinSourceDirectories_complex() { } @Test - public void getKotlinSourceDirectories_noDuplicates() { + void getKotlinSourceDirectories_noDuplicates() { Mockito.when(kotlinPlugin.getExecutions()) .thenReturn(Arrays.asList(pluginExecution1, pluginExecution2)); configuration1.addChild(sourceDirs1); @@ -198,7 +201,7 @@ public void getKotlinSourceDirectories_noDuplicates() { } @Test - public void getKotlinSourceDirectories_excludeTestCompileGoal() { + void getKotlinSourceDirectories_excludeTestCompileGoal() { Mockito.when(kotlinPlugin.getExecutions()) .thenReturn(Arrays.asList(pluginExecution1, pluginExecution2)); pluginExecution1.setGoals(Arrays.asList("compile")); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2Test.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2Test.java index 929d57842a4..bc77573a1f9 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2Test.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/FilesMojoV2Test.java @@ -30,15 +30,24 @@ import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link FilesMojoV2}. */ -public class FilesMojoV2Test { +@ExtendWith({MockitoExtension.class}) +@MockitoSettings(strictness = Strictness.LENIENT) +class FilesMojoV2Test { + @TempDir Path tempDir; - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @RegisterExtension + public final TestProject simpleTestProject = new TestProject("simple", tempDir); - @ClassRule public static final TestProject multiTestProject = new TestProject("multi"); + @RegisterExtension public final TestProject multiTestProject = new TestProject("multi", tempDir); private static void verifyFiles( Path projectRoot, @@ -75,7 +84,7 @@ private static void verifyFiles( } @Test - public void testFilesMojo_singleModule() throws VerificationException, IOException { + void testFilesMojo_singleModule() throws VerificationException, IOException { Path projectRoot = simpleTestProject.getProjectRoot(); verifyFiles( @@ -92,7 +101,7 @@ public void testFilesMojo_singleModule() throws VerificationException, IOExcepti } @Test - public void testFilesMojo_singleModuleWithMultipleExtraDirectories() + void testFilesMojo_singleModuleWithMultipleExtraDirectories() throws VerificationException, IOException { Path projectRoot = simpleTestProject.getProjectRoot(); @@ -111,7 +120,7 @@ public void testFilesMojo_singleModuleWithMultipleExtraDirectories() } @Test - public void testFilesMojo_multiModuleSimpleService() throws VerificationException, IOException { + void testFilesMojo_multiModuleSimpleService() throws VerificationException, IOException { Path projectRoot = multiTestProject.getProjectRoot(); Path simpleServiceRoot = projectRoot.resolve("simple-service"); @@ -131,7 +140,7 @@ public void testFilesMojo_multiModuleSimpleService() throws VerificationExceptio } @Test - public void testFilesMojo_multiModuleComplexService() throws VerificationException, IOException { + void testFilesMojo_multiModuleComplexService() throws VerificationException, IOException { Path projectRoot = multiTestProject.getProjectRoot(); Path complexServiceRoot = projectRoot.resolve("complex-service"); Path libRoot = projectRoot.resolve("lib"); @@ -162,7 +171,7 @@ public void testFilesMojo_multiModuleComplexService() throws VerificationExcepti } @Test - public void testFilesMojo_extraDirectoriesProperty() throws VerificationException, IOException { + void testFilesMojo_extraDirectoriesProperty() throws VerificationException, IOException { Path projectRoot = simpleTestProject.getProjectRoot(); verifyFiles( @@ -181,7 +190,7 @@ public void testFilesMojo_extraDirectoriesProperty() throws VerificationExceptio } @Test - public void testFilesMojo_skaffoldConfigProperties() throws VerificationException, IOException { + void testFilesMojo_skaffoldConfigProperties() throws VerificationException, IOException { Path projectRoot = simpleTestProject.getProjectRoot(); verifyFiles( diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/InitMojoTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/InitMojoTest.java index dc273aa4038..f4afdfdbf88 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/InitMojoTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/InitMojoTest.java @@ -32,18 +32,27 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link InitMojo}. */ -public class InitMojoTest { +@ExtendWith({MockitoExtension.class}) +@MockitoSettings(strictness = Strictness.LENIENT) +class InitMojoTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); + @TempDir Path tempDir; - @ClassRule public static final TestProject multiTestProject = new TestProject("multi"); + @RegisterExtension public TestProject simpleTestProject = new TestProject("simple", tempDir); - @ClassRule - public static final TestProject springTestProject = new TestProject("spring-boot-multi"); + @RegisterExtension public TestProject multiTestProject = new TestProject("multi", tempDir); + + @RegisterExtension + public TestProject springTestProject = new TestProject("spring-boot-multi", tempDir); /** * Verifies that the files task succeeded and returns the list of JSON strings printed by the @@ -76,7 +85,7 @@ private static List getJsons(TestProject project) } @Test - public void testFilesMojo_singleModule() throws IOException, VerificationException { + void testFilesMojo_singleModule() throws IOException, VerificationException { List outputs = getJsons(simpleTestProject); Assert.assertEquals(1, outputs.size()); @@ -86,7 +95,7 @@ public void testFilesMojo_singleModule() throws IOException, VerificationExcepti } @Test - public void testFilesMojo_multiModule() throws IOException, VerificationException { + void testFilesMojo_multiModule() throws IOException, VerificationException { List outputs = getJsons(multiTestProject); Assert.assertEquals(3, outputs.size()); @@ -104,8 +113,7 @@ public void testFilesMojo_multiModule() throws IOException, VerificationExceptio } @Test - public void testFilesMojo_multiModule_differentParent() - throws IOException, VerificationException { + void testFilesMojo_multiModule_differentParent() throws IOException, VerificationException { List outputs = getJsons(springTestProject); Assert.assertEquals(2, outputs.size()); diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/PackageGoalsMojoTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/PackageGoalsMojoTest.java index dbd80d4e776..ca598e4d5b0 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/PackageGoalsMojoTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/PackageGoalsMojoTest.java @@ -28,13 +28,22 @@ import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link PackageGoalsMojo}. */ -public class PackageGoalsMojoTest { +@ExtendWith({MockitoExtension.class}) +@MockitoSettings(strictness = Strictness.LENIENT) +class PackageGoalsMojoTest { - @ClassRule public static final TestProject multiTestProject = new TestProject("multi"); + @TempDir Path tempDir; + + @RegisterExtension public final TestProject multiTestProject = new TestProject("multi", tempDir); private void verifyGoals(Path projectRoot, String profilesString, String... expectedGoals) throws VerificationException, IOException { @@ -60,25 +69,23 @@ private void verifyGoals(Path projectRoot, String profilesString, String... expe } @Test - public void testPackageGoalsMojo_complexServiceDefault() - throws VerificationException, IOException { + void testPackageGoalsMojo_complexServiceDefault() throws VerificationException, IOException { verifyGoals(multiTestProject.getProjectRoot(), null); } @Test - public void testPackageGoalsMojo_complexServiceLocalProfile() - throws VerificationException, IOException { + void testPackageGoalsMojo_complexServiceLocalProfile() throws VerificationException, IOException { verifyGoals(multiTestProject.getProjectRoot(), "localJib", "dockerBuild"); } @Test - public void testPackageGoalsMojo_complexServiceRemoteProfile() + void testPackageGoalsMojo_complexServiceRemoteProfile() throws VerificationException, IOException { verifyGoals(multiTestProject.getProjectRoot(), "remoteJib", "build"); } @Test - public void testPackageGoalsMojo_complexServiceMultipleProfiles() + void testPackageGoalsMojo_complexServiceMultipleProfiles() throws VerificationException, IOException { verifyGoals(multiTestProject.getProjectRoot(), "localJib,remoteJib", "dockerBuild", "build"); } diff --git a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/SyncMapMojoTest.java b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/SyncMapMojoTest.java index 31001fe0758..35b46b7c4a5 100644 --- a/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/SyncMapMojoTest.java +++ b/jib-maven-plugin/src/test/java/com/google/cloud/tools/jib/maven/skaffold/SyncMapMojoTest.java @@ -34,15 +34,28 @@ import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link SyncMapMojo}. */ -public class SyncMapMojoTest { +@ExtendWith({MockitoExtension.class}) +@MockitoSettings(strictness = Strictness.LENIENT) +class SyncMapMojoTest { - @ClassRule public static final TestProject simpleTestProject = new TestProject("simple"); - @ClassRule public static final TestProject multiTestProject = new TestProject("multi"); - @ClassRule public static final TestProject warProject = new TestProject("war_servlet25"); + @TempDir Path tempDir; + + @RegisterExtension + public final TestProject simpleTestProject = new TestProject("simple", tempDir); + + @RegisterExtension public final TestProject multiTestProject = new TestProject("multi", tempDir); + + @RegisterExtension + public final TestProject warProject = new TestProject("war_servlet25", tempDir); private static Path runBuild(Path projectRoot, String module, String pomXml) throws VerificationException { @@ -82,7 +95,7 @@ private static void assertFilePaths(Path src, AbsoluteUnixPath dest, FileTemplat } @Test - public void testSyncMapMojo_simpleTestProjectOutput() throws IOException, VerificationException { + void testSyncMapMojo_simpleTestProjectOutput() throws IOException, VerificationException { Path projectRoot = simpleTestProject.getProjectRoot(); String json = getSyncMapJson(projectRoot, null, null); SkaffoldSyncMapTemplate parsed = SkaffoldSyncMapTemplate.from(json); @@ -111,7 +124,7 @@ public void testSyncMapMojo_simpleTestProjectOutput() throws IOException, Verifi } @Test - public void testSyncMapMojo_multiProjectOutput() throws IOException, VerificationException { + void testSyncMapMojo_multiProjectOutput() throws IOException, VerificationException { Path projectRoot = multiTestProject.getProjectRoot(); Path m2 = Paths.get(System.getProperty("user.home")).resolve(".m2").resolve("repository"); String json = getSyncMapJson(projectRoot, "complex-service", null); @@ -146,7 +159,7 @@ public void testSyncMapMojo_multiProjectOutput() throws IOException, Verificatio } @Test - public void testSyncMapMojo_skaffoldConfig() throws IOException, VerificationException { + void testSyncMapMojo_skaffoldConfig() throws IOException, VerificationException { Path projectRoot = simpleTestProject.getProjectRoot(); String json = getSyncMapJson(projectRoot, null, "pom-skaffold-config.xml"); SkaffoldSyncMapTemplate parsed = SkaffoldSyncMapTemplate.from(json); @@ -169,7 +182,7 @@ public void testSyncMapMojo_skaffoldConfig() throws IOException, VerificationExc } @Test - public void testSyncMapMojo_failIfPackagingNotJar() throws IOException { + void testSyncMapMojo_failIfPackagingNotJar() throws IOException { Path projectRoot = warProject.getProjectRoot(); VerificationException ve = assertThrows(VerificationException.class, () -> runBuild(projectRoot, null, null)); @@ -181,7 +194,7 @@ public void testSyncMapMojo_failIfPackagingNotJar() throws IOException { } @Test - public void testSyncMapMojo_failIfJarContainerizationMode() throws IOException { + void testSyncMapMojo_failIfJarContainerizationMode() throws IOException { Path projectRoot = simpleTestProject.getProjectRoot(); VerificationException ve = assertThrows( diff --git a/jib-maven-plugin/src/test/resources/maven/projects/war_servlet25/pom-tomcat.xml b/jib-maven-plugin/src/test/resources/maven/projects/war_servlet25/pom-tomcat.xml index dc65ff9dea8..bedec4d6712 100644 --- a/jib-maven-plugin/src/test/resources/maven/projects/war_servlet25/pom-tomcat.xml +++ b/jib-maven-plugin/src/test/resources/maven/projects/war_servlet25/pom-tomcat.xml @@ -30,6 +30,11 @@ + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + org.apache.maven.plugins maven-compiler-plugin diff --git a/jib-plugins-common/build.gradle b/jib-plugins-common/build.gradle index 6adf2158844..54601db7f04 100644 --- a/jib-plugins-common/build.gradle +++ b/jib-plugins-common/build.gradle @@ -13,8 +13,12 @@ dependencies { implementation dependencyStrings.EXTENSION_COMMON - testImplementation dependencyStrings.JUNIT + testImplementation dependencyStrings.JUNIT_API + testRuntimeOnly dependencyStrings.JUNIT_ENGINE testImplementation dependencyStrings.JUNIT_PARAMS + testImplementation dependencyStrings.JUNIT_PARAM_TESTS + testImplementation dependencyStrings.SYSTEM_RULES_STUB + testImplementation dependencyStrings.TRUTH testImplementation dependencyStrings.TRUTH8 testImplementation dependencyStrings.MOCKITO_CORE diff --git a/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/ProjectProperties.java b/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/ProjectProperties.java index e8a0516226b..bfcf30f6804 100644 --- a/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/ProjectProperties.java +++ b/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/ProjectProperties.java @@ -25,6 +25,7 @@ import java.io.IOException; import java.nio.file.Path; import java.util.List; +import java.util.Optional; import javax.annotation.Nullable; /** Project property methods that require maven/gradle-specific implementations. */ @@ -92,6 +93,15 @@ JibContainerBuilder createJibContainerBuilder( JibContainerBuilder runPluginExtensions( List extensionConfigs, - JibContainerBuilder jibContainerBuilder) + JibContainerBuilder jibContainerBuilder, + Optional project) throws JibPluginExtensionException; + + default JibContainerBuilder runPluginExtensions( + List extensionConfigs, + JibContainerBuilder jibContainerBuilder) + throws JibPluginExtensionException { + return runPluginExtensions( + extensionConfigs, jibContainerBuilder, Optional.empty()); // for maven + } } diff --git a/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutput.java b/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutput.java index 33594d3648e..6c955d7b509 100644 --- a/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutput.java +++ b/jib-plugins-common/src/main/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutput.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; @@ -97,6 +98,15 @@ public void addBuild(Path build) { skaffoldFilesTemplate.build.add(build.toString()); } + /** + * Adds a build file/directory. + * + * @param build the path to the file/directory + */ + public void addBuild(File build) { + addBuild(build.toPath()); + } + /** * Adds an input file/directory. * @@ -106,6 +116,15 @@ public void addInput(Path inputFile) { skaffoldFilesTemplate.inputs.add(inputFile.toString()); } + /** + * Adds an input file/directory. + * + * @param inputFile the path to the file/directory + */ + public void addInput(File inputFile) { + addInput(inputFile.toPath()); + } + /** * Adds an ignored file/directory. * @@ -115,6 +134,15 @@ public void addIgnore(Path ignoreFile) { skaffoldFilesTemplate.ignore.add(ignoreFile.toString()); } + /** + * Adds an ignored file/directory. + * + * @param ignoreFile the path to the file/directory + */ + public void addIgnore(File ignoreFile) { + addIgnore(ignoreFile.toPath()); + } + @VisibleForTesting public List getBuild() { return skaffoldFilesTemplate.build; diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ConfigurationPropertyValidatorTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ConfigurationPropertyValidatorTest.java index 737ae4a4012..5a80b98d5e6 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ConfigurationPropertyValidatorTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ConfigurationPropertyValidatorTest.java @@ -31,21 +31,24 @@ import com.google.cloud.tools.jib.api.LogEvent; import java.util.Optional; import java.util.function.Consumer; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ConfigurationPropertyValidator}. */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigurationPropertyValidatorTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ConfigurationPropertyValidatorTest { @Mock private Consumer mockLogger; @Mock private AuthProperty mockAuth; @Mock private RawConfiguration mockConfiguration; @Test - public void testGetImageAuth() { + void testGetImageAuth() { when(mockAuth.getUsernameDescriptor()).thenReturn("user"); when(mockAuth.getPasswordDescriptor()).thenReturn("pass"); when(mockAuth.getUsername()).thenReturn("vwxyz"); @@ -100,7 +103,7 @@ public void testGetImageAuth() { } @Test - public void testGetGeneratedTargetDockerTag() throws InvalidImageReferenceException { + void testGetGeneratedTargetDockerTag() throws InvalidImageReferenceException { HelpfulSuggestions helpfulSuggestions = new HelpfulSuggestions("", "", "to", "--to", "build.txt"); @@ -140,7 +143,7 @@ public void testGetGeneratedTargetDockerTag() throws InvalidImageReferenceExcept } @Test - public void testParseListProperty() { + void testParseListProperty() { assertThat(ConfigurationPropertyValidator.parseListProperty("abc")).containsExactly("abc"); assertThat( ConfigurationPropertyValidator.parseListProperty( @@ -157,7 +160,7 @@ public void testParseListProperty() { } @Test - public void testParseMapProperty() { + void testParseMapProperty() { assertThat(ConfigurationPropertyValidator.parseMapProperty("abc=def")) .containsExactly("abc", "def"); assertThat( diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ContainerizingModeTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ContainerizingModeTest.java index 3abd56f1a52..b440552862a 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ContainerizingModeTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ContainerizingModeTest.java @@ -17,19 +17,19 @@ package com.google.cloud.tools.jib.plugins.common; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ContainerizingMode}. */ -public class ContainerizingModeTest { +class ContainerizingModeTest { @Test - public void testFrom_validValues() throws InvalidContainerizingModeException { + void testFrom_validValues() throws InvalidContainerizingModeException { Assert.assertEquals(ContainerizingMode.EXPLODED, ContainerizingMode.from("exploded")); Assert.assertEquals(ContainerizingMode.PACKAGED, ContainerizingMode.from("packaged")); } @Test - public void testFrom_invalidCasing() { + void testFrom_invalidCasing() { try { ContainerizingMode.from("PACKAGED"); Assert.fail(); @@ -40,7 +40,7 @@ public void testFrom_invalidCasing() { } @Test - public void testFrom_invalidValue() { + void testFrom_invalidValue() { try { ContainerizingMode.from("this is wrong"); Assert.fail(); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/DefaultCredentialRetrieversTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/DefaultCredentialRetrieversTest.java index 16a765fc561..785b24acd14 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/DefaultCredentialRetrieversTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/DefaultCredentialRetrieversTest.java @@ -27,6 +27,7 @@ import com.google.cloud.tools.jib.api.CredentialRetriever; import com.google.cloud.tools.jib.frontend.CredentialRetrieverFactory; import com.google.common.collect.ImmutableMap; +import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; @@ -36,19 +37,21 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.io.TempDir; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link DefaultCredentialRetrievers}. */ -@RunWith(MockitoJUnitRunner.class) -public class DefaultCredentialRetrieversTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DefaultCredentialRetrieversTest { - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock private CredentialRetrieverFactory mockCredentialRetrieverFactory; @Mock private CredentialRetriever mockDockerCredentialHelperCredentialRetriever; @@ -75,8 +78,8 @@ public class DefaultCredentialRetrieversTest { private final Credential knownCredential = Credential.from("username", "password"); private final Credential inferredCredential = Credential.from("username2", "password2"); - @Before - public void setUp() { + @BeforeEach + void setUp() { properties = new Properties(); properties.setProperty("os.name", "unknown"); properties.setProperty("user.home", Paths.get("/system/home").toString()); @@ -138,7 +141,7 @@ public void setUp() { } @Test - public void testAsList() throws FileNotFoundException { + void testAsList() throws FileNotFoundException { List retriever = new DefaultCredentialRetrievers(mockCredentialRetrieverFactory, properties, environment) .asList(); @@ -162,7 +165,7 @@ public void testAsList() throws FileNotFoundException { } @Test - public void testAsList_all() throws FileNotFoundException { + void testAsList_all() throws FileNotFoundException { List retrievers = new DefaultCredentialRetrievers(mockCredentialRetrieverFactory, properties, environment) .setKnownCredential(knownCredential, "credentialSource") @@ -197,8 +200,9 @@ public void testAsList_all() throws FileNotFoundException { } @Test - public void testAsList_credentialHelperPath() throws IOException { - Path fakeCredentialHelperPath = temporaryFolder.newFile("fake-credHelper").toPath(); + void testAsList_credentialHelperPath() throws IOException { + Path fakeCredentialHelperPath = new File(temporaryFolder.toFile(), "fake-credHelper").toPath(); + fakeCredentialHelperPath.toFile().createNewFile(); DefaultCredentialRetrievers credentialRetrievers = new DefaultCredentialRetrievers(mockCredentialRetrieverFactory, properties, environment) .setCredentialHelper(fakeCredentialHelperPath.toString()); @@ -233,7 +237,7 @@ public void testAsList_credentialHelperPath() throws IOException { } @Test - public void testDockerConfigRetrievers_undefinedHome() throws FileNotFoundException { + void testDockerConfigRetrievers_undefinedHome() throws FileNotFoundException { List retrievers = new DefaultCredentialRetrievers( mockCredentialRetrieverFactory, new Properties(), new HashMap<>()) @@ -246,7 +250,7 @@ mockCredentialRetrieverFactory, new Properties(), new HashMap<>()) } @Test - public void testDockerConfigRetrievers_noDuplicateRetrievers() throws FileNotFoundException { + void testDockerConfigRetrievers_noDuplicateRetrievers() throws FileNotFoundException { properties.setProperty("user.home", Paths.get("/env/home").toString()); List retrievers = new DefaultCredentialRetrievers(mockCredentialRetrieverFactory, properties, environment) @@ -286,8 +290,10 @@ public void testDockerConfigRetrievers_noDuplicateRetrievers() throws FileNotFou } @Test - public void testCredentialHelper_cmdExtension() throws IOException { - Path credHelper = temporaryFolder.newFile("foo.cmd").toPath(); + void testCredentialHelper_cmdExtension() throws IOException { + File f = new File(temporaryFolder.toFile(), "foo.cmd"); + f.createNewFile(); + Path credHelper = f.toPath(); Path pathWithoutCmd = credHelper.getParent().resolve("foo"); assertThat(credHelper).isEqualTo(pathWithoutCmd.getParent().resolve("foo.cmd")); @@ -325,8 +331,10 @@ public void testCredentialHelper_cmdExtension() throws IOException { } @Test - public void testCredentialHelper_exeExtension() throws IOException { - Path credHelper = temporaryFolder.newFile("foo.exe").toPath(); + void testCredentialHelper_exeExtension() throws IOException { + File f = new File(temporaryFolder.toFile(), "foo.exe"); + f.createNewFile(); + Path credHelper = f.toPath(); Path pathWithoutExe = credHelper.getParent().resolve("foo"); assertThat(credHelper).isEqualTo(pathWithoutExe.getParent().resolve("foo.exe")); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/HelpfulSuggestionsTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/HelpfulSuggestionsTest.java index 2efcc619d85..8f20f87e571 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/HelpfulSuggestionsTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/HelpfulSuggestionsTest.java @@ -18,17 +18,17 @@ import java.nio.file.Paths; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link HelpfulSuggestions}. */ -public class HelpfulSuggestionsTest { +class HelpfulSuggestionsTest { private static final HelpfulSuggestions TEST_HELPFUL_SUGGESTIONS = new HelpfulSuggestions( "messagePrefix", "clearCacheCommand", "toProperty", "toFlag", "buildFile"); @Test - public void testSuggestions_smoke() { + void testSuggestions_smoke() { Assert.assertEquals( "messagePrefix, perhaps you should make sure your Internet is up and that the registry you are pushing to exists", TEST_HELPFUL_SUGGESTIONS.forHttpHostConnect()); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ImageMetadataOutputTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ImageMetadataOutputTest.java index 037a5b31b16..7ecaa5f087d 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ImageMetadataOutputTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ImageMetadataOutputTest.java @@ -19,9 +19,9 @@ import com.google.common.collect.ImmutableList; import java.io.IOException; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ImageMetadataOutputTest { +class ImageMetadataOutputTest { private static final String TEST_JSON = "{\"image\":" @@ -35,7 +35,7 @@ public class ImageMetadataOutputTest { + "}"; @Test - public void testFromJson() throws IOException { + void testFromJson() throws IOException { ImageMetadataOutput output = ImageMetadataOutput.fromJson(TEST_JSON); Assert.assertEquals("gcr.io/project/image:tag", output.getImage()); Assert.assertEquals( @@ -50,7 +50,7 @@ public void testFromJson() throws IOException { } @Test - public void testToJson() throws IOException { + void testToJson() throws IOException { ImageMetadataOutput output = ImageMetadataOutput.fromJson(TEST_JSON); Assert.assertEquals(TEST_JSON, output.toJson()); } diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JavaContainerBuilderHelperTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JavaContainerBuilderHelperTest.java index 808306473e7..e5c841d21cd 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JavaContainerBuilderHelperTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JavaContainerBuilderHelperTest.java @@ -48,12 +48,11 @@ import java.util.Collections; import java.util.Map; import java.util.Set; -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; /** Tests for {@link JavaContainerBuilderHelper}. */ -public class JavaContainerBuilderHelperTest { +class JavaContainerBuilderHelperTest { private static final Correspondence SOURCE_FILE_OF = Correspondence.transforming(FileEntry::getSourceFile, "has sourceFile of"); @@ -69,10 +68,10 @@ private static FileEntriesLayer getLayerConfigurationByName( .get(); } - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Test - public void testExtraDirectoryLayerConfiguration() throws URISyntaxException, IOException { + void testExtraDirectoryLayerConfiguration() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); FileEntriesLayer layerConfiguration = JavaContainerBuilderHelper.extraDirectoryLayerConfiguration( @@ -94,8 +93,7 @@ public void testExtraDirectoryLayerConfiguration() throws URISyntaxException, IO } @Test - public void testExtraDirectoryLayerConfiguration_includes() - throws URISyntaxException, IOException { + void testExtraDirectoryLayerConfiguration_includes() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); FileEntriesLayer layerConfiguration = JavaContainerBuilderHelper.extraDirectoryLayerConfiguration( @@ -112,8 +110,7 @@ public void testExtraDirectoryLayerConfiguration_includes() } @Test - public void testExtraDirectoryLayerConfiguration_excludes() - throws URISyntaxException, IOException { + void testExtraDirectoryLayerConfiguration_excludes() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); FileEntriesLayer layerConfiguration = JavaContainerBuilderHelper.extraDirectoryLayerConfiguration( @@ -133,7 +130,7 @@ public void testExtraDirectoryLayerConfiguration_excludes() } @Test - public void testExtraDirectoryLayerConfiguration_includesAndExcludesEverything() + void testExtraDirectoryLayerConfiguration_includesAndExcludesEverything() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); FileEntriesLayer layerConfiguration = @@ -148,7 +145,7 @@ public void testExtraDirectoryLayerConfiguration_includesAndExcludesEverything() } @Test - public void testExtraDirectoryLayerConfiguration_includesAndExcludes() + void testExtraDirectoryLayerConfiguration_includesAndExcludes() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); FileEntriesLayer layerConfiguration = @@ -165,7 +162,7 @@ public void testExtraDirectoryLayerConfiguration_includesAndExcludes() } @Test - public void testExtraDirectoryLayerConfiguration_globPermissions() + void testExtraDirectoryLayerConfiguration_globPermissions() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); Map permissionsMap = @@ -204,7 +201,7 @@ public void testExtraDirectoryLayerConfiguration_globPermissions() } @Test - public void testExtraDirectoryLayerConfiguration_overlappingPermissions() + void testExtraDirectoryLayerConfiguration_overlappingPermissions() throws URISyntaxException, IOException { Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI()); Map permissionsMap = @@ -245,14 +242,14 @@ public void testExtraDirectoryLayerConfiguration_overlappingPermissions() } @Test - public void testFromExplodedWar() + void testFromExplodedWar() throws URISyntaxException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { // Copy test files to a temporary directory that we can safely operate on Path resourceExplodedWar = Paths.get(Resources.getResource("plugins-common/exploded-war").toURI()); - FileOperations.copy(ImmutableList.of(resourceExplodedWar), temporaryFolder.getRoot().toPath()); - Path temporaryExplodedWar = temporaryFolder.getRoot().toPath().resolve("exploded-war"); + FileOperations.copy(ImmutableList.of(resourceExplodedWar), temporaryFolder); + Path temporaryExplodedWar = temporaryFolder.resolve("exploded-war"); Files.createDirectories(temporaryExplodedWar.resolve("WEB-INF/classes/empty_dir")); Files.createFile(temporaryExplodedWar.resolve("WEB-INF/lib/project-dependency-1.0.0.jar")); Set projectArtifacts = ImmutableSet.of("project-dependency-1.0.0.jar"); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JibBuildRunnerTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JibBuildRunnerTest.java index 4b41447b55c..cc730f3d862 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JibBuildRunnerTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/JibBuildRunnerTest.java @@ -29,6 +29,7 @@ import com.google.cloud.tools.jib.api.RegistryUnauthorizedException; import com.google.cloud.tools.jib.registry.RegistryCredentialsNotSentException; import com.google.common.collect.ImmutableSet; +import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; @@ -38,24 +39,26 @@ import java.util.concurrent.ExecutionException; import org.apache.http.conn.HttpHostConnectException; import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.io.TempDir; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link JibBuildRunner}. */ -@RunWith(MockitoJUnitRunner.class) -public class JibBuildRunnerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JibBuildRunnerTest { private static final HelpfulSuggestions TEST_HELPFUL_SUGGESTIONS = new HelpfulSuggestions( "messagePrefix", "clearCacheCommand", "toConfig", "toFlag", "buildFile"); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock private JibContainerBuilder mockJibContainerBuilder; @Mock private JibContainer mockJibContainer; @@ -66,8 +69,8 @@ public class JibBuildRunnerTest { private JibBuildRunner testJibBuildRunner; - @Before - public void setUpMocks() { + @BeforeEach + void setUpMocks() { testJibBuildRunner = new JibBuildRunner( mockJibContainerBuilder, @@ -79,14 +82,14 @@ public void setUpMocks() { } @Test - public void testBuildImage_pass() + void testBuildImage_pass() throws BuildStepsExecutionException, IOException, CacheDirectoryCreationException { JibContainer buildResult = testJibBuildRunner.runBuild(); Assert.assertNull(buildResult); } @Test - public void testBuildImage_httpHostConnectException() + void testBuildImage_httpHostConnectException() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { HttpHostConnectException mockHttpHostConnectException = @@ -105,7 +108,7 @@ public void testBuildImage_httpHostConnectException() } @Test - public void testBuildImage_unknownHostException() + void testBuildImage_unknownHostException() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { UnknownHostException mockUnknownHostException = Mockito.mock(UnknownHostException.class); @@ -123,7 +126,7 @@ public void testBuildImage_unknownHostException() } @Test - public void testBuildImage_insecureRegistryException() + void testBuildImage_insecureRegistryException() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { InsecureRegistryException mockInsecureRegistryException = @@ -142,7 +145,7 @@ public void testBuildImage_insecureRegistryException() } @Test - public void testBuildImage_registryUnauthorizedException_statusCodeForbidden() + void testBuildImage_registryUnauthorizedException_statusCodeForbidden() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { Mockito.when(mockRegistryUnauthorizedException.getHttpResponseException()) @@ -168,7 +171,7 @@ public void testBuildImage_registryUnauthorizedException_statusCodeForbidden() } @Test - public void testBuildImage_registryUnauthorizedException_noCredentials() + void testBuildImage_registryUnauthorizedException_noCredentials() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { Mockito.when(mockRegistryUnauthorizedException.getHttpResponseException()) @@ -193,7 +196,7 @@ public void testBuildImage_registryUnauthorizedException_noCredentials() } @Test - public void testBuildImage_registryCredentialsNotSentException() + void testBuildImage_registryCredentialsNotSentException() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { Mockito.doThrow(mockRegistryCredentialsNotSentException) @@ -210,7 +213,7 @@ public void testBuildImage_registryCredentialsNotSentException() } @Test - public void testBuildImage_other() + void testBuildImage_other() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { Mockito.doThrow(new RegistryException("messagePrefix")) @@ -227,14 +230,16 @@ public void testBuildImage_other() } @Test - public void testBuildImage_writesImageJson() throws Exception { + void testBuildImage_writesImageJson() throws Exception { final ImageReference targetImageReference = ImageReference.parse("gcr.io/distroless/java:11"); final String imageId = "sha256:61bb3ec31a47cb730eb58a38bbfa813761a51dca69d10e39c24c3d00a7b2c7a9"; final String digest = "sha256:3f1be7e19129edb202c071a659a4db35280ab2bb1a16f223bfd5d1948657b6fc"; final Set tags = ImmutableSet.of("latest", "0.1.41-69d10e-20200116T101403"); - final Path outputPath = temporaryFolder.newFile("jib-image.json").toPath(); + File f = new File(temporaryFolder.toFile(), "jib-image.json"); + f.createNewFile(); + final Path outputPath = f.toPath(); Mockito.when(mockJibContainer.getTargetImage()).thenReturn(targetImageReference); Mockito.when(mockJibContainer.getImageId()).thenReturn(DescriptorDigest.fromDigest(imageId)); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/MainClassResolverTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/MainClassResolverTest.java index c5134b099a6..cdd69dda8e3 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/MainClassResolverTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/MainClassResolverTest.java @@ -26,27 +26,30 @@ import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Assert; -import org.junit.Before; -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.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Test for {@link MainClassResolver}. */ -@RunWith(MockitoJUnitRunner.class) -public class MainClassResolverTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MainClassResolverTest { @Mock private ProjectProperties mockProjectProperties; - @Before - public void setup() { + @BeforeEach + void setupBefore() { Mockito.when(mockProjectProperties.getPluginName()).thenReturn("jib-plugin"); Mockito.when(mockProjectProperties.getJarPluginName()).thenReturn("jar-plugin"); } @Test - public void testResolveMainClass_validMainClassConfigured() + void testResolveMainClass_validMainClassConfigured() throws MainClassInferenceException, IOException { Assert.assertEquals( "configured.main.class", @@ -55,7 +58,7 @@ public void testResolveMainClass_validMainClassConfigured() } @Test - public void testResolveMainClass_invalidMainClassConfigured() throws IOException { + void testResolveMainClass_invalidMainClassConfigured() throws IOException { try { MainClassResolver.resolveMainClass("In Val id", mockProjectProperties); Assert.fail(); @@ -71,7 +74,7 @@ public void testResolveMainClass_invalidMainClassConfigured() throws IOException } @Test - public void testResolveMainClass_validMainClassFromJarPlugin() + void testResolveMainClass_validMainClassFromJarPlugin() throws MainClassInferenceException, IOException { Mockito.when(mockProjectProperties.getMainClassFromJarPlugin()) .thenReturn("main.class.from.jar"); @@ -85,7 +88,7 @@ public void testResolveMainClass_validMainClassFromJarPlugin() } @Test - public void testResolveMainClass_multipleInferredWithInvalidMainClassFromJarPlugin() + void testResolveMainClass_multipleInferredWithInvalidMainClassFromJarPlugin() throws URISyntaxException, IOException { Mockito.when(mockProjectProperties.getMainClassFromJarPlugin()).thenReturn("${start-class}"); Mockito.when(mockProjectProperties.getClassFiles()) @@ -119,7 +122,7 @@ public void testResolveMainClass_multipleInferredWithInvalidMainClassFromJarPlug } @Test - public void testResolveMainClass_multipleInferredWithoutMainClassFromJarPlugin() + void testResolveMainClass_multipleInferredWithoutMainClassFromJarPlugin() throws URISyntaxException, IOException { Mockito.when(mockProjectProperties.getClassFiles()) .thenReturn( @@ -148,8 +151,7 @@ public void testResolveMainClass_multipleInferredWithoutMainClassFromJarPlugin() } @Test - public void testResolveMainClass_noneInferredWithInvalidMainClassFromJarPlugin() - throws IOException { + void testResolveMainClass_noneInferredWithInvalidMainClassFromJarPlugin() throws IOException { Mockito.when(mockProjectProperties.getMainClassFromJarPlugin()).thenReturn("${start-class}"); Mockito.when(mockProjectProperties.getClassFiles()) .thenReturn(ImmutableList.of(Paths.get("ignored"))); @@ -176,7 +178,7 @@ public void testResolveMainClass_noneInferredWithInvalidMainClassFromJarPlugin() } @Test - public void testResolveMainClass_noneInferredWithoutMainClassFromJar() throws IOException { + void testResolveMainClass_noneInferredWithoutMainClassFromJar() throws IOException { Mockito.when(mockProjectProperties.getClassFiles()) .thenReturn(ImmutableList.of(Paths.get("ignored"))); try { @@ -199,7 +201,7 @@ public void testResolveMainClass_noneInferredWithoutMainClassFromJar() throws IO } @Test - public void testValidJavaClassRegex() { + void testValidJavaClassRegex() { Assert.assertTrue(MainClassResolver.isValidJavaClass("my.Class")); Assert.assertTrue(MainClassResolver.isValidJavaClass("my.java_Class$valid")); Assert.assertTrue(MainClassResolver.isValidJavaClass("multiple.package.items")); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/PluginConfigurationProcessorTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/PluginConfigurationProcessorTest.java index 7fd608667c2..29b0daf44cd 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/PluginConfigurationProcessorTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/PluginConfigurationProcessorTest.java @@ -67,24 +67,28 @@ import java.util.Optional; import java.util.function.Consumer; import javax.annotation.Nullable; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.rules.TemporaryFolder; -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.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Answers; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link PluginConfigurationProcessor}. */ -@RunWith(JUnitParamsRunner.class) -public class PluginConfigurationProcessorTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class PluginConfigurationProcessorTest { private static class TestPlatformConfiguration implements PlatformConfiguration { @Nullable private final String os; @@ -153,7 +157,7 @@ private static List getLayerEntries(ContainerBuildPlan buildPlan, Str @Rule public final MockitoRule mockitoRule = MockitoJUnit.rule().silent(); @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; @Mock(answer = Answers.RETURNS_SELF) private Containerizer containerizer; @@ -169,8 +173,8 @@ private static List getLayerEntries(ContainerBuildPlan buildPlan, Str private Path appCacheDirectory; private final JibContainerBuilder jibContainerBuilder = Jib.fromScratch(); - @Before - public void setUp() throws IOException, InvalidImageReferenceException, InferredAuthException { + @BeforeEach + void setUpBeforeEach() throws IOException, InvalidImageReferenceException, InferredAuthException { when(rawConfiguration.getFromAuth()).thenReturn(authProperty); when(rawConfiguration.getEntrypoint()).thenReturn(Optional.empty()); when(rawConfiguration.getAppRoot()).thenReturn("/app"); @@ -192,14 +196,16 @@ public void setUp() throws IOException, InvalidImageReferenceException, Inferred when(projectProperties.getDependencies()) .thenReturn(Arrays.asList(Paths.get("/repo/foo-1.jar"), Paths.get("/home/libs/bar-2.jar"))); - appCacheDirectory = temporaryFolder.newFolder("jib-cache").toPath(); + File f = new File(temporaryFolder.toFile(), "jib-cache"); + f.mkdirs(); + appCacheDirectory = f.toPath(); when(projectProperties.getDefaultCacheDirectory()).thenReturn(appCacheDirectory); when(inferredAuthProvider.inferAuth(any())).thenReturn(Optional.empty()); } @Test - public void testPluginConfigurationProcessor_defaults() + void testPluginConfigurationProcessor_defaults() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -221,7 +227,7 @@ public void testPluginConfigurationProcessor_defaults() } @Test - public void testPluginConfigurationProcessor_extraDirectory() + void testPluginConfigurationProcessor_extraDirectory() throws URISyntaxException, InvalidContainerVolumeException, MainClassInferenceException, InvalidAppRootException, IOException, IncompatibleBaseImageJavaVersionException, InvalidWorkingDirectoryException, InvalidPlatformException, @@ -267,7 +273,7 @@ public void testPluginConfigurationProcessor_extraDirectory() } @Test - public void testPluginConfigurationProcessor__errorOnExtraDirectoryPathNotFound() + void testPluginConfigurationProcessor__errorOnExtraDirectoryPathNotFound() throws URISyntaxException, NumberFormatException { Path extraDirectory = Paths.get(Resources.getResource("core/layer").toURI()).resolve("xyz"); Mockito.>when(rawConfiguration.getExtraDirectories()) @@ -279,7 +285,7 @@ public void testPluginConfigurationProcessor__errorOnExtraDirectoryPathNotFound( } @Test - public void testPluginConfigurationProcessor_cacheDirectorySystemProperties() + void testPluginConfigurationProcessor_cacheDirectorySystemProperties() throws InvalidContainerVolumeException, MainClassInferenceException, InvalidAppRootException, IOException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidImageReferenceException, IncompatibleBaseImageJavaVersionException, @@ -296,7 +302,7 @@ public void testPluginConfigurationProcessor_cacheDirectorySystemProperties() } @Test - public void testAddJvmArgFilesLayer() throws IOException, InvalidAppRootException { + void testAddJvmArgFilesLayer() throws IOException, InvalidAppRootException { String classpath = "/extra:/app/classes:/app/libs/dep.jar"; String mainClass = "com.example.Main"; PluginConfigurationProcessor.addJvmArgFilesLayer( @@ -322,8 +328,8 @@ public void testAddJvmArgFilesLayer() throws IOException, InvalidAppRootExceptio } @Test - public void testWriteFileConservatively() throws IOException { - Path file = temporaryFolder.getRoot().toPath().resolve("file.txt"); + void testWriteFileConservatively() throws IOException { + Path file = temporaryFolder.resolve("file.txt"); PluginConfigurationProcessor.writeFileConservatively(file, "some content"); @@ -332,8 +338,9 @@ public void testWriteFileConservatively() throws IOException { } @Test - public void testWriteFileConservatively_updatedContent() throws IOException { - Path file = temporaryFolder.newFile().toPath(); + void testWriteFileConservatively_updatedContent() throws IOException { + + Path file = Files.createTempFile(temporaryFolder, "jib", "test"); PluginConfigurationProcessor.writeFileConservatively(file, "some content"); @@ -342,8 +349,8 @@ public void testWriteFileConservatively_updatedContent() throws IOException { } @Test - public void testWriteFileConservatively_noWriteIfUnchanged() throws IOException { - Path file = temporaryFolder.newFile().toPath(); + void testWriteFileConservatively_noWriteIfUnchanged() throws IOException { + Path file = Files.createTempFile(temporaryFolder, "jib", "test"); Files.write(file, "some content".getBytes(StandardCharsets.UTF_8)); FileTime fileTime = Files.getLastModifiedTime(file); @@ -355,7 +362,7 @@ public void testWriteFileConservatively_noWriteIfUnchanged() throws IOException } @Test - public void testEntrypoint() + void testEntrypoint() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -372,7 +379,7 @@ public void testEntrypoint() } @Test - public void testComputeEntrypoint_inheritKeyword() + void testComputeEntrypoint_inheritKeyword() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { when(rawConfiguration.getEntrypoint()) @@ -385,7 +392,7 @@ public void testComputeEntrypoint_inheritKeyword() } @Test - public void testComputeEntrypoint_inheritKeywordInNonSingletonList() + void testComputeEntrypoint_inheritKeywordInNonSingletonList() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { when(rawConfiguration.getEntrypoint()).thenReturn(Optional.of(Arrays.asList("INHERIT", ""))); @@ -397,7 +404,7 @@ public void testComputeEntrypoint_inheritKeywordInNonSingletonList() } @Test - public void testComputeEntrypoint_default() + void testComputeEntrypoint_default() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { assertThat( @@ -409,7 +416,7 @@ public void testComputeEntrypoint_default() } @Test - public void testComputeEntrypoint_packaged() + void testComputeEntrypoint_packaged() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { when(rawConfiguration.getContainerizingMode()).thenReturn("packaged"); @@ -421,7 +428,7 @@ public void testComputeEntrypoint_packaged() } @Test - public void testComputeEntrypoint_expandClasspathDependencies() + void testComputeEntrypoint_expandClasspathDependencies() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { when(rawConfiguration.getExpandClasspathDependencies()).thenReturn(true); @@ -436,12 +443,16 @@ public void testComputeEntrypoint_expandClasspathDependencies() .inOrder(); } + @TempDir Path libFoo13Tmp; + @TempDir Path libFoo45Tmp; + @Test - public void testComputeEntrypoint_expandClasspathDependencies_sizeAddedForDuplicateJars() + void testComputeEntrypoint_expandClasspathDependencies_sizeAddedForDuplicateJars() throws MainClassInferenceException, InvalidAppRootException, IOException, InvalidContainerizingModeException { - Path libFoo13 = temporaryFolder.newFolder().toPath().resolve("foo-1.jar"); - Path libFoo45 = temporaryFolder.newFolder().toPath().resolve("foo-1.jar"); + + Path libFoo13 = libFoo13Tmp.resolve("foo-1.jar"); + Path libFoo45 = libFoo45Tmp.resolve("foo-1.jar"); Files.write(libFoo13, new byte[13]); Files.write(libFoo45, new byte[45]); @@ -462,7 +473,7 @@ public void testComputeEntrypoint_expandClasspathDependencies_sizeAddedForDuplic } @Test - public void testEntrypoint_defaultWarPackaging() + void testEntrypoint_defaultWarPackaging() throws IOException, InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -480,7 +491,7 @@ public void testEntrypoint_defaultWarPackaging() } @Test - public void testEntrypoint_defaultNonWarPackaging() + void testEntrypoint_defaultNonWarPackaging() throws IOException, InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -501,7 +512,7 @@ public void testEntrypoint_defaultNonWarPackaging() } @Test - public void testEntrypoint_extraClasspathNonWarPackaging() + void testEntrypoint_extraClasspathNonWarPackaging() throws IOException, InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -523,7 +534,7 @@ public void testEntrypoint_extraClasspathNonWarPackaging() } @Test - public void testClasspathArgumentFile() + void testClasspathArgumentFile() throws NumberFormatException, InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, IOException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, @@ -563,7 +574,7 @@ public void testClasspathArgumentFile() } @Test - public void testClasspathArgumentFile_mainClassInferenceFailureWithCustomEntrypoint() + void testClasspathArgumentFile_mainClassInferenceFailureWithCustomEntrypoint() throws NumberFormatException, InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, IOException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, @@ -600,7 +611,7 @@ public void testClasspathArgumentFile_mainClassInferenceFailureWithCustomEntrypo } @Test - public void testUser() + void testUser() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -614,7 +625,7 @@ public void testUser() } @Test - public void testUser_null() + void testUser_null() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -626,7 +637,7 @@ public void testUser_null() } @Test - public void testEntrypoint_warningOnJvmFlags() + void testEntrypoint_warningOnJvmFlags() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -648,7 +659,7 @@ public void testEntrypoint_warningOnJvmFlags() } @Test - public void testEntrypoint_warningOnMainclass() + void testEntrypoint_warningOnMainclass() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -670,7 +681,7 @@ public void testEntrypoint_warningOnMainclass() } @Test - public void testEntrypoint_warningOnExpandClasspathDependencies() + void testEntrypoint_warningOnExpandClasspathDependencies() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -692,7 +703,7 @@ public void testEntrypoint_warningOnExpandClasspathDependencies() } @Test - public void testEntrypoint_warningOnMainclassForWar() + void testEntrypoint_warningOnMainclassForWar() throws IOException, InvalidCreationTimeException, InvalidImageReferenceException, IncompatibleBaseImageJavaVersionException, InvalidPlatformException, InvalidContainerVolumeException, MainClassInferenceException, InvalidAppRootException, @@ -714,7 +725,7 @@ public void testEntrypoint_warningOnMainclassForWar() } @Test - public void testEntrypoint_warningOnExpandClasspathDependenciesForWar() + void testEntrypoint_warningOnExpandClasspathDependenciesForWar() throws IOException, InvalidCreationTimeException, InvalidImageReferenceException, IncompatibleBaseImageJavaVersionException, InvalidPlatformException, InvalidContainerVolumeException, MainClassInferenceException, InvalidAppRootException, @@ -736,7 +747,7 @@ public void testEntrypoint_warningOnExpandClasspathDependenciesForWar() } @Test - public void testEntrypointClasspath_nonDefaultAppRoot() + void testEntrypointClasspath_nonDefaultAppRoot() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -754,7 +765,7 @@ public void testEntrypointClasspath_nonDefaultAppRoot() } @Test - public void testWebAppEntrypoint_inheritedFromCustomBaseImage() + void testWebAppEntrypoint_inheritedFromCustomBaseImage() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, @@ -770,29 +781,21 @@ public void testWebAppEntrypoint_inheritedFromCustomBaseImage() } @Test - public void testGetAppRootChecked() throws InvalidAppRootException { + void testGetAppRootChecked() throws InvalidAppRootException { when(rawConfiguration.getAppRoot()).thenReturn("/some/root"); assertThat(PluginConfigurationProcessor.getAppRootChecked(rawConfiguration, projectProperties)) .isEqualTo(AbsoluteUnixPath.get("/some/root")); } - @Test - public void testGetAppRootChecked_errorOnNonAbsolutePath() { - when(rawConfiguration.getAppRoot()).thenReturn("relative/path"); - - Exception exception = - assertThrows( - InvalidAppRootException.class, - () -> - PluginConfigurationProcessor.getAppRootChecked( - rawConfiguration, projectProperties)); - assertThat(exception).hasMessageThat().isEqualTo("relative/path"); - } - - @Test - public void testGetAppRootChecked_errorOnWindowsPath() { - when(rawConfiguration.getAppRoot()).thenReturn("\\windows\\path"); + @ParameterizedTest + @CsvSource({ + "relative/path", // non absolute + "\\windows\\path", // windows + "C:\\windows\\path" // windows with driver letter + }) + void testGetAppRootChecked_errorOnNonAbsolutePath(String path) { + when(rawConfiguration.getAppRoot()).thenReturn(path); Exception exception = assertThrows( @@ -800,24 +803,11 @@ public void testGetAppRootChecked_errorOnWindowsPath() { () -> PluginConfigurationProcessor.getAppRootChecked( rawConfiguration, projectProperties)); - assertThat(exception).hasMessageThat().isEqualTo("\\windows\\path"); + assertThat(exception).hasMessageThat().isEqualTo(path); } @Test - public void testGetAppRootChecked_errorOnWindowsPathWithDriveLetter() { - when(rawConfiguration.getAppRoot()).thenReturn("C:\\windows\\path"); - - Exception exception = - assertThrows( - InvalidAppRootException.class, - () -> - PluginConfigurationProcessor.getAppRootChecked( - rawConfiguration, projectProperties)); - assertThat(exception).hasMessageThat().isEqualTo("C:\\windows\\path"); - } - - @Test - public void testGetAppRootChecked_defaultNonWarProject() throws InvalidAppRootException { + void testGetAppRootChecked_defaultNonWarProject() throws InvalidAppRootException { when(rawConfiguration.getAppRoot()).thenReturn(""); when(projectProperties.isWarProject()).thenReturn(false); @@ -826,7 +816,7 @@ public void testGetAppRootChecked_defaultNonWarProject() throws InvalidAppRootEx } @Test - public void testGetAppRootChecked_defaultWarProject() throws InvalidAppRootException { + void testGetAppRootChecked_defaultWarProject() throws InvalidAppRootException { when(rawConfiguration.getAppRoot()).thenReturn(""); when(projectProperties.isWarProject()).thenReturn(true); @@ -835,7 +825,7 @@ public void testGetAppRootChecked_defaultWarProject() throws InvalidAppRootExcep } @Test - public void testGetContainerizingModeChecked_packagedWithWar() { + void testGetContainerizingModeChecked_packagedWithWar() { when(rawConfiguration.getContainerizingMode()).thenReturn("packaged"); when(projectProperties.isWarProject()).thenReturn(true); @@ -851,7 +841,7 @@ public void testGetContainerizingModeChecked_packagedWithWar() { } @Test - public void testGetWorkingDirectoryChecked() throws InvalidWorkingDirectoryException { + void testGetWorkingDirectoryChecked() throws InvalidWorkingDirectoryException { when(rawConfiguration.getWorkingDirectory()).thenReturn(Optional.of("/valid/path")); Optional checkedPath = @@ -860,13 +850,13 @@ public void testGetWorkingDirectoryChecked() throws InvalidWorkingDirectoryExcep } @Test - public void testGetWorkingDirectoryChecked_undefined() throws InvalidWorkingDirectoryException { + void testGetWorkingDirectoryChecked_undefined() throws InvalidWorkingDirectoryException { when(rawConfiguration.getWorkingDirectory()).thenReturn(Optional.empty()); assertThat(PluginConfigurationProcessor.getWorkingDirectoryChecked(rawConfiguration)).isEmpty(); } @Test - public void testGetWorkingDirectoryChecked_notAbsolute() { + void testGetWorkingDirectoryChecked_notAbsolute() { when(rawConfiguration.getWorkingDirectory()).thenReturn(Optional.of("relative/path")); InvalidWorkingDirectoryException exception = @@ -878,8 +868,7 @@ public void testGetWorkingDirectoryChecked_notAbsolute() { } @Test - public void testGetDefaultBaseImage_nonWarPackaging() - throws IncompatibleBaseImageJavaVersionException { + void testGetDefaultBaseImage_nonWarPackaging() throws IncompatibleBaseImageJavaVersionException { when(projectProperties.isWarProject()).thenReturn(false); assertThat(PluginConfigurationProcessor.getDefaultBaseImage(projectProperties)) @@ -887,16 +876,15 @@ public void testGetDefaultBaseImage_nonWarPackaging() } @Test - public void testGetDefaultBaseImage_warProject() - throws IncompatibleBaseImageJavaVersionException { + void testGetDefaultBaseImage_warProject() throws IncompatibleBaseImageJavaVersionException { when(projectProperties.isWarProject()).thenReturn(true); assertThat(PluginConfigurationProcessor.getDefaultBaseImage(projectProperties)) .isEqualTo("jetty"); } - @Test - @Parameters( + @ParameterizedTest + @CsvSource( value = { "6, eclipse-temurin:8-jre", "8, eclipse-temurin:8-jre", @@ -905,15 +893,15 @@ public void testGetDefaultBaseImage_warProject() "13, eclipse-temurin:17-jre", "17, eclipse-temurin:17-jre" }) - public void testGetDefaultBaseImage_defaultJavaBaseImage( - int javaVersion, String expectedBaseImage) throws IncompatibleBaseImageJavaVersionException { + void testGetDefaultBaseImage_defaultJavaBaseImage(int javaVersion, String expectedBaseImage) + throws IncompatibleBaseImageJavaVersionException { when(projectProperties.getMajorJavaVersion()).thenReturn(javaVersion); assertThat(PluginConfigurationProcessor.getDefaultBaseImage(projectProperties)) .isEqualTo(expectedBaseImage); } @Test - public void testGetDefaultBaseImage_projectHigherThanJava17() { + void testGetDefaultBaseImage_projectHigherThanJava17() { when(projectProperties.getMajorJavaVersion()).thenReturn(20); IncompatibleBaseImageJavaVersionException exception = @@ -926,7 +914,7 @@ public void testGetDefaultBaseImage_projectHigherThanJava17() { } @Test - public void testGetJavaContainerBuilderWithBaseImage_dockerBase() + void testGetJavaContainerBuilderWithBaseImage_dockerBase() throws IncompatibleBaseImageJavaVersionException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { when(rawConfiguration.getFromImage()).thenReturn(Optional.of("docker://ima.ge/name")); @@ -937,7 +925,7 @@ public void testGetJavaContainerBuilderWithBaseImage_dockerBase() } @Test - public void testGetJavaContainerBuilderWithBaseImage_tarBase() + void testGetJavaContainerBuilderWithBaseImage_tarBase() throws IncompatibleBaseImageJavaVersionException, IOException, InvalidImageReferenceException, CacheDirectoryCreationException { when(rawConfiguration.getFromImage()).thenReturn(Optional.of("tar:///path/to.tar")); @@ -947,7 +935,7 @@ public void testGetJavaContainerBuilderWithBaseImage_tarBase() } @Test - public void testGetJavaContainerBuilderWithBaseImage_registry() + void testGetJavaContainerBuilderWithBaseImage_registry() throws IncompatibleBaseImageJavaVersionException, InvalidImageReferenceException, IOException, CacheDirectoryCreationException { when(rawConfiguration.getFromImage()).thenReturn(Optional.of("ima.ge/name")); @@ -958,7 +946,7 @@ public void testGetJavaContainerBuilderWithBaseImage_registry() } @Test - public void testGetJavaContainerBuilderWithBaseImage_registryWithPrefix() + void testGetJavaContainerBuilderWithBaseImage_registryWithPrefix() throws IncompatibleBaseImageJavaVersionException, InvalidImageReferenceException, IOException, CacheDirectoryCreationException { when(rawConfiguration.getFromImage()).thenReturn(Optional.of("registry://ima.ge/name")); @@ -968,8 +956,8 @@ public void testGetJavaContainerBuilderWithBaseImage_registryWithPrefix() assertThat(result.getTarPath()).isEmpty(); } - @Test - @Parameters( + @ParameterizedTest + @CsvSource( value = { "adoptopenjdk:8, 8, 11", "adoptopenjdk:8-jre, 8, 11", @@ -982,7 +970,7 @@ public void testGetJavaContainerBuilderWithBaseImage_registryWithPrefix() "eclipse-temurin:17, 17, 19", "eclipse-temurin:17-jre, 17, 19" }) - public void testGetJavaContainerBuilderWithBaseImage_incompatibleJavaBaseImage( + void testGetJavaContainerBuilderWithBaseImage_incompatibleJavaBaseImage( String baseImage, int baseImageJavaVersion, int appJavaVersion) { when(projectProperties.getMajorJavaVersion()).thenReturn(appJavaVersion); @@ -999,7 +987,7 @@ public void testGetJavaContainerBuilderWithBaseImage_incompatibleJavaBaseImage( // https://github.com/GoogleContainerTools/jib/issues/1995 @Test - public void testGetJavaContainerBuilderWithBaseImage_java12BaseImage() + void testGetJavaContainerBuilderWithBaseImage_java12BaseImage() throws InvalidImageReferenceException, IOException, IncompatibleBaseImageJavaVersionException, CacheDirectoryCreationException { when(projectProperties.getMajorJavaVersion()).thenReturn(12); @@ -1010,7 +998,7 @@ public void testGetJavaContainerBuilderWithBaseImage_java12BaseImage() } @Test - public void testGetJavaContainerBuilderWithBaseImage_java19NoBaseImage() { + void testGetJavaContainerBuilderWithBaseImage_java19NoBaseImage() { when(projectProperties.getMajorJavaVersion()).thenReturn(19); when(rawConfiguration.getFromImage()).thenReturn(Optional.empty()); IncompatibleBaseImageJavaVersionException exception = @@ -1024,7 +1012,7 @@ public void testGetJavaContainerBuilderWithBaseImage_java19NoBaseImage() { } @Test - public void testGetPlatformsSet() throws InvalidPlatformException { + void testGetPlatformsSet() throws InvalidPlatformException { Mockito.>when(rawConfiguration.getPlatforms()) .thenReturn(Arrays.asList(new TestPlatformConfiguration("testArchitecture", "testOs"))); @@ -1033,7 +1021,7 @@ public void testGetPlatformsSet() throws InvalidPlatformException { } @Test - public void testGetPlatformsSet_architectureMissing() { + void testGetPlatformsSet_architectureMissing() { TestPlatformConfiguration platform = new TestPlatformConfiguration(null, "testOs"); Mockito.>when(rawConfiguration.getPlatforms()).thenReturn(Arrays.asList(platform)); @@ -1048,7 +1036,7 @@ public void testGetPlatformsSet_architectureMissing() { } @Test - public void testGetPlatformsSet_osMissing() { + void testGetPlatformsSet_osMissing() { TestPlatformConfiguration platform = new TestPlatformConfiguration("testArchitecture", null); Mockito.>when(rawConfiguration.getPlatforms()).thenReturn(Arrays.asList(platform)); @@ -1064,7 +1052,7 @@ public void testGetPlatformsSet_osMissing() { } @Test - public void testGetValidVolumesList() throws InvalidContainerVolumeException { + void testGetValidVolumesList() throws InvalidContainerVolumeException { when(rawConfiguration.getVolumes()).thenReturn(Collections.singletonList("/some/root")); assertThat(PluginConfigurationProcessor.getVolumesSet(rawConfiguration)) @@ -1072,7 +1060,7 @@ public void testGetValidVolumesList() throws InvalidContainerVolumeException { } @Test - public void testGetInvalidVolumesList() { + void testGetInvalidVolumesList() { when(rawConfiguration.getVolumes()).thenReturn(Collections.singletonList("`some/root")); InvalidContainerVolumeException exception = @@ -1084,7 +1072,7 @@ public void testGetInvalidVolumesList() { } @Test - public void testCreateModificationTimeProvider_epochPlusSecond() + void testCreateModificationTimeProvider_epochPlusSecond() throws InvalidFilesModificationTimeException { ModificationTimeProvider timeProvider = PluginConfigurationProcessor.createModificationTimeProvider("EPOCH_PLUS_SECOND"); @@ -1093,7 +1081,7 @@ public void testCreateModificationTimeProvider_epochPlusSecond() } @Test - public void testCreateModificationTimeProvider_isoDateTimeValue() + void testCreateModificationTimeProvider_isoDateTimeValue() throws InvalidFilesModificationTimeException { ModificationTimeProvider timeProvider = PluginConfigurationProcessor.createModificationTimeProvider("2011-12-03T10:15:30+09:00"); @@ -1103,7 +1091,7 @@ public void testCreateModificationTimeProvider_isoDateTimeValue() } @Test - public void testCreateModificationTimeProvider_invalidValue() { + void testCreateModificationTimeProvider_invalidValue() { InvalidFilesModificationTimeException exception = assertThrows( InvalidFilesModificationTimeException.class, @@ -1113,13 +1101,13 @@ public void testCreateModificationTimeProvider_invalidValue() { } @Test - public void testGetCreationTime_epoch() throws InvalidCreationTimeException { + void testGetCreationTime_epoch() throws InvalidCreationTimeException { Instant time = PluginConfigurationProcessor.getCreationTime("EPOCH", projectProperties); assertThat(time).isEqualTo(Instant.EPOCH); } @Test - public void testGetCreationTime_useCurrentTimestamp() throws InvalidCreationTimeException { + void testGetCreationTime_useCurrentTimestamp() throws InvalidCreationTimeException { Instant now = Instant.now().minusSeconds(2); Instant time = PluginConfigurationProcessor.getCreationTime("USE_CURRENT_TIMESTAMP", projectProperties); @@ -1127,7 +1115,7 @@ public void testGetCreationTime_useCurrentTimestamp() throws InvalidCreationTime } @Test - public void testGetCreationTime_isoDateTimeValue() throws InvalidCreationTimeException { + void testGetCreationTime_isoDateTimeValue() throws InvalidCreationTimeException { Instant expected = DateTimeFormatter.ISO_DATE_TIME.parse("2011-12-03T01:15:30Z", Instant::from); List validTimeStamps = ImmutableList.of( @@ -1146,7 +1134,7 @@ public void testGetCreationTime_isoDateTimeValue() throws InvalidCreationTimeExc } @Test - public void testGetCreationTime_isoDateTimeValueTimeZoneRegionOnlyAllowedForMostStrict8601Mode() { + void testGetCreationTime_isoDateTimeValueTimeZoneRegionOnlyAllowedForMostStrict8601Mode() { List invalidTimeStamps = ImmutableList.of( "2011-12-03T01:15:30+0900[Asia/Tokyo]", "2011-12-03T01:15:30+09[Asia/Tokyo]"); @@ -1161,7 +1149,7 @@ public void testGetCreationTime_isoDateTimeValueTimeZoneRegionOnlyAllowedForMost } @Test - public void testGetCreationTime_isoDateTimeValueRequiresTimeZone() { + void testGetCreationTime_isoDateTimeValueRequiresTimeZone() { // getCreationTime should fail if timezone not specified. // this is the expected behavior, not specifically designed like this for any reason, feel // free to change this behavior and update the test @@ -1172,7 +1160,7 @@ public void testGetCreationTime_isoDateTimeValueRequiresTimeZone() { } @Test - public void testGetCreationTime_invalidValue() { + void testGetCreationTime_invalidValue() { InvalidCreationTimeException exception = assertThrows( InvalidCreationTimeException.class, @@ -1188,7 +1176,7 @@ private ImageConfiguration getCommonImageConfiguration() JibContainerBuilder containerBuilder = PluginConfigurationProcessor.getJavaContainerBuilderWithBaseImage( rawConfiguration, projectProperties, inferredAuthProvider) - .addClasses(temporaryFolder.getRoot().toPath()) + .addClasses(temporaryFolder) .toContainerBuilder(); return JibContainerBuilderTestHelper.toBuildContext( containerBuilder, Containerizer.to(RegistryImage.named("ignored"))) @@ -1209,10 +1197,14 @@ private ContainerBuildPlan processCommonConfiguration() } @Test - public void getAllFiles_expandsDirectories() throws IOException { - File rootFile = temporaryFolder.newFile("file"); - File folder = temporaryFolder.newFolder("folder"); - File folderFile = temporaryFolder.newFile("folder/file2"); + void getAllFiles_expandsDirectories() throws IOException { + File rootFile = new File(temporaryFolder.toFile(), "file"); + rootFile.createNewFile(); + + File folder = new File(temporaryFolder.toFile(), "folder"); + folder.mkdir(); + File folderFile = new File(temporaryFolder.toFile(), "folder/file2"); + folderFile.createNewFile(); assertThat( PluginConfigurationProcessor.getAllFiles( ImmutableSet.of(rootFile.toPath(), folder.toPath()))) @@ -1220,7 +1212,7 @@ public void getAllFiles_expandsDirectories() throws IOException { } @Test - public void getAllFiles_doesntBreakForNonExistentFiles() throws IOException { + void getAllFiles_doesntBreakForNonExistentFiles() throws IOException { Path testPath = Paths.get("/a/file/that/doesnt/exist"); assertThat(Files.exists(testPath)).isFalse(); assertThat(PluginConfigurationProcessor.getAllFiles(ImmutableSet.of(testPath))).isEmpty(); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutputTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutputTest.java index e25d2070f2d..b2dd00edcdd 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutputTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldFilesOutputTest.java @@ -20,35 +20,35 @@ import java.io.IOException; import java.nio.file.Paths; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link SkaffoldFilesOutput}. */ -public class SkaffoldFilesOutputTest { +class SkaffoldFilesOutputTest { private static final String TEST_JSON = "{\"build\":[\"buildFile1\",\"buildFile2\"],\"inputs\":[\"input1\",\"input2\"],\"ignore\":[\"ignore1\",\"ignore2\"]}"; @Test - public void testGetJsonString() throws IOException { + void testGetJsonString() throws IOException { SkaffoldFilesOutput skaffoldFilesOutput = new SkaffoldFilesOutput(); skaffoldFilesOutput.addBuild(Paths.get("buildFile1")); - skaffoldFilesOutput.addBuild(Paths.get("buildFile2")); + skaffoldFilesOutput.addBuild(Paths.get("buildFile2").toFile()); skaffoldFilesOutput.addInput(Paths.get("input1")); - skaffoldFilesOutput.addInput(Paths.get("input2")); + skaffoldFilesOutput.addInput(Paths.get("input2").toFile()); skaffoldFilesOutput.addIgnore(Paths.get("ignore1")); - skaffoldFilesOutput.addIgnore(Paths.get("ignore2")); + skaffoldFilesOutput.addIgnore(Paths.get("ignore2").toFile()); Assert.assertEquals(TEST_JSON, skaffoldFilesOutput.getJsonString()); } @Test - public void testGetJsonString_empty() throws IOException { + void testGetJsonString_empty() throws IOException { SkaffoldFilesOutput skaffoldFilesOutput = new SkaffoldFilesOutput(); Assert.assertEquals( "{\"build\":[],\"inputs\":[],\"ignore\":[]}", skaffoldFilesOutput.getJsonString()); } @Test - public void testConstructor_json() throws IOException { + void testConstructor_json() throws IOException { SkaffoldFilesOutput skaffoldFilesOutput = new SkaffoldFilesOutput(TEST_JSON); Assert.assertEquals( ImmutableList.of("buildFile1", "buildFile2"), skaffoldFilesOutput.getBuild()); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldSyncMapTemplateTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldSyncMapTemplateTest.java index ead776d982d..89a2de61784 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldSyncMapTemplateTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/SkaffoldSyncMapTemplateTest.java @@ -26,10 +26,10 @@ import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link SkaffoldFilesOutput}. */ -public class SkaffoldSyncMapTemplateTest { +class SkaffoldSyncMapTemplateTest { private static final Path GEN_SRC = Paths.get("/gen/src/").toAbsolutePath(); private static final Path DIR_SRC_1 = Paths.get("/dir/src/").toAbsolutePath(); @@ -80,7 +80,7 @@ private static String getPathForJson(Path path) { } @Test - public void testFrom_badPropertyName() throws IOException { + void testFrom_badPropertyName() throws IOException { try { SkaffoldSyncMapTemplate.from(FAIL_TEST_JSON_BAD_PROPERTY_NAME); Assert.fail(); @@ -90,7 +90,7 @@ public void testFrom_badPropertyName() throws IOException { } @Test - public void testFrom_missingField() throws IOException { + void testFrom_missingField() throws IOException { try { SkaffoldSyncMapTemplate.from(FAIL_TEST_JSON_MISSING_FIELD); Assert.fail(); @@ -100,7 +100,7 @@ public void testFrom_missingField() throws IOException { } @Test - public void testFrom_validEmpty() throws Exception { + void testFrom_validEmpty() throws Exception { SkaffoldSyncMapTemplate templateEmptyGenerated = SkaffoldSyncMapTemplate.from(TEST_JSON_EMPTY_GENERATED); SkaffoldSyncMapTemplate templateNoGenerated = @@ -110,7 +110,7 @@ public void testFrom_validEmpty() throws Exception { } @Test - public void testGetJsonString() throws IOException { + void testGetJsonString() throws IOException { SkaffoldSyncMapTemplate ssmt = new SkaffoldSyncMapTemplate(); ssmt.addGenerated( new FileEntry( @@ -134,7 +134,7 @@ public void testGetJsonString() throws IOException { } @Test - public void testGetJsonString_emptyGenerated() throws IOException { + void testGetJsonString_emptyGenerated() throws IOException { SkaffoldSyncMapTemplate ssmt = new SkaffoldSyncMapTemplate(); ssmt.addDirect( new FileEntry( diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/TimerEventHandlerTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/TimerEventHandlerTest.java index a2062bbd7e1..cf25349b414 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/TimerEventHandlerTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/TimerEventHandlerTest.java @@ -23,17 +23,17 @@ import java.util.Deque; import java.util.Optional; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link TimerEventHandler}. */ -public class TimerEventHandlerTest { +class TimerEventHandlerTest { private final Deque logMessageQueue = new ArrayDeque<>(); private static final TimerEvent.Timer ROOT_TIMER = Optional::empty; @Test - public void testAccept() { + void testAccept() { TimerEventHandler timerEventHandler = new TimerEventHandler(logMessageQueue::add); timerEventHandler.accept( diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/UpdateCheckerTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/UpdateCheckerTest.java index 7b918ee2e09..c3d34941aa1 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/UpdateCheckerTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/UpdateCheckerTest.java @@ -34,41 +34,44 @@ import java.util.Collections; import java.util.Optional; import java.util.concurrent.Future; -import org.junit.After; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +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.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link UpdateChecker}. */ -@RunWith(MockitoJUnitRunner.class) -public class UpdateCheckerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UpdateCheckerTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir public Path temporaryFolder; private TestWebServer testWebServer; private Path configDir; - @Before - public void setUp() + @BeforeEach + void setUpBeforeEach() throws InterruptedException, GeneralSecurityException, URISyntaxException, IOException { String response = "HTTP/1.1 200 OK\nContent-Length:18\n\n{\"latest\":\"2.0.0\"}"; testWebServer = new TestWebServer(false, Collections.singletonList(response), 1); - configDir = temporaryFolder.getRoot().toPath(); + configDir = temporaryFolder; } - @After - public void tearDown() throws IOException { + @AfterEach + void tearDownAfterEach() throws IOException { testWebServer.close(); } @Test - public void testPerformUpdateCheck_newVersionFound() throws IOException, InterruptedException { + void testPerformUpdateCheck_newVersionFound() throws IOException, InterruptedException { Instant before = Instant.now(); Thread.sleep(100); setupLastUpdateCheck(); @@ -85,7 +88,7 @@ public void testPerformUpdateCheck_newVersionFound() throws IOException, Interru } @Test - public void testPerformUpdateCheck_newJsonField() + void testPerformUpdateCheck_newJsonField() throws IOException, InterruptedException, GeneralSecurityException, URISyntaxException { String response = "HTTP/1.1 200 OK\nContent-Length:43\n\n{\"latest\":\"2.0.0\",\"unknownField\":\"unknown\"}"; @@ -100,7 +103,7 @@ public void testPerformUpdateCheck_newJsonField() } @Test - public void testPerformUpdateCheck_onLatest() throws IOException, InterruptedException { + void testPerformUpdateCheck_onLatest() throws IOException, InterruptedException { Instant before = Instant.now(); Thread.sleep(100); setupLastUpdateCheck(); @@ -117,7 +120,7 @@ public void testPerformUpdateCheck_onLatest() throws IOException, InterruptedExc } @Test - public void testPerformUpdateCheck_noLastUpdateCheck() throws IOException, InterruptedException { + void testPerformUpdateCheck_noLastUpdateCheck() throws IOException, InterruptedException { Instant before = Instant.now(); Thread.sleep(100); Optional message = @@ -132,8 +135,7 @@ public void testPerformUpdateCheck_noLastUpdateCheck() throws IOException, Inter } @Test - public void testPerformUpdateCheck_emptyLastUpdateCheck() - throws IOException, InterruptedException { + void testPerformUpdateCheck_emptyLastUpdateCheck() throws IOException, InterruptedException { Files.createFile(configDir.resolve("lastUpdateCheck")); Instant before = Instant.now(); Thread.sleep(100); @@ -149,7 +151,7 @@ public void testPerformUpdateCheck_emptyLastUpdateCheck() } @Test - public void testPerformUpdateCheck_lastUpdateCheckTooSoon() throws IOException { + void testPerformUpdateCheck_lastUpdateCheckTooSoon() throws IOException { FileTime modifiedTime = FileTime.from(Instant.now().minusSeconds(12)); setupLastUpdateCheck(); Files.write( @@ -169,7 +171,7 @@ public void testPerformUpdateCheck_lastUpdateCheckTooSoon() throws IOException { } @Test - public void testPerformUpdateCheck_badLastUpdateTime() throws IOException, InterruptedException { + void testPerformUpdateCheck_badLastUpdateTime() throws IOException, InterruptedException { Instant before = Instant.now(); Thread.sleep(100); Files.write( @@ -186,7 +188,7 @@ public void testPerformUpdateCheck_badLastUpdateTime() throws IOException, Inter } @Test - public void testPerformUpdateCheck_failSilently() + void testPerformUpdateCheck_failSilently() throws InterruptedException, GeneralSecurityException, URISyntaxException, IOException { String response = "HTTP/1.1 400 Bad Request\nContent-Length: 0\n\n"; try (TestWebServer badServer = @@ -206,14 +208,14 @@ public void testPerformUpdateCheck_failSilently() } @Test - public void testFinishUpdateCheck_success() { + void testFinishUpdateCheck_success() { Future> updateCheckFuture = Futures.immediateFuture(Optional.of("Hello")); Optional result = UpdateChecker.finishUpdateCheck(updateCheckFuture); assertThat(result).hasValue("Hello"); } @Test - public void testFinishUpdateCheck_notDone() { + void testFinishUpdateCheck_notDone() { @SuppressWarnings("unchecked") Future> updateCheckFuture = Mockito.mock(Future.class); Mockito.when(updateCheckFuture.isDone()).thenReturn(false); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/VersionCheckerTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/VersionCheckerTest.java index 581f3e8c58a..33b261d345a 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/VersionCheckerTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/VersionCheckerTest.java @@ -17,11 +17,17 @@ package com.google.cloud.tools.jib.plugins.common; import org.junit.Assert; -import org.junit.Before; -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.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link VersionChecker}. */ -public class VersionCheckerTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class VersionCheckerTest { private static class TestVersion implements Comparable { private int[] components; @@ -50,8 +56,8 @@ public int compareTo(TestVersion other) { private VersionChecker checker; - @Before - public void setUp() { + @BeforeEach + void setUpBeforeEach() { Assert.assertTrue(new TestVersion("1.0").compareTo(new TestVersion("1.1.1")) < 0); Assert.assertTrue(new TestVersion("1.1.1").compareTo(new TestVersion("1.0")) > 0); Assert.assertTrue(new TestVersion("1.1").compareTo(new TestVersion("1.1.0.0")) == 0); @@ -59,35 +65,35 @@ public void setUp() { } @Test - public void testComparators_LT() { + void testComparators_LT() { Assert.assertTrue(VersionChecker.lt(0, 1)); Assert.assertFalse(VersionChecker.lt(1, 1)); Assert.assertFalse(VersionChecker.lt(2, 1)); } @Test - public void testComparators_LE() { + void testComparators_LE() { Assert.assertTrue(VersionChecker.le(0, 1)); Assert.assertTrue(VersionChecker.le(1, 1)); Assert.assertFalse(VersionChecker.le(2, 1)); } @Test - public void testComparators_GE() { + void testComparators_GE() { Assert.assertFalse(VersionChecker.ge(0, 1)); Assert.assertTrue(VersionChecker.ge(1, 1)); Assert.assertTrue(VersionChecker.ge(2, 1)); } @Test - public void testComparators_GT() { + void testComparators_GT() { Assert.assertFalse(VersionChecker.gt(0, 1)); Assert.assertFalse(VersionChecker.gt(1, 1)); Assert.assertTrue(VersionChecker.gt(2, 1)); } @Test - public void testRange_leftClosed() { + void testRange_leftClosed() { Assert.assertFalse(checker.compatibleVersion("[2.3,4.3]", "1.0")); Assert.assertFalse(checker.compatibleVersion("[2.3,4.3)", "1.0")); Assert.assertFalse(checker.compatibleVersion("[2.3,)", "1.0")); @@ -95,7 +101,7 @@ public void testRange_leftClosed() { } @Test - public void testRange_leftClosed_exact() { + void testRange_leftClosed_exact() { Assert.assertTrue(checker.compatibleVersion("[2.3,4.3]", "2.3")); Assert.assertTrue(checker.compatibleVersion("[2.3,4.3)", "2.3")); Assert.assertTrue(checker.compatibleVersion("[2.3,)", "2.3")); @@ -103,7 +109,7 @@ public void testRange_leftClosed_exact() { } @Test - public void testRange_leftOpen() { + void testRange_leftOpen() { Assert.assertFalse(checker.compatibleVersion("(2.3,4.3]", "1.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "1.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,)", "1.0")); @@ -111,7 +117,7 @@ public void testRange_leftOpen() { } @Test - public void testRange_leftOpen_exact() { + void testRange_leftOpen_exact() { Assert.assertFalse(checker.compatibleVersion("(2.3,4.3]", "2.3")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "2.3")); Assert.assertFalse(checker.compatibleVersion("(2.3,)", "2.3")); @@ -119,7 +125,7 @@ public void testRange_leftOpen_exact() { } @Test - public void testRange_rightClosed() { + void testRange_rightClosed() { Assert.assertFalse(checker.compatibleVersion("[2.3,4.3]", "5.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3]", "5.0")); Assert.assertFalse(checker.compatibleVersion("[,4.3]", "5.0")); @@ -127,7 +133,7 @@ public void testRange_rightClosed() { } @Test - public void testRange_rightClosed_exact() { + void testRange_rightClosed_exact() { Assert.assertTrue(checker.compatibleVersion("[2.3,4.3]", "4.3")); Assert.assertTrue(checker.compatibleVersion("(2.3,4.3]", "4.3")); Assert.assertTrue(checker.compatibleVersion("[,4.3]", "4.3")); @@ -135,7 +141,7 @@ public void testRange_rightClosed_exact() { } @Test - public void testRange_between() { + void testRange_between() { Assert.assertTrue(checker.compatibleVersion("[2.3,4.3]", "2.4")); Assert.assertTrue(checker.compatibleVersion("(2.3,4.3]", "4.2")); Assert.assertTrue(checker.compatibleVersion("[2.3,4.3)", "2.4")); @@ -143,7 +149,7 @@ public void testRange_between() { } @Test - public void testRange_rightOpen() { + void testRange_rightOpen() { Assert.assertFalse(checker.compatibleVersion("[2.3,4.3)", "5.0")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "5.0")); Assert.assertFalse(checker.compatibleVersion("[,4.3)", "5.0")); @@ -151,7 +157,7 @@ public void testRange_rightOpen() { } @Test - public void testRange_rightOpen_exact() { + void testRange_rightOpen_exact() { Assert.assertFalse(checker.compatibleVersion("[2.3,4.3)", "4.3")); Assert.assertFalse(checker.compatibleVersion("(2.3,4.3)", "4.3")); Assert.assertFalse(checker.compatibleVersion("[,4.3)", "4.3")); @@ -159,25 +165,25 @@ public void testRange_rightOpen_exact() { } @Test - public void testMinimumBound_low() { + void testMinimumBound_low() { Assert.assertFalse(checker.compatibleVersion("2.3", "1.0")); Assert.assertFalse(checker.compatibleVersion("2.3", "2.2")); } @Test - public void testMinimumBound_exact() { + void testMinimumBound_exact() { Assert.assertTrue(checker.compatibleVersion("2.3", "2.3")); } @Test - public void testMinimumBound_high() { + void testMinimumBound_high() { Assert.assertTrue(checker.compatibleVersion("2.3", "2.4")); Assert.assertTrue(checker.compatibleVersion("2.3", "4.0")); } // @SuppressWarnings({"TryFailThrowable", "AssertionFailureIgnored"}) @Test - public void testRange_invalid() { + void testRange_invalid() { for (String rangeSpec : new String[] {"[]", "[,]", "(,]", "[,)", "(,)", "[1,2,3]", "[1]", "foo", "{,2.3)", ""}) { try { diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ZipUtilTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ZipUtilTest.java index 2a5584aa586..ad00f5cc9af 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ZipUtilTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/ZipUtilTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertThrows; import com.google.common.io.Resources; +import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; @@ -31,30 +32,29 @@ import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.junit.Assume; -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; /** Tests for {@link ZipUtil}. */ -public class ZipUtilTest { +class ZipUtilTest { - @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir public Path tempFolder; @Test - public void testUnzip() throws URISyntaxException, IOException { - verifyUnzip(tempFolder.getRoot().toPath()); + void testUnzip() throws URISyntaxException, IOException { + verifyUnzip(tempFolder); } @Test - public void testUnzip_nonExistingDestination() throws URISyntaxException, IOException { - Path destination = tempFolder.getRoot().toPath().resolve("non/exisiting"); + void testUnzip_nonExistingDestination() throws URISyntaxException, IOException { + Path destination = tempFolder.resolve("non/exisiting"); verifyUnzip(destination); Assert.assertTrue(Files.exists(destination)); } @Test - public void testZipSlipVulnerability_windows() throws URISyntaxException { + void testZipSlipVulnerability_windows() throws URISyntaxException { Assume.assumeTrue(System.getProperty("os.name").startsWith("Windows")); Path archive = @@ -63,7 +63,7 @@ public void testZipSlipVulnerability_windows() throws URISyntaxException { } @Test - public void testZipSlipVulnerability_unix() throws URISyntaxException { + void testZipSlipVulnerability_unix() throws URISyntaxException { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows")); Path archive = @@ -72,10 +72,10 @@ public void testZipSlipVulnerability_unix() throws URISyntaxException { } @Test - public void testUnzip_modificationTimePreserved() throws URISyntaxException, IOException { + void testUnzip_modificationTimePreserved() throws URISyntaxException, IOException { Path archive = Paths.get(Resources.getResource("plugins-common/test-archives/test.zip").toURI()); - Path destination = tempFolder.getRoot().toPath(); + Path destination = tempFolder; ZipUtil.unzip(archive, destination); @@ -96,14 +96,14 @@ public void testUnzip_modificationTimePreserved() throws URISyntaxException, IOE } @Test - public void testUnzip_reproducibleTimestampsEnabled() throws URISyntaxException, IOException { + void testUnzip_reproducibleTimestampsEnabled() throws URISyntaxException, IOException { // The zipfile has only level1/level2/level3/file.txt packaged Path archive = Paths.get( Resources.getResource("plugins-common/test-archives/zip-only-file-packaged.zip") .toURI()); - Path destination = tempFolder.getRoot().toPath(); + Path destination = tempFolder; ZipUtil.unzip(archive, destination, true); @@ -118,9 +118,9 @@ public void testUnzip_reproducibleTimestampsEnabled() throws URISyntaxException, } @Test - public void testUnzip_reproducibleTimestampsEnabled_destinationNotEmpty() throws IOException { - Path destination = tempFolder.getRoot().toPath(); - tempFolder.newFile(); + void testUnzip_reproducibleTimestampsEnabled_destinationNotEmpty() throws IOException { + Path destination = tempFolder; + File.createTempFile("jib", "test", tempFolder.toFile()); IllegalStateException exception = assertThrows( @@ -147,7 +147,7 @@ private void verifyUnzip(Path destination) throws URISyntaxException, IOExceptio private void verifyZipSlipSafe(Path archive) { try { - ZipUtil.unzip(archive, tempFolder.getRoot().toPath()); + ZipUtil.unzip(archive, tempFolder); Assert.fail("Should block Zip-Slip"); } catch (IOException ex) { MatcherAssert.assertThat( diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/globalconfig/GlobalConfigTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/globalconfig/GlobalConfigTest.java index e3247c9f1d7..29ce01da84f 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/globalconfig/GlobalConfigTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/globalconfig/GlobalConfigTest.java @@ -25,27 +25,38 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.rules.TemporaryFolder; +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.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; /** Tests for {@link GlobalConfig}. */ -public class GlobalConfigTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@ExtendWith(SystemStubsExtension.class) +class GlobalConfigTest { - @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @SystemStub + @SuppressWarnings("unused") + private SystemProperties restoreSystemProperties; + + @TempDir public Path temporaryFolder; private Path configDir; - @Before - public void setUp() { - configDir = temporaryFolder.getRoot().toPath(); + @BeforeEach + void setUpBeforeEach() { + configDir = temporaryFolder; } @Test - public void testReadConfig_default() throws IOException, InvalidGlobalConfigException { + void testReadConfig_default() throws IOException, InvalidGlobalConfigException { GlobalConfig globalConfig = GlobalConfig.readConfig(configDir); assertThat(globalConfig.isDisableUpdateCheck()).isFalse(); @@ -53,7 +64,7 @@ public void testReadConfig_default() throws IOException, InvalidGlobalConfigExce } @Test - public void testReadConfig_newConfigCreated() throws IOException, InvalidGlobalConfigException { + void testReadConfig_newConfigCreated() throws IOException, InvalidGlobalConfigException { GlobalConfig.readConfig(configDir); String configJson = new String(Files.readAllBytes(configDir.resolve("config.json")), StandardCharsets.UTF_8); @@ -61,7 +72,7 @@ public void testReadConfig_newConfigCreated() throws IOException, InvalidGlobalC } @Test - public void testReadConfig_emptyJson() throws IOException, InvalidGlobalConfigException { + void testReadConfig_emptyJson() throws IOException, InvalidGlobalConfigException { Files.write(configDir.resolve("config.json"), "{}".getBytes(StandardCharsets.UTF_8)); GlobalConfig globalConfig = GlobalConfig.readConfig(configDir); @@ -70,7 +81,7 @@ public void testReadConfig_emptyJson() throws IOException, InvalidGlobalConfigEx } @Test - public void testReadConfig() throws IOException, InvalidGlobalConfigException { + void testReadConfig() throws IOException, InvalidGlobalConfigException { String json = "{\"disableUpdateCheck\":true, \"registryMirrors\":[" + "{ \"registry\": \"registry-1.docker.io\"," @@ -92,7 +103,7 @@ public void testReadConfig() throws IOException, InvalidGlobalConfigException { } @Test - public void testReadConfig_systemProperties() throws IOException, InvalidGlobalConfigException { + void testReadConfig_systemProperties() throws IOException, InvalidGlobalConfigException { Files.write( configDir.resolve("config.json"), "{\"disableUpdateCheck\":false}".getBytes(StandardCharsets.UTF_8)); @@ -103,8 +114,9 @@ public void testReadConfig_systemProperties() throws IOException, InvalidGlobalC } @Test - public void testReadConfig_emptyFile() throws IOException { - temporaryFolder.newFile("config.json"); + void testReadConfig_emptyFile() throws IOException { + new File(temporaryFolder.toFile(), "config.json").createNewFile(); + IOException exception = assertThrows(IOException.class, () -> GlobalConfig.readConfig(configDir)); assertThat(exception) @@ -117,7 +129,7 @@ public void testReadConfig_emptyFile() throws IOException { } @Test - public void testReadConfig_corrupted() throws IOException { + void testReadConfig_corrupted() throws IOException { Files.write( configDir.resolve("config.json"), "corrupt config".getBytes(StandardCharsets.UTF_8)); IOException exception = @@ -132,7 +144,7 @@ public void testReadConfig_corrupted() throws IOException { } @Test - public void testReadConfig_missingRegistry() throws IOException { + void testReadConfig_missingRegistry() throws IOException { String json = "{\"registryMirrors\":[{\"mirrors\":[\"mirror.gcr.io\"]}]}"; Files.write(configDir.resolve("config.json"), json.getBytes(StandardCharsets.UTF_8)); InvalidGlobalConfigException exception = @@ -146,7 +158,7 @@ public void testReadConfig_missingRegistry() throws IOException { } @Test - public void testReadConfig_missingMirrors() throws IOException { + void testReadConfig_missingMirrors() throws IOException { String json = "{\"registryMirrors\":[{\"registry\": \"registry\"}]}"; Files.write(configDir.resolve("config.json"), json.getBytes(StandardCharsets.UTF_8)); InvalidGlobalConfigException exception = diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/AnsiLoggerWithFooterTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/AnsiLoggerWithFooterTest.java index fb8c8ff5ad1..190e712d664 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/AnsiLoggerWithFooterTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/AnsiLoggerWithFooterTest.java @@ -25,10 +25,10 @@ import java.util.List; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link AnsiLoggerWithFooter}. */ -public class AnsiLoggerWithFooterTest { +class AnsiLoggerWithFooterTest { private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(3); @@ -38,7 +38,7 @@ public class AnsiLoggerWithFooterTest { private final List levels = new ArrayList<>(); @Test - public void testTruncateToMaxWidth() { + void testTruncateToMaxWidth() { List lines = Arrays.asList( "this line of text is way too long and will be truncated", @@ -51,7 +51,7 @@ public void testTruncateToMaxWidth() { } @Test - public void testNoLifecycle() { + void testNoLifecycle() { try { new AnsiLoggerWithFooter(ImmutableMap.of(), singleThreadedExecutor, false); Assert.fail(); @@ -63,7 +63,7 @@ public void testNoLifecycle() { } @Test - public void testLog_noFooter() { + void testLog_noFooter() { AnsiLoggerWithFooter testAnsiLoggerWithFooter = createTestLogger(false); testAnsiLoggerWithFooter.log(Level.LIFECYCLE, "lifecycle"); testAnsiLoggerWithFooter.log(Level.PROGRESS, "progress"); @@ -83,7 +83,7 @@ public void testLog_noFooter() { } @Test - public void testLog_ignoreIfNoMessageConsumer() { + void testLog_ignoreIfNoMessageConsumer() { AnsiLoggerWithFooter testAnsiLoggerWithFooter = new AnsiLoggerWithFooter( ImmutableMap.of(Level.LIFECYCLE, createMessageConsumer(Level.LIFECYCLE)), @@ -104,7 +104,7 @@ public void testLog_ignoreIfNoMessageConsumer() { } @Test - public void testLog_sameFooter() { + void testLog_sameFooter() { AnsiLoggerWithFooter testAnsiLoggerWithFooter = createTestLogger(false); testAnsiLoggerWithFooter.setFooter(Collections.singletonList("footer")); testAnsiLoggerWithFooter.log(Level.INFO, "message"); @@ -139,7 +139,7 @@ public void testLog_sameFooter() { } @Test - public void testLog_sameFooterWithEnableTwoCursorUpJump() { + void testLog_sameFooterWithEnableTwoCursorUpJump() { AnsiLoggerWithFooter testAnsiLoggerWithFooter = createTestLogger(true); testAnsiLoggerWithFooter.setFooter(Collections.singletonList("footer")); testAnsiLoggerWithFooter.log(Level.INFO, "message"); @@ -178,7 +178,7 @@ public void testLog_sameFooterWithEnableTwoCursorUpJump() { } @Test - public void testLog_changingFooter() { + void testLog_changingFooter() { AnsiLoggerWithFooter testAnsiLoggerWithFooter = createTestLogger(false); testAnsiLoggerWithFooter.setFooter(Collections.singletonList("footer")); testAnsiLoggerWithFooter.log(Level.WARN, "message"); @@ -224,7 +224,7 @@ public void testLog_changingFooter() { } @Test - public void testLog_changingFooterWithEnableTwoCursorUpJump() { + void testLog_changingFooterWithEnableTwoCursorUpJump() { AnsiLoggerWithFooter testAnsiLoggerWithFooter = createTestLogger(true); testAnsiLoggerWithFooter.setFooter(Collections.singletonList("footer")); testAnsiLoggerWithFooter.log(Level.WARN, "message"); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ConsoleLoggerBuilderTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ConsoleLoggerBuilderTest.java index fda6efaa617..c30cb6362b0 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ConsoleLoggerBuilderTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ConsoleLoggerBuilderTest.java @@ -24,14 +24,17 @@ import java.util.List; import java.util.function.Consumer; import org.junit.Assert; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ConsoleLoggerBuilder}. */ -@RunWith(MockitoJUnitRunner.class) -public class ConsoleLoggerBuilderTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ConsoleLoggerBuilderTest { @Mock private Consumer mockLifecycleConsumer; @Mock private Consumer mockProgressConsumer; @@ -41,7 +44,7 @@ public class ConsoleLoggerBuilderTest { @Mock private Consumer mockErrorConsumer; @Test - public void testBuild() { + void testBuild() { List messages = new ArrayList<>(); List levels = new ArrayList<>(); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/PlainConsoleLoggerTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/PlainConsoleLoggerTest.java index 67f75c73315..5f47cb9f945 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/PlainConsoleLoggerTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/PlainConsoleLoggerTest.java @@ -25,10 +25,10 @@ import java.util.List; import java.util.function.Consumer; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link PlainConsoleLogger}. */ -public class PlainConsoleLoggerTest { +class PlainConsoleLoggerTest { private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(3); @@ -40,7 +40,7 @@ public class PlainConsoleLoggerTest { private PlainConsoleLogger testPlainConsoleLogger; @Test - public void testLog() { + void testLog() { ImmutableMap.Builder> messageConsumers = ImmutableMap.builder(); for (Level level : Level.values()) { messageConsumers.put(level, createMessageConsumer(level)); @@ -67,7 +67,7 @@ public void testLog() { } @Test - public void testLog_filterOutColors() { + void testLog_filterOutColors() { ImmutableMap.Builder> messageConsumers = ImmutableMap.builder(); for (Level level : Level.values()) { messageConsumers.put(level, createMessageConsumer(level)); @@ -87,7 +87,7 @@ public void testLog_filterOutColors() { } @Test - public void testLog_ignoreIfNoMessageConsumer() { + void testLog_ignoreIfNoMessageConsumer() { testPlainConsoleLogger = new PlainConsoleLogger( ImmutableMap.of(Level.WARN, createMessageConsumer(Level.WARN)), singleThreadedExecutor); diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ProgressDisplayGeneratorTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ProgressDisplayGeneratorTest.java index 8a09dd6850d..b78c1676f81 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ProgressDisplayGeneratorTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/ProgressDisplayGeneratorTest.java @@ -19,38 +19,38 @@ import java.util.Arrays; import java.util.Collections; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ProgressDisplayGenerator}. */ -public class ProgressDisplayGeneratorTest { +class ProgressDisplayGeneratorTest { private static String getBar(String bar, double value) { return String.format("%s %.1f%% complete", bar, value); } @Test - public void testGenerateProgressDisplay_progressBar_0() { + void testGenerateProgressDisplay_progressBar_0() { Assert.assertEquals( Arrays.asList("Executing tasks:", getBar("[ ]", 0.0)), ProgressDisplayGenerator.generateProgressDisplay(0, Collections.emptyList())); } @Test - public void testGenerateProgressDisplay_progressBar_50() { + void testGenerateProgressDisplay_progressBar_50() { Assert.assertEquals( Arrays.asList("Executing tasks:", getBar("[=============== ]", 50.0)), ProgressDisplayGenerator.generateProgressDisplay(0.5, Collections.emptyList())); } @Test - public void testGenerateProgressDisplay_progressBar_100() { + void testGenerateProgressDisplay_progressBar_100() { Assert.assertEquals( Arrays.asList("Executing tasks:", getBar("[==============================]", 100.0)), ProgressDisplayGenerator.generateProgressDisplay(1, Collections.emptyList())); } @Test - public void testGenerateProgressDisplay_unfinishedTasks() { + void testGenerateProgressDisplay_unfinishedTasks() { Assert.assertEquals( Arrays.asList( "Executing tasks:", diff --git a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/SingleThreadedExecutorTest.java b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/SingleThreadedExecutorTest.java index e875eb9fbe1..b8a902fd09b 100644 --- a/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/SingleThreadedExecutorTest.java +++ b/jib-plugins-common/src/test/java/com/google/cloud/tools/jib/plugins/common/logging/SingleThreadedExecutorTest.java @@ -24,17 +24,16 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link SingleThreadedExecutor}. */ -public class SingleThreadedExecutorTest { +class SingleThreadedExecutorTest { private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(3); @SuppressWarnings("ThreadPriorityCheck") // use of Thread.yield() @Test - public void testExecute_mutualExclusion() - throws IOException, ExecutionException, InterruptedException { + void testExecute_mutualExclusion() throws IOException, ExecutionException, InterruptedException { SingleThreadedExecutor singleThreadedExecutor = new SingleThreadedExecutor(); Lock lock = new ReentrantLock(); diff --git a/jib-plugins-extension-common/build.gradle b/jib-plugins-extension-common/build.gradle index 5151d6a8915..9107876cdf6 100644 --- a/jib-plugins-extension-common/build.gradle +++ b/jib-plugins-extension-common/build.gradle @@ -38,7 +38,7 @@ publishing { release { tagTemplate = 'v$version-extension-common' git { - requireBranch = /^extension-common-release-v\d+.*$/ //regex + requireBranch.set(/^extension-common-release-v\d+.*$/) //regex } } /* RELEASE */