From 67bcce0cc324430f9e81f38ebd30cf224441b424 Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Fri, 2 Jan 2026 14:13:18 +0100 Subject: [PATCH] Migrate tests to JUnit Jupiter * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor code cleanup * Ban JUnit4 imports --- pom.xml | 3 +- .../AbstractBucketLifecycleManagerTest.java | 107 ++++---- .../plugins/storage/AbstractUploadTest.java | 241 ++++++++---------- .../storage/ClassicUploadStepTest.java | 40 +-- .../plugins/storage/ClassicUploadTest.java | 66 ++--- .../plugins/storage/DownloadStepTest.java | 91 ++++--- ...xpiringBucketLifecycleManagerStepTest.java | 32 ++- .../ExpiringBucketLifecycleManagerTest.java | 82 +++--- .../GoogleCloudStorageUploaderTest.java | 131 +++++----- .../plugins/storage/HttpHeadersTest.java | 20 +- .../plugins/storage/MockUploadModule.java | 40 ++- .../plugins/storage/StdoutUploadStepTest.java | 32 ++- .../plugins/storage/StdoutUploadTest.java | 32 ++- .../plugins/storage/UploadModuleTest.java | 57 +++-- .../storage/client/ClientFactoryTest.java | 26 +- .../storage/client/StorageClientTest.java | 97 +++---- .../ClassicUploadStepPipelineIT.java | 32 +-- .../integration/DownloadStepPipelineIT.java | 29 ++- .../ExpiringBucketLifeCycleManagerIT.java | 31 +-- .../plugins/storage/integration/ITUtil.java | 24 +- .../StdoutUploadStepPipelineIT.java | 30 ++- .../reports/AbstractGcsUploadReportTest.java | 21 +- .../reports/BuildGcsUploadReportTest.java | 43 ++-- .../reports/ProjectGcsUploadReportTest.java | 25 +- .../storage/util/CredentialsUtilTest.java | 69 +++-- .../util/RetryStorageOperationTest.java | 84 ++---- .../plugins/storage/util/StorageUtilTest.java | 39 ++- 27 files changed, 772 insertions(+), 752 deletions(-) diff --git a/pom.xml b/pom.xml index a2fa7e1a..5b263726 100644 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,7 @@ High false + false @@ -258,7 +259,7 @@ org.mockito - mockito-core + mockito-junit-jupiter test diff --git a/src/test/java/com/google/jenkins/plugins/storage/AbstractBucketLifecycleManagerTest.java b/src/test/java/com/google/jenkins/plugins/storage/AbstractBucketLifecycleManagerTest.java index 1cbdc44b..92def1f5 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/AbstractBucketLifecycleManagerTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/AbstractBucketLifecycleManagerTest.java @@ -16,10 +16,11 @@ package com.google.jenkins.plugins.storage; import static com.google.common.base.Preconditions.checkNotNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -34,27 +35,34 @@ import com.google.jenkins.plugins.util.ForbiddenException; import com.google.jenkins.plugins.util.MockExecutor; import com.google.jenkins.plugins.util.NotFoundException; +import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.Extension; +import hudson.FilePath; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.TaskListener; import hudson.util.FormValidation; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Verifier; +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.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link AbstractBucketLifecycleManager}. */ -public class AbstractBucketLifecycleManagerTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AbstractBucketLifecycleManagerTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -67,24 +75,18 @@ public class AbstractBucketLifecycleManagerTest { private NotFoundException notFoundException; private Predicate checkBucketName(final String bucketName) { - return new Predicate() { - @Override - public boolean apply(Storage.Buckets.Insert operation) { - Bucket bucket = (Bucket) operation.getJsonContent(); - assertEquals(bucketName, bucket.getName()); - return true; - } + return operation -> { + Bucket bucket = (Bucket) operation.getJsonContent(); + assertEquals(bucketName, bucket.getName()); + return true; }; } private Predicate checkSameBucket(final Bucket theBucket) { - return new Predicate() { - @Override - public boolean apply(Storage.Buckets.Update operation) { - Bucket bucket = (Bucket) operation.getJsonContent(); - assertSame(bucket, theBucket); - return true; - } + return operation -> { + Bucket bucket = (Bucket) operation.getJsonContent(); + assertSame(bucket, theBucket); + return true; }; } @@ -113,15 +115,6 @@ public MockExecutor newExecutor() { private final int retryCount; } - @Rule - public Verifier verifySawAll = new Verifier() { - @Override - public void verify() { - assertTrue(executor.sawAll()); - assertFalse(executor.sawUnexpected()); - } - }; - private static class FakeUpload extends AbstractBucketLifecycleManager { public FakeUpload(String bucketName, MockUploadModule module, String details, @Nullable Bucket bucket) { @@ -161,6 +154,8 @@ public DescriptorImpl() { super(FakeUpload.class); } + @NonNull + @Override public String getDisplayName() { return "asdf"; } @@ -170,9 +165,9 @@ public String getDisplayName() { private FreeStyleProject project; private FreeStyleBuild build; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -200,9 +195,15 @@ public void setUp() throws Exception { forbiddenException = new ForbiddenException(); } + @AfterEach + void afterEach() { + assertTrue(executor.sawAll()); + assertFalse(executor.sawUnexpected()); + } + @Test @WithoutJenkins - public void testGetters() { + void testGetters() { FakeUpload underTest = new FakeUpload(BUCKET_URI, new MockUploadModule(executor), FAKE_DETAILS, null /* bucket */); @@ -211,7 +212,7 @@ public void testGetters() { } @Test - public void testFailingBucketCheck() throws Exception { + void testFailingBucketCheck() throws Exception { final Bucket bucket = new Bucket().setName(BUCKET_NAME); FakeUpload underTest = new FakeUpload(BUCKET_URI, new MockUploadModule(executor), FAKE_DETAILS, bucket); @@ -224,7 +225,7 @@ public void testFailingBucketCheck() throws Exception { } @Test - public void testPassingBucketCheck() throws Exception { + void testPassingBucketCheck() throws Exception { final Bucket bucket = new Bucket().setName(BUCKET_NAME); FakeUpload underTest = new FakeUpload( @@ -237,7 +238,7 @@ public void testPassingBucketCheck() throws Exception { } @Test - public void testPassingBucketCheckAfterNotFoundThenConflict() throws Exception { + void testPassingBucketCheckAfterNotFoundThenConflict() throws Exception { final Bucket bucket = new Bucket().setName(BUCKET_NAME); FakeUpload underTest = new FakeUpload(BUCKET_URI, new MockUploadModule(executor), FAKE_DETAILS, bucket); @@ -251,28 +252,28 @@ public void testPassingBucketCheckAfterNotFoundThenConflict() throws Exception { underTest.perform(CREDENTIALS_ID, build, build.getWorkspace(), TaskListener.NULL); } - @Test(expected = UploadException.class) - public void testRandomErrorExecutor() throws Exception { + @Test + void testRandomErrorExecutor() { FakeUpload underTest = new FakeUpload( BUCKET_URI, new MockUploadModule(executor), FAKE_DETAILS, null /* pass the bucket check */); - executor.throwWhen(Storage.Buckets.Get.class, conflictException); - - underTest.perform(CREDENTIALS_ID, build, build.getWorkspace(), TaskListener.NULL); + FilePath workspace = build.getWorkspace(); + TaskListener x = TaskListener.NULL; + assertThrows(UploadException.class, () -> underTest.perform(CREDENTIALS_ID, build, workspace, x)); } - @Test(expected = UploadException.class) - public void testRandomErrorIOException() throws Exception { + @Test + void testRandomErrorIOException() { FakeUpload underTest = new FakeUpload( BUCKET_URI, new MockUploadModule(executor), FAKE_DETAILS, null /* pass the bucket check */); - executor.throwWhen(Storage.Buckets.Get.class, new IOException("test")); - - underTest.perform(CREDENTIALS_ID, build, build.getWorkspace(), TaskListener.NULL); + FilePath workspace = build.getWorkspace(); + TaskListener x = TaskListener.NULL; + assertThrows(UploadException.class, () -> underTest.perform(CREDENTIALS_ID, build, workspace, x)); } @Test - public void testCustomBucketNameValidation() throws Exception { + void testCustomBucketNameValidation() throws Exception { FakeUpload underTest = new FakeUpload( BUCKET_URI, new MockUploadModule(executor), FAKE_DETAILS, null /* pass the bucket check */); diff --git a/src/test/java/com/google/jenkins/plugins/storage/AbstractUploadTest.java b/src/test/java/com/google/jenkins/plugins/storage/AbstractUploadTest.java index 5c596252..e039d4df 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/AbstractUploadTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/AbstractUploadTest.java @@ -18,12 +18,13 @@ import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_UNAUTHORIZED; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -35,8 +36,6 @@ import com.google.api.services.storage.model.Bucket; import com.google.api.services.storage.model.ObjectAccessControl; import com.google.api.services.storage.model.StorageObject; -import com.google.common.base.Charsets; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -50,6 +49,7 @@ import com.google.jenkins.plugins.util.ForbiddenException; import com.google.jenkins.plugins.util.MockExecutor; import com.google.jenkins.plugins.util.NotFoundException; +import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.Extension; import hudson.FilePath; @@ -60,28 +60,34 @@ import hudson.util.FormValidation; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import org.apache.commons.lang3.SystemUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.Verifier; +import org.junit.jupiter.api.AfterEach; +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.api.io.TempDir; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link AbstractUpload}. */ -public class AbstractUploadTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AbstractUploadTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; - @Rule - public TemporaryFolder tempDir = new TemporaryFolder(); + @TempDir + private File tempDir; private FilePath workspace; private FilePath nonWorkspace; @@ -104,15 +110,6 @@ public class AbstractUploadTest { @Mock private HttpResponseException httpResponseException; - @Rule - public Verifier verifySawAll = new Verifier() { - @Override - public void verify() { - assertTrue(executor.sawAll()); - assertFalse(executor.sawUnexpected()); - } - }; - private static class FakeUpload extends AbstractUpload { public FakeUpload( @@ -140,8 +137,7 @@ public String getDetails() { @Override @Nullable - protected UploadSpec getInclusions(Run run, FilePath workspace, TaskListener listener) - throws UploadException { + protected UploadSpec getInclusions(Run run, FilePath workspace, TaskListener listener) { return uploads; } @@ -158,6 +154,8 @@ public DescriptorImpl() { super(FakeUpload.class); } + @NonNull + @Override public String getDisplayName() { return "asdf"; } @@ -167,14 +165,14 @@ public String getDisplayName() { private FreeStyleProject project; private FreeStyleBuild build; - @BeforeClass - public static void init() { + @BeforeAll + static void beforeAll() { assumeFalse(SystemUtils.IS_OS_WINDOWS); } - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -205,21 +203,27 @@ public void setUp() throws Exception { workspace = new FilePath(makeTempDir("workspace")); workspaceFile = workspace.child(FILENAME); workspaceFileContent = "Some filler content"; - workspaceFile.write(workspaceFileContent, Charsets.UTF_8.name()); + workspaceFile.write(workspaceFileContent, StandardCharsets.UTF_8.name()); workspaceFile2 = workspace.child(FILENAME2); - workspaceFile2.write(workspaceFileContent, Charsets.UTF_8.name()); + workspaceFile2.write(workspaceFileContent, StandardCharsets.UTF_8.name()); workspaceSubdir = workspace.child(SUBDIR_PREFIX); workspaceSubdir.mkdirs(); workspaceSubdirFile = workspaceSubdir.child(FILENAME); - workspaceSubdirFile.write(workspaceFileContent, Charsets.UTF_8.name()); + workspaceSubdirFile.write(workspaceFileContent, StandardCharsets.UTF_8.name()); nonWorkspace = new FilePath(makeTempDir("non-workspace")); } + @AfterEach + void afterEach() { + assertTrue(executor.sawAll()); + assertFalse(executor.sawUnexpected()); + } + @Test @WithoutJenkins - public void testGetters() { + void testGetters() { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = true; @@ -240,22 +244,24 @@ public void testGetters() { assertEquals(showInline, underTest.isShowInline()); } - @Test(expected = NullPointerException.class) + @Test @WithoutJenkins - public void testCheckNullBucket() throws Exception { - new FakeUpload( - null /* TESTING NULL BUCKET*/, - false /* sharedPublicly */, - true /* forFailedJobs */, - false /* showInline */, - null /* pathPrefix */, - new MockUploadModule(executor), - FAKE_DETAILS, - null /* uploads */); + void testCheckNullBucket() { + assertThrows( + NullPointerException.class, + () -> new FakeUpload( + null /* TESTING NULL BUCKET*/, + false /* sharedPublicly */, + true /* forFailedJobs */, + false /* showInline */, + null /* pathPrefix */, + new MockUploadModule(executor), + FAKE_DETAILS, + null /* uploads */)); } @Test - public void testCheckNullOnNullables() throws Exception { + void testCheckNullOnNullables() { // The upload should handle null for the other fields. new FakeUpload( BUCKET_URI, @@ -269,7 +275,7 @@ public void testCheckNullOnNullables() throws Exception { } @Test - public void testKeepPathPrefix() throws Exception { + void testKeepPathPrefix() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -296,7 +302,7 @@ public void testKeepPathPrefix() throws Exception { } @Test - public void testStripPathPrefixWithCorrectPrefix() throws Exception { + void testStripPathPrefixWithCorrectPrefix() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -328,7 +334,7 @@ public void testStripPathPrefixWithCorrectPrefix() throws Exception { } @Test - public void testStripPathPrefixWithWrongPrefix() throws Exception { + void testStripPathPrefixWithWrongPrefix() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -357,7 +363,7 @@ public void testStripPathPrefixWithWrongPrefix() throws Exception { } @Test - public void testStripPathPrefixNoTrailingSlash() throws Exception { + void testStripPathPrefixNoTrailingSlash() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -384,7 +390,7 @@ public void testStripPathPrefixNoTrailingSlash() throws Exception { } @Test - public void testStripPathPrefixWithNonDirectoryPrefix() throws Exception { + void testStripPathPrefixWithNonDirectoryPrefix() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -415,7 +421,7 @@ public void testStripPathPrefixWithNonDirectoryPrefix() throws Exception { } @Test - public void testOnePartPrefix() throws Exception { + void testOnePartPrefix() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -442,7 +448,7 @@ public void testOnePartPrefix() throws Exception { } @Test - public void testTwoPartPrefix() throws Exception { + void testTwoPartPrefix() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -470,7 +476,7 @@ public void testTwoPartPrefix() throws Exception { } @Test - public void testRetryOnFailure() throws Exception { + void testRetryOnFailure() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -497,16 +503,14 @@ public void testRetryOnFailure() throws Exception { underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); } - @Test(expected = UploadException.class) - public void testRetryOnFailureStillFails() throws Exception { + @Test + void testRetryOnFailureStillFails() { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; final String pathPrefix = null; - final AbstractUpload.UploadSpec uploads = new AbstractUpload.UploadSpec(workspace, ImmutableList.of(workspaceFile)); - FakeUpload underTest = new FakeUpload( BUCKET_URI, sharedPublicly, @@ -516,17 +520,16 @@ public void testRetryOnFailureStillFails() throws Exception { new MockUploadModule(executor, 2 /* retries */), FAKE_DETAILS, uploads); - executor.throwWhen(Storage.Buckets.Get.class, notFoundException); executor.passThruWhen(Storage.Buckets.Insert.class, MockUploadModule.checkBucketName(BUCKET_NAME)); executor.throwWhen(Storage.Objects.Insert.class, new IOException("should trigger retry")); executor.throwWhen(Storage.Objects.Insert.class, new IOException("should trigger failure")); - - underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); + TaskListener x = TaskListener.NULL; + assertThrows(UploadException.class, () -> underTest.perform(CREDENTIALS_ID, build, x)); } @Test - public void testRetryOn401() throws Exception { + void testRetryOn401() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -560,20 +563,17 @@ public void testRetryOn401() throws Exception { underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); } - @Test(expected = UploadException.class) - public void testRetryOn401StillFails() throws Exception { + @Test + void testRetryOn401StillFails() { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; final String pathPrefix = null; - Bucket bucket = new Bucket(); bucket.setName(BUCKET_NAME); bucket.setDefaultObjectAcl(Lists.newArrayList(new ObjectAccessControl())); - final AbstractUpload.UploadSpec uploads = new AbstractUpload.UploadSpec(workspace, ImmutableList.of(workspaceFile)); - FakeUpload underTest = new FakeUpload( BUCKET_URI, sharedPublicly, @@ -583,20 +583,18 @@ public void testRetryOn401StillFails() throws Exception { new MockUploadModule(executor), /* no retries */ FAKE_DETAILS, uploads); - int maxRetriesPlus1 = RetryStorageOperation.MAX_REMOTE_CREDENTIAL_EXPIRED_RETRIES + 1; - for (int i = 0; i < maxRetriesPlus1; i++) { executor.when(Storage.Buckets.Get.class, bucket); executor.throwWhen( Storage.Objects.Insert.class, httpResponseException, MockUploadModule.checkObjectName(FILENAME)); } - - underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); + TaskListener x = TaskListener.NULL; + assertThrows(UploadException.class, () -> underTest.perform(CREDENTIALS_ID, build, x)); } @Test - public void testNullUploadSpec() throws Exception { + void testNullUploadSpec() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -617,14 +615,13 @@ public void testNullUploadSpec() throws Exception { } @Test - public void testWorkspaceNoFiles() throws Exception { + void testWorkspaceNoFiles() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; final String pathPrefix = null; - final AbstractUpload.UploadSpec uploads = - new AbstractUpload.UploadSpec(workspace, ImmutableList.of()); + final AbstractUpload.UploadSpec uploads = new AbstractUpload.UploadSpec(workspace, ImmutableList.of()); FakeUpload underTest = new FakeUpload( BUCKET_URI + "/" + STORAGE_PREFIX, @@ -644,14 +641,13 @@ public void testWorkspaceNoFiles() throws Exception { } @Test - public void testBucketConflict() throws Exception { + void testBucketConflict() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; final String pathPrefix = null; - final AbstractUpload.UploadSpec uploads = - new AbstractUpload.UploadSpec(workspace, ImmutableList.of()); + final AbstractUpload.UploadSpec uploads = new AbstractUpload.UploadSpec(workspace, ImmutableList.of()); FakeUpload underTest = new FakeUpload( BUCKET_URI, @@ -675,16 +671,13 @@ public void testBucketConflict() throws Exception { underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); } - @Test(expected = UploadException.class) - public void testBucketException() throws Exception { + @Test + void testBucketException() { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; final String pathPrefix = null; - - final AbstractUpload.UploadSpec uploads = - new AbstractUpload.UploadSpec(workspace, ImmutableList.of()); - + final AbstractUpload.UploadSpec uploads = new AbstractUpload.UploadSpec(workspace, ImmutableList.of()); FakeUpload underTest = new FakeUpload( BUCKET_URI, sharedPublicly, @@ -694,14 +687,13 @@ public void testBucketException() throws Exception { new MockUploadModule(executor), FAKE_DETAILS, uploads); - executor.throwWhen(Storage.Buckets.Get.class, new IOException("test")); - - underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); + TaskListener x = TaskListener.NULL; + assertThrows(UploadException.class, () -> underTest.perform(CREDENTIALS_ID, build, x)); } @Test - public void testTrailingSlash() throws Exception { + void testTrailingSlash() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -731,7 +723,7 @@ public void testTrailingSlash() throws Exception { } @Test - public void testSharedPublicly() throws Exception { + void testSharedPublicly() throws Exception { final boolean sharedPublicly = true; final boolean forFailedJobs = true; final boolean showInline = false; @@ -755,30 +747,27 @@ public void testSharedPublicly() throws Exception { bucket.setDefaultObjectAcl(Lists.newArrayList(new ObjectAccessControl())); executor.when(Storage.Buckets.Get.class, bucket); - executor.passThruWhen(Storage.Objects.Insert.class, new Predicate() { - @Override - public boolean apply(Storage.Objects.Insert operation) { - StorageObject object = (StorageObject) operation.getJsonContent(); - - assertTrue(object.getAcl().containsAll(bucket.getDefaultObjectAcl())); - - List addedAcl = - Lists.newArrayList(Iterables.filter(object.getAcl(), not(in(bucket.getDefaultObjectAcl())))); - Set addedEntities = Sets.newHashSet(); - for (ObjectAccessControl access : addedAcl) { - assertEquals("READER", access.getRole()); - addedEntities.add(access.getEntity()); - } - assertTrue(addedEntities.contains("allUsers")); - return true; + executor.passThruWhen(Storage.Objects.Insert.class, operation -> { + StorageObject object = (StorageObject) operation.getJsonContent(); + + assertTrue(object.getAcl().containsAll(bucket.getDefaultObjectAcl())); + + List addedAcl = + Lists.newArrayList(Iterables.filter(object.getAcl(), not(in(bucket.getDefaultObjectAcl())))); + Set addedEntities = Sets.newHashSet(); + for (ObjectAccessControl access : addedAcl) { + assertEquals("READER", access.getRole()); + addedEntities.add(access.getEntity()); } + assertTrue(addedEntities.contains("allUsers")); + return true; }); underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); } @Test - public void testNotShared() throws Exception { + void testNotShared() throws Exception { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; @@ -802,30 +791,25 @@ public void testNotShared() throws Exception { bucket.setDefaultObjectAcl(Lists.newArrayList(new ObjectAccessControl())); executor.when(Storage.Buckets.Get.class, bucket); - executor.passThruWhen(Storage.Objects.Insert.class, new Predicate() { - @Override - public boolean apply(Storage.Objects.Insert operation) { - StorageObject object = (StorageObject) operation.getJsonContent(); + executor.passThruWhen(Storage.Objects.Insert.class, operation -> { + StorageObject object = (StorageObject) operation.getJsonContent(); - assertNull(object.getAcl()); - return true; - } + assertNull(object.getAcl()); + return true; }); underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); } - @Test(expected = UploadException.class) - public void upload_nofile() throws UploadException, IOException { + @Test + void upload_nofile() { final boolean sharedPublicly = false; final boolean forFailedJobs = true; final boolean showInline = false; final String pathPrefix = null; - FilePath nonExistentFile = workspace.child("non-existent-file"); final AbstractUpload.UploadSpec uploads = new AbstractUpload.UploadSpec(workspace, ImmutableList.of(nonExistentFile)); - FakeUpload underTest = new FakeUpload( BUCKET_URI, sharedPublicly, @@ -835,16 +819,15 @@ public void upload_nofile() throws UploadException, IOException { new MockUploadModule(executor), FAKE_DETAILS, uploads); - executor.throwWhen(Storage.Buckets.Get.class, notFoundException); executor.passThruWhen(Storage.Buckets.Insert.class, MockUploadModule.checkBucketName(BUCKET_NAME)); - - underTest.perform(CREDENTIALS_ID, build, TaskListener.NULL); + TaskListener x = TaskListener.NULL; + assertThrows(UploadException.class, () -> underTest.perform(CREDENTIALS_ID, build, x)); } @Test @WithoutJenkins - public void doCheckBucketTest() throws IOException { + void doCheckBucketTest() throws IOException { DescriptorImpl descriptor = new DescriptorImpl(); assertEquals(FormValidation.Kind.OK, descriptor.doCheckBucketNameWithVars("gs://asdf").kind); @@ -860,8 +843,8 @@ public void doCheckBucketTest() throws IOException { assertEquals(FormValidation.Kind.ERROR, descriptor.doCheckBucketNameWithVars("foo").kind); } - private File makeTempDir(String name) throws IOException { - File dir = new File(tempDir.getRoot(), name); + private File makeTempDir(String name) { + File dir = new File(tempDir, name); dir.mkdir(); return dir; } diff --git a/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadStepTest.java b/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadStepTest.java index aa2a89d1..c5c059e9 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadStepTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadStepTest.java @@ -15,8 +15,9 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -32,18 +33,23 @@ import hudson.model.FreeStyleProject; import hudson.model.TaskListener; import org.apache.commons.lang3.SystemUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ClassicUpload}. */ -public class ClassicUploadStepTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ClassicUploadStepTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -52,11 +58,11 @@ public class ClassicUploadStepTest { private final MockExecutor executor = new MockExecutor(); - private NotFoundException notFoundException = new NotFoundException(); + private final NotFoundException notFoundException = new NotFoundException(); - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -77,7 +83,7 @@ private void ConfigurationRoundTripTest(ClassicUploadStep s) throws Exception { } @Test - public void testRoundtrip() throws Exception { + void testRoundtrip() throws Exception { assumeFalse(SystemUtils.IS_OS_WINDOWS); ClassicUploadStep step = new ClassicUploadStep(CREDENTIALS_ID, "bucket", "pattern"); ConfigurationRoundTripTest(step); @@ -93,7 +99,7 @@ public void testRoundtrip() throws Exception { } @Test - public void testBuild() throws Exception { + void testBuild() throws Exception { ClassicUploadStep step = new ClassicUploadStep(CREDENTIALS_ID, BUCKET_URI, new MockUploadModule(executor), "*.$BUILD_ID.txt"); FreeStyleProject project = jenkins.createFreeStyleProject("testBuild"); @@ -116,7 +122,7 @@ public void testBuild() throws Exception { } @Test - public void testInvalidCredentials() throws Exception { + void testInvalidCredentials() throws Exception { ClassicUploadStep step = new ClassicUploadStep("bad-credentials", BUCKET_URI, new MockUploadModule(executor), "*.$BUILD_ID.txt"); FreeStyleProject project = jenkins.createFreeStyleProject("testBuild"); @@ -139,7 +145,7 @@ public void testInvalidCredentials() throws Exception { return; } // Expected exception to happen. - assertTrue(false); + fail(); } private static final String PROJECT_ID = "foo.com:project-build"; diff --git a/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadTest.java b/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadTest.java index 92dd97cd..bc425084 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/ClassicUploadTest.java @@ -15,9 +15,10 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -35,20 +36,25 @@ import hudson.util.FormValidation; import java.io.BufferedReader; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Verifier; +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.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ClassicUpload}. */ -public class ClassicUploadTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ClassicUploadTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -84,18 +90,9 @@ public MockExecutor newExecutor() { private final MockExecutor executor; } - @Rule - public Verifier verifySawAll = new Verifier() { - @Override - public void verify() { - assertTrue(executor.sawAll()); - assertFalse(executor.sawUnexpected()); - } - }; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -124,15 +121,21 @@ public void setUp() throws Exception { bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */); } + @AfterEach + void afterEach() { + assertTrue(executor.sawAll()); + assertFalse(executor.sawUnexpected()); + } + @Test @WithoutJenkins - public void testGetters() { + void testGetters() { assertEquals(glob, underTest.getPattern()); } @Test @WithoutJenkins - public void testLegacyArgs() { + void testLegacyArgs() { ClassicUpload legacyVersion = new ClassicUpload(null /* bucket */, new MockUploadModule(executor), null /* glob */, bucket, glob); legacyVersion.setSharedPublicly(sharedPublicly); @@ -146,21 +149,24 @@ public void testLegacyArgs() { assertEquals(underTest.getPattern(), legacyVersion.getPattern()); } - @Test(expected = NullPointerException.class) + @Test @WithoutJenkins - public void testCheckNullGlob() throws Exception { - new ClassicUpload(bucket, new MockUploadModule(executor), null, null /* legacy arg */, null /* legacy arg */); + void testCheckNullGlob() { + assertThrows( + NullPointerException.class, + () -> new ClassicUpload( + bucket, new MockUploadModule(executor), null, null /* legacy arg */, null /* legacy arg */)); } @Test - public void testCheckNullOnNullables() throws Exception { + void testCheckNullOnNullables() { // The upload should handle null for the other fields. new ClassicUpload(bucket, null /* module */, glob, null /* legacy arg */, null /* legacy arg */); } @Test @WithoutJenkins - public void doCheckGlobTest() throws IOException { + void doCheckGlobTest() { DescriptorImpl descriptor = new DescriptorImpl(); assertEquals(FormValidation.Kind.OK, descriptor.doCheckPattern("asdf").kind); diff --git a/src/test/java/com/google/jenkins/plugins/storage/DownloadStepTest.java b/src/test/java/com/google/jenkins/plugins/storage/DownloadStepTest.java index 8170f4b0..0674ccbe 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/DownloadStepTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/DownloadStepTest.java @@ -15,11 +15,11 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -35,29 +35,36 @@ import hudson.FilePath; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; -import hudson.util.IOUtils; +import java.io.File; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.apache.commons.io.IOUtils; +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.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link AbstractUpload}. */ -public class DownloadStepTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DownloadStepTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; - @Rule - public TemporaryFolder tempDir = new TemporaryFolder(); + @TempDir + private File tempDir; @Mock private GoogleRobotCredentials credentials; @@ -66,9 +73,9 @@ public class DownloadStepTest { private final MockExecutor executor = new MockExecutor(); - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -91,7 +98,7 @@ private void ConfigurationRoundTripTest(DownloadStep s) throws Exception { } @Test - public void testRoundtrip() throws Exception { + void testRoundtrip() throws Exception { DownloadStep step = new DownloadStep(CREDENTIALS_ID, "bucket", "Dir", new MockUploadModule(executor)); ConfigurationRoundTripTest(step); @@ -100,7 +107,7 @@ public void testRoundtrip() throws Exception { } @Test - public void testBuild() throws Exception { + void testBuild() throws Exception { MockUploadModule module = new MockUploadModule(executor); DownloadStep step = new DownloadStep(CREDENTIALS_ID, "gs://bucket/path/to/object.txt", "", module); FreeStyleProject project = jenkins.createFreeStyleProject("testBuild"); @@ -111,7 +118,7 @@ public void testBuild() throws Exception { objToGet.setName("path/to/obj.txt"); executor.when(Storage.Objects.Get.class, objToGet, MockUploadModule.checkGetObject("path/to/object.txt")); - module.addNextMedia(IOUtils.toInputStream("test", "UTF-8")); + module.addNextMedia(IOUtils.toInputStream("test", StandardCharsets.UTF_8)); project.getBuildersList().add(step); FreeStyleBuild build = jenkins.buildAndAssertSuccess(project); @@ -122,7 +129,7 @@ public void testBuild() throws Exception { } @Test - public void testBuildPrefix() throws Exception { + void testBuildPrefix() throws Exception { MockUploadModule module = new MockUploadModule(executor); DownloadStep step = new DownloadStep(CREDENTIALS_ID, "gs://bucket/path/to/object.txt", "subPath", module); step.setPathPrefix("path/to/"); @@ -134,7 +141,7 @@ public void testBuildPrefix() throws Exception { objToGet.setName("path/to/obj.txt"); executor.when(Storage.Objects.Get.class, objToGet, MockUploadModule.checkGetObject("path/to/object.txt")); - module.addNextMedia(IOUtils.toInputStream("test", "UTF-8")); + module.addNextMedia(IOUtils.toInputStream("test", StandardCharsets.UTF_8)); project.getBuildersList().add(step); FreeStyleBuild build = jenkins.buildAndAssertSuccess(project); @@ -145,7 +152,7 @@ public void testBuildPrefix() throws Exception { } @Test - public void testBuildMoreComplex() throws Exception { + void testBuildMoreComplex() throws Exception { MockUploadModule module = new MockUploadModule(executor); DownloadStep step = new DownloadStep( CREDENTIALS_ID, "gs://bucket/download/$BUILD_ID/path/$BUILD_ID/test_$BUILD_ID.txt", "output", module); @@ -159,7 +166,7 @@ public void testBuildMoreComplex() throws Exception { executor.when( Storage.Objects.Get.class, objToGet, MockUploadModule.checkGetObject("download/1/path/1/test_1.txt")); - module.addNextMedia(IOUtils.toInputStream("contents 1", "UTF-8")); + module.addNextMedia(IOUtils.toInputStream("contents 1", StandardCharsets.UTF_8)); project.getBuildersList().add(step); FreeStyleBuild build = jenkins.buildAndAssertSuccess(project); @@ -181,15 +188,15 @@ private void checkSplitException(String s) { @Test @WithoutJenkins - public void testSplit() throws Exception { - assertArrayEquals(DownloadStep.split("a"), new String[] {"a"}); + void testSplit() throws Exception { + assertArrayEquals(new String[] {"a"}, DownloadStep.split("a")); assertArrayEquals( - DownloadStep.split("asdjfkl2358/9/8024@#$@%^$#^#"), new String[] {"asdjfkl2358/9/8024@#$@%^$#^#"}); + new String[] {"asdjfkl2358/9/8024@#$@%^$#^#"}, DownloadStep.split("asdjfkl2358/9/8024@#$@%^$#^#")); - assertArrayEquals(DownloadStep.split("a*"), new String[] {"a", ""}); - assertArrayEquals(DownloadStep.split("*"), new String[] {"", ""}); + assertArrayEquals(new String[] {"a", ""}, DownloadStep.split("a*")); + assertArrayEquals(new String[] {"", ""}, DownloadStep.split("*")); - assertArrayEquals(DownloadStep.split("pre-*-post"), new String[] {"pre-", "-post"}); + assertArrayEquals(new String[] {"pre-", "-post"}, DownloadStep.split("pre-*-post")); // Not yet supported checkSplitException("**"); @@ -206,14 +213,14 @@ public void testSplit() throws Exception { */ private Objects createObjects(String prefix, List names) { Objects o = new Objects(); - List items = new ArrayList(); - Set prefixes = new HashSet(); + List items = new ArrayList<>(); + Set prefixes = new HashSet<>(); for (String s : names) { if (!s.startsWith(prefix)) { continue; } - String subdirectory[] = s.substring(prefix.length()).split("/"); + String[] subdirectory = s.substring(prefix.length()).split("/"); if (subdirectory.length > 1) { // This object is nested deeper. Add a subdirectory prefixes.add(prefix + subdirectory[0]); @@ -226,7 +233,7 @@ private Objects createObjects(String prefix, List names) { } } o.setItems(items); - o.setPrefixes(new ArrayList(prefixes)); + o.setPrefixes(new ArrayList<>(prefixes)); return o; } @@ -236,7 +243,7 @@ public void tryWildcards(String uriPostfix, String[] matches, String[] notMatche FreeStyleProject project = jenkins.createFreeStyleProject("testBuild"); - final List objectNames = new ArrayList(); + final List objectNames = new ArrayList<>(); objectNames.addAll(Arrays.asList(matches)); objectNames.addAll(Arrays.asList(notMatches)); @@ -255,7 +262,7 @@ public void tryWildcards(String uriPostfix, String[] matches, String[] notMatche // ensure module has enough streams. Since the order in which they // will be queries is undefined, we will not attempt to verify // which one belongs to which. - module.addNextMedia(IOUtils.toInputStream("contents 1", "UTF-8")); + module.addNextMedia(IOUtils.toInputStream("contents 1", StandardCharsets.UTF_8)); } // Stub out the response from the Cloud @@ -271,12 +278,12 @@ public void tryWildcards(String uriPostfix, String[] matches, String[] notMatche } for (String s : notMatches) { FilePath result = build.getWorkspace().withSuffix("/" + s); - assertFalse("File exists but shouldn't:" + result, result.exists()); + assertFalse(result.exists(), "File exists but shouldn't:" + result); } } @Test - public void testBuildWildcards() throws Exception { + void testBuildWildcards() throws Exception { tryWildcards( "download/log_*.txt", new String[] { @@ -288,12 +295,12 @@ public void testBuildWildcards() throws Exception { } @Test - public void testBuildWildcardsOnly() throws Exception { + void testBuildWildcardsOnly() throws Exception { tryWildcards("*", new String[] {"a", "b.txt", "l_a_b_d_f"}, new String[] {"a/b.txt", "/b"}); } @Test - public void testBuildWildcardEnd() throws Exception { + void testBuildWildcardEnd() throws Exception { tryWildcards("a/*", new String[] {"a/a.txt", "a/b.txt", "a/log"}, new String[] {"a/b/c.txt"}); } diff --git a/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerStepTest.java b/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerStepTest.java index d73114a4..4b28bd1b 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerStepTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerStepTest.java @@ -28,17 +28,23 @@ import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.TaskListener; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ExpiringBucketLifecycleManagerStep} */ -public class ExpiringBucketLifecycleManagerStepTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ExpiringBucketLifecycleManagerStepTest { + + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -46,16 +52,16 @@ public class ExpiringBucketLifecycleManagerStepTest { private GoogleCredential credential; private final MockExecutor executor = new MockExecutor(); - private NotFoundException notFoundException = new NotFoundException(); + private final NotFoundException notFoundException = new NotFoundException(); private static final String PROJECT_ID = "foo.com:project-build"; private static final String CREDENTIALS_ID = "creds"; private static final String BUCKET_NAME = "test-bucket-43"; private static final String BUCKET_URI = "gs://" + BUCKET_NAME; private static final int TTL = 1; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -76,14 +82,14 @@ private void ConfigurationRoundTripTest(ExpiringBucketLifecycleManagerStep s) th } @Test - public void testRoundtrip() throws Exception { + void testRoundtrip() throws Exception { ExpiringBucketLifecycleManagerStep step = new ExpiringBucketLifecycleManagerStep(CREDENTIALS_ID, "bucket", 1); ConfigurationRoundTripTest(step); } @Test - public void testBuild() throws Exception { + void testBuild() throws Exception { ExpiringBucketLifecycleManagerStep step = new ExpiringBucketLifecycleManagerStep(CREDENTIALS_ID, BUCKET_URI, TTL); FreeStyleProject project = jenkins.createFreeStyleProject("testBuild"); diff --git a/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerTest.java b/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerTest.java index 8d3295e4..8f783249 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/ExpiringBucketLifecycleManagerTest.java @@ -15,10 +15,10 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -38,19 +38,25 @@ import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.TaskListener; -import org.junit.Before; -import org.junit.Test; -import org.junit.rules.Verifier; +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.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link ExpiringBucketLifecycleManager}. */ -public class ExpiringBucketLifecycleManagerTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ExpiringBucketLifecycleManagerTest { - @org.junit.Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -65,15 +71,12 @@ public class ExpiringBucketLifecycleManagerTest { private NotFoundException notFoundException; private Predicate checkHasOneRuleLifecycle() { - return new Predicate() { - @Override - public boolean apply(Storage.Buckets.Update operation) { - Bucket bucket = (Bucket) operation.getJsonContent(); - assertNotNull(bucket.getLifecycle()); - assertNotNull(bucket.getLifecycle().getRule()); - assertEquals(1, bucket.getLifecycle().getRule().size()); - return true; - } + return operation -> { + Bucket bucket = (Bucket) operation.getJsonContent(); + assertNotNull(bucket.getLifecycle()); + assertNotNull(bucket.getLifecycle().getRule()); + assertEquals(1, bucket.getLifecycle().getRule().size()); + return true; }; } @@ -90,21 +93,12 @@ public MockExecutor newExecutor() { private final MockExecutor executor; } - @org.junit.Rule - public Verifier verifySawAll = new Verifier() { - @Override - public void verify() { - assertTrue(executor.sawAll()); - assertFalse(executor.sawUnexpected()); - } - }; - private FreeStyleProject project; private FreeStyleBuild build; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -135,16 +129,22 @@ public void setUp() throws Exception { BUCKET_URI, new MockUploadModule(executor), TTL, null /* legacy arg */, null /* legacy arg */); } + @AfterEach + void afterEach() { + assertTrue(executor.sawAll()); + assertFalse(executor.sawUnexpected()); + } + @Test @WithoutJenkins - public void testGetters() { + void testGetters() { assertEquals(BUCKET_URI, underTest.getBucket()); assertEquals(TTL, underTest.getTtl()); } @Test @WithoutJenkins - public void testGettersWithLegacy() { + void testGettersWithLegacy() { underTest = new ExpiringBucketLifecycleManager( null /* bucket */, new MockUploadModule(executor), null /* ttl */, BUCKET_URI, TTL); assertEquals(BUCKET_URI, underTest.getBucket()); @@ -152,7 +152,7 @@ public void testGettersWithLegacy() { } @Test - public void testFailingCheckWithAnnotation() throws Exception { + void testFailingCheckWithAnnotation() throws Exception { final Bucket bucket = new Bucket().setName(BUCKET_NAME); // A get that returns a bucket should trigger a check/decorate/update @@ -163,7 +163,7 @@ public void testFailingCheckWithAnnotation() throws Exception { } @Test - public void testBadTTLWithUpdate() throws Exception { + void testBadTTLWithUpdate() throws Exception { final Bucket bucket = new Bucket() .setName(BUCKET_NAME) .setLifecycle(new Bucket.Lifecycle() @@ -179,7 +179,7 @@ public void testBadTTLWithUpdate() throws Exception { } @Test - public void testReplaceComplexLifecycle() throws Exception { + void testReplaceComplexLifecycle() throws Exception { final Rule expireGoodTTL = new Rule() .setCondition(new Rule.Condition().setAge(TTL)) .setAction(new Rule.Action().setType("Delete")); @@ -199,7 +199,7 @@ public void testReplaceComplexLifecycle() throws Exception { } @Test - public void testBadAction() throws Exception { + void testBadAction() throws Exception { final Bucket bucket = new Bucket() .setName(BUCKET_NAME) .setLifecycle(new Bucket.Lifecycle() @@ -215,7 +215,7 @@ public void testBadAction() throws Exception { } @Test - public void testBadCondition() throws Exception { + void testBadCondition() throws Exception { final Bucket bucket = new Bucket() .setName(BUCKET_NAME) .setLifecycle(new Bucket.Lifecycle() @@ -231,7 +231,7 @@ public void testBadCondition() throws Exception { } @Test - public void testBadComplexCondition() throws Exception { + void testBadComplexCondition() throws Exception { final Bucket bucket = new Bucket() .setName(BUCKET_NAME) .setLifecycle(new Bucket.Lifecycle() @@ -247,7 +247,7 @@ public void testBadComplexCondition() throws Exception { } @Test - public void testPassingCheck() throws Exception { + void testPassingCheck() throws Exception { final Bucket bucket = new Bucket() .setName(BUCKET_NAME) .setLifecycle(new Bucket.Lifecycle() diff --git a/src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java b/src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java index fffaacb6..62b0e60d 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java @@ -16,15 +16,16 @@ package com.google.jenkins.plugins.storage; import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -53,22 +54,27 @@ import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.SystemUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Verifier; +import org.junit.jupiter.api.AfterEach; +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.jvnet.hudson.test.FailureBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link GoogleCloudStorageUploader}. */ -public class GoogleCloudStorageUploaderTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class GoogleCloudStorageUploaderTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -115,19 +121,10 @@ public MockExecutor newExecutor() { private final MockExecutor executor; } - @Rule - public Verifier verifySawAll = new Verifier() { - @Override - public void verify() { - assertTrue(executor.sawAll()); - assertFalse(executor.sawUnexpected()); - } - }; - /** * Checks that any object insertion that we do has certain properties at the point of execution. */ - private Predicate checkFieldsMatch = new Predicate() { + private final Predicate checkFieldsMatch = new Predicate<>() { public boolean apply(Storage.Objects.Insert insertion) { assertNotNull(insertion.getMediaHttpUploader()); assertEquals(bucket.substring(GCS_SCHEME.length()), insertion.getBucket()); @@ -143,14 +140,14 @@ public boolean apply(Storage.Objects.Insert insertion) { } }; - @BeforeClass - public static void init() { + @BeforeAll + static void beforeAll() { assumeFalse(SystemUtils.IS_OS_WINDOWS); } - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -177,33 +174,38 @@ public void setUp() throws Exception { glob = "bar.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(new ClassicUpload( + ImmutableList.of(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg*/, null /* legacy arg */))); } + @AfterEach + void afterEach() { + assertTrue(executor.sawAll()); + assertFalse(executor.sawUnexpected()); + } + @Test @WithoutJenkins - public void testGetters() { + void testGetters() { assertEquals(CREDENTIALS_ID, underTest.getCredentialsId()); assertEquals(1, underTest.getUploads().size()); } - @Test(expected = NullPointerException.class) + @Test @WithoutJenkins - public void testCheckNull() throws Exception { - new GoogleCloudStorageUploader(null, ImmutableList.of()); + void testCheckNull() { + assertThrows(NullPointerException.class, () -> new GoogleCloudStorageUploader(null, ImmutableList.of())); } @Test @WithoutJenkins - public void testCheckNullOnNullables() throws Exception { + void testCheckNullOnNullables() { // The uploader should handle null for the other fields. new GoogleCloudStorageUploader("", null); } - @SuppressWarnings("unchecked") @Test - public void testFilePlain() throws Exception { + void testFilePlain() throws Exception { project.getBuildersList().add(new Shell("echo foo > bar.txt")); project.getPublishersList().add(underTest); @@ -217,9 +219,8 @@ public void testFilePlain() throws Exception { assertEquals(Result.SUCCESS, build.getResult()); } - @SuppressWarnings("unchecked") @Test - public void testFilePlain_uploadFailed() throws Exception { + void testFilePlain_uploadFailed() throws Exception { project.getBuildersList().add(new Shell("echo foo > bar.txt")); project.getPublishersList().add(underTest); @@ -232,11 +233,11 @@ public void testFilePlain_uploadFailed() throws Exception { } @Test - public void testBadBucket() throws Exception { + void testBadBucket() throws Exception { bucket = "bucket"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > bar.txt")); @@ -248,7 +249,7 @@ public void testBadBucket() throws Exception { } @Test - public void testNoFileFailure() throws Exception { + void testNoFileFailure() throws Exception { project.getBuildersList().add(new Shell("echo foo > foo.txt")); project.getPublishersList().add(underTest); @@ -263,7 +264,7 @@ public void testNoFileFailure() throws Exception { } @Test - public void testFilePlainWithFailure() throws Exception { + void testFilePlainWithFailure() throws Exception { project.getBuildersList().add(new Shell("echo foo > bar.txt")); // Fail the build to show that the uploader does nothing. project.getBuildersList().add(new FailureBuilder()); @@ -275,12 +276,12 @@ public void testFilePlainWithFailure() throws Exception { } @Test - public void testFilePlainWithFailureAndUpload() throws Exception { + void testFilePlainWithFailureAndUpload() throws Exception { forFailedJobs = true; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > bar.txt")); @@ -298,10 +299,10 @@ public void testFilePlainWithFailureAndUpload() throws Exception { } @Test - public void testStdoutUpload() throws Exception { + void testStdoutUpload() throws Exception { underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new StdoutUpload( + ImmutableList.of(setOptionalParams(new StdoutUpload( bucket, new MockUploadModule(executor), "build-log.txt", null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo Hello World!")); @@ -317,11 +318,11 @@ public void testStdoutUpload() throws Exception { } @Test - public void testFileGlob() throws Exception { + void testFileGlob() throws Exception { glob = "*.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > bar.txt")); @@ -337,12 +338,12 @@ public void testFileGlob() throws Exception { } @Test - public void testAbsolutePath() throws Exception { + void testAbsolutePath() throws Exception { String absoluteFilePath = "/tmp/bar.txt"; glob = absoluteFilePath; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > " + absoluteFilePath)); @@ -358,13 +359,13 @@ public void testAbsolutePath() throws Exception { } @Test - public void testAbsoluteGlob() throws Exception { + void testAbsoluteGlob() throws Exception { String absoluteFilePath1 = "/tmp/bar.1.txt"; String absoluteFilePath2 = "/tmp/bar.2.txt"; glob = "/tmp/bar.*.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > " + absoluteFilePath1)); @@ -382,11 +383,11 @@ public void testAbsoluteGlob() throws Exception { } @Test - public void testFileWithVar() throws Exception { + void testFileWithVar() throws Exception { glob = "bar.$BUILD_NUMBER.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > bar.$BUILD_NUMBER.txt")); @@ -402,11 +403,11 @@ public void testFileWithVar() throws Exception { } @Test - public void testFileWithDir() throws Exception { + void testFileWithDir() throws Exception { glob = "blah/bar.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("mkdir blah; echo foo > blah/bar.txt")); @@ -422,11 +423,11 @@ public void testFileWithDir() throws Exception { } @Test - public void testFileWithRecursiveGlob() throws Exception { + void testFileWithRecursiveGlob() throws Exception { glob = "**/*.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("mkdir blah; echo foo > blah/bar.txt")); @@ -442,11 +443,11 @@ public void testFileWithRecursiveGlob() throws Exception { } @Test - public void testMultiFileGlob() throws Exception { + void testMultiFileGlob() throws Exception { glob = "*.txt"; underTest = new GoogleCloudStorageUploader( CREDENTIALS_ID, - ImmutableList.of(setOptionalParams(new ClassicUpload( + ImmutableList.of(setOptionalParams(new ClassicUpload( bucket, new MockUploadModule(executor), glob, null /* legacy arg */, null /* legacy arg */)))); project.getBuildersList().add(new Shell("echo foo > foo.txt; echo bar > bar.txt")); @@ -464,14 +465,14 @@ public void testMultiFileGlob() throws Exception { @Test @WithoutJenkins - public void testDescriptor() { + void testDescriptor() { DescriptorImpl descriptor = new DescriptorImpl(); assertTrue(descriptor.isApplicable(AbstractProject.class)); assertEquals(Messages.GoogleCloudStorageUploader_DisplayName(), descriptor.getDisplayName()); } @Test - public void testGetDefaultUploads() { + void testGetDefaultUploads() { DescriptorImpl descriptor = new DescriptorImpl(); List defaultUploads = descriptor.getDefaultUploads(); assertEquals(1, defaultUploads.size()); diff --git a/src/test/java/com/google/jenkins/plugins/storage/HttpHeadersTest.java b/src/test/java/com/google/jenkins/plugins/storage/HttpHeadersTest.java index b524f228..94773190 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/HttpHeadersTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/HttpHeadersTest.java @@ -15,15 +15,15 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link HttpHeaders}. */ -public class HttpHeadersTest { +class HttpHeadersTest { @Test - public void testGetContentDisposition_ascii() { + void testGetContentDisposition_ascii() { assertEquals( "attachment; filename=\"myapp.war\"; filename*=UTF-8''myapp.war", HttpHeaders.getContentDisposition("myapp.war", false)); @@ -34,42 +34,42 @@ public void testGetContentDisposition_ascii() { } @Test - public void testGetContentDisposition_asciiInline() { + void testGetContentDisposition_asciiInline() { assertEquals( "inline; filename=\"build-log.txt\"; filename*=UTF-8''build-log.txt", HttpHeaders.getContentDisposition("build-log.txt", true)); } @Test - public void testGetContentDisposition_unicodeBmp() { + void testGetContentDisposition_unicodeBmp() { assertEquals( "attachment; filename=\"snowman _.txt\"; " + "filename*=UTF-8''snowman%20%E2%98%83.txt", HttpHeaders.getContentDisposition("snowman ☃.txt", false)); } @Test - public void testGetContentDisposition_unicodeNonBmp() { + void testGetContentDisposition_unicodeNonBmp() { assertEquals( "attachment; filename=\"_.zip\"; filename*=UTF-8''%F0%9D%92%9E.zip", HttpHeaders.getContentDisposition("𝒞.zip", false)); } @Test - public void testGetContentDisposition_rfc2616Escapes() { + void testGetContentDisposition_rfc2616Escapes() { assertEquals( "attachment; filename=\"-\\\\-\\\"-\"; filename*=UTF-8''-%5C-%22-", HttpHeaders.getContentDisposition("-\\-\"-", false)); } @Test - public void testGetContentDisposition_rfc5987IdentitySymbols() { + void testGetContentDisposition_rfc5987IdentitySymbols() { assertEquals( "attachment; filename=\"!#$&+-.^_`|~\"; filename*=UTF-8''!#$&+-.^_`|~", HttpHeaders.getContentDisposition("!#$&+-.^_`|~", false)); } @Test - public void testGetContentDisposition_rfc5987PercentEncodedSymbols() { + void testGetContentDisposition_rfc5987PercentEncodedSymbols() { assertEquals( "attachment; filename=\"@%*()=[]{}\\\\:;\\\"'<>,/?\"; " + "filename*=UTF-8''%40%25%2A%28%29%3D%5B%5D%7B%7D%5C%3A%3B%22%27" diff --git a/src/test/java/com/google/jenkins/plugins/storage/MockUploadModule.java b/src/test/java/com/google/jenkins/plugins/storage/MockUploadModule.java index d334cf1b..7596b276 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/MockUploadModule.java +++ b/src/test/java/com/google/jenkins/plugins/storage/MockUploadModule.java @@ -16,7 +16,7 @@ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.services.storage.Storage; import com.google.api.services.storage.Storage.Objects.Get; @@ -24,9 +24,9 @@ import com.google.api.services.storage.model.StorageObject; import com.google.common.base.Predicate; import com.google.jenkins.plugins.util.MockExecutor; -import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; +import org.junit.jupiter.api.Assertions; /** Mock upload module to stub out executor for testing. */ public class MockUploadModule extends UploadModule { @@ -53,48 +53,38 @@ public MockExecutor newExecutor() { private final int retryCount; public static Predicate checkObjectName(final String objectName) { - return new Predicate() { - @Override - public boolean apply(Storage.Objects.Insert operation) { - StorageObject object = (StorageObject) operation.getJsonContent(); - assertEquals(objectName, object.getName()); - return true; - } + return operation -> { + StorageObject object = (StorageObject) operation.getJsonContent(); + assertEquals(objectName, object.getName()); + return true; }; } public static Predicate checkGetObject(final String objectName) { - return new Predicate() { - @Override - public boolean apply(Storage.Objects.Get operation) { - assertEquals(objectName, operation.getObject()); - return true; - } + return operation -> { + Assertions.assertEquals(objectName, operation.getObject()); + return true; }; } public static Predicate checkBucketName(final String bucketName) { - return new Predicate() { - @Override - public boolean apply(Storage.Buckets.Insert operation) { - Bucket bucket = (Bucket) operation.getJsonContent(); - assertEquals(bucketName, bucket.getName()); - return true; - } + return operation -> { + Bucket bucket = (Bucket) operation.getJsonContent(); + assertEquals(bucketName, bucket.getName()); + return true; }; } - private final LinkedList mediaStreams = new LinkedList(); + private final LinkedList mediaStreams = new LinkedList<>(); public void addNextMedia(InputStream stream) { mediaStreams.add(stream); } - public InputStream executeMediaAsInputStream(Get getObject) throws IOException { + public InputStream executeMediaAsInputStream(Get getObject) { if (mediaStreams.isEmpty()) { return null; } return mediaStreams.remove(0); } } -; diff --git a/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadStepTest.java b/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadStepTest.java index 12ae7d25..3d8c99a4 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadStepTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadStepTest.java @@ -29,17 +29,23 @@ import hudson.model.FreeStyleProject; import hudson.model.TaskListener; import java.util.Optional; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link StdoutUploadStep} */ -public class StdoutUploadStepTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class StdoutUploadStepTest { + + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -47,16 +53,16 @@ public class StdoutUploadStepTest { private GoogleCredential credential; private final MockExecutor executor = new MockExecutor(); - private NotFoundException notFoundException = new NotFoundException(); + private final NotFoundException notFoundException = new NotFoundException(); private static final String PROJECT_ID = "foo.com:project-build"; private static final String CREDENTIALS_ID = "creds"; private static final String BUCKET_NAME = "test-bucket-43"; private static final String BUCKET_URI = "gs://" + BUCKET_NAME; private static final String LOG_NAME = "build-log.txt"; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -77,7 +83,7 @@ private void ConfigurationRoundTripTest(StdoutUploadStep s) throws Exception { } @Test - public void testRoundtrip() throws Exception { + void testRoundtrip() throws Exception { StdoutUploadStep step = new StdoutUploadStep(CREDENTIALS_ID, "bucket", "logName"); ConfigurationRoundTripTest(step); @@ -93,7 +99,7 @@ public void testRoundtrip() throws Exception { } @Test - public void testBuild() throws Exception { + void testBuild() throws Exception { StdoutUploadStep step = new StdoutUploadStep(CREDENTIALS_ID, BUCKET_URI, Optional.of(new MockUploadModule(executor)), LOG_NAME); diff --git a/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadTest.java b/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadTest.java index f4579945..50783cb4 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/StdoutUploadTest.java @@ -15,7 +15,7 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -31,19 +31,23 @@ import hudson.model.FreeStyleProject; import hudson.model.TaskListener; import hudson.util.FormValidation; -import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Unit test for {@link StdoutUpload} and friends. */ -public class StdoutUploadTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class StdoutUploadTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials credentials; @@ -57,9 +61,9 @@ public class StdoutUploadTest { private NotFoundException notFoundException; - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; when(credentials.getId()).thenReturn(CREDENTIALS_ID); when(credentials.getProjectId()).thenReturn(PROJECT_ID); @@ -85,7 +89,7 @@ public void setup() throws Exception { } @Test - public void doCheckLogNameTest() throws IOException { + void doCheckLogNameTest() { DescriptorImpl descriptor = new DescriptorImpl(); assertEquals(FormValidation.Kind.OK, descriptor.doCheckLogName("asdf").kind); @@ -98,7 +102,7 @@ public void doCheckLogNameTest() throws IOException { } @Test - public void doCheckLogNameExpansion() throws Exception { + void doCheckLogNameExpansion() throws Exception { StdoutUpload underTest = new StdoutUpload(BUCKET_URI, new MockUploadModule(executor), "build.$BUILD_NUMBER.log", null); diff --git a/src/test/java/com/google/jenkins/plugins/storage/UploadModuleTest.java b/src/test/java/com/google/jenkins/plugins/storage/UploadModuleTest.java index a543c8dc..f884ab2c 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/UploadModuleTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/UploadModuleTest.java @@ -15,7 +15,10 @@ */ package com.google.jenkins.plugins.storage; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; @@ -25,34 +28,34 @@ import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials; import java.io.IOException; import java.security.GeneralSecurityException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Tests for {@link UploadModule}. */ -public class UploadModuleTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UploadModuleTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); + private JenkinsRule jenkins; @Mock private GoogleRobotCredentials mockGoogleRobotCredentials; private UploadModule underTest; - GoogleCredential credential = new GoogleCredential(); + private final GoogleCredential credential = new GoogleCredential(); - @SuppressWarnings("serial") - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; underTest = new UploadModule(); when(mockGoogleRobotCredentials.getGoogleCredential(isA(GoogleOAuth2ScopeRequirement.class))) @@ -60,30 +63,30 @@ public void setup() throws Exception { } @Test - public void version_space() throws Exception { + void version_space() throws Exception { Storage storage = underTest.getStorageService(mockGoogleRobotCredentials, "0.14-SNAPSHOT (other details)"); - assertEquals(storage.getApplicationName(), "Jenkins-GCS-Plugin/0.14-SNAPSHOT"); + assertEquals("Jenkins-GCS-Plugin/0.14-SNAPSHOT", storage.getApplicationName()); } @Test - public void version_noSpace() throws Exception { + void version_noSpace() throws Exception { Storage storage = underTest.getStorageService(mockGoogleRobotCredentials, "v"); - assertEquals(storage.getApplicationName(), "Jenkins-GCS-Plugin/v"); + assertEquals("Jenkins-GCS-Plugin/v", storage.getApplicationName()); } @Test - public void version_none() throws Exception { + void version_none() throws Exception { Storage storage = underTest.getStorageService(mockGoogleRobotCredentials, ""); - assertEquals(storage.getApplicationName(), "Jenkins-GCS-Plugin"); + assertEquals("Jenkins-GCS-Plugin", storage.getApplicationName()); } @Test - public void newUploader_notRightScope() throws GeneralSecurityException, IOException, UploadException { + void newUploader_notRightScope() throws Exception { GeneralSecurityException ex = new GeneralSecurityException(); when(mockGoogleRobotCredentials.getGoogleCredential(isA(GoogleOAuth2ScopeRequirement.class))) .thenThrow(ex); - thrown.expect(IOException.class); - thrown.expectMessage(Messages.UploadModule_ExceptionStorageService()); - underTest.getStorageService(mockGoogleRobotCredentials, ""); + Throwable exception = + assertThrows(IOException.class, () -> underTest.getStorageService(mockGoogleRobotCredentials, "")); + assertThat(exception.getMessage(), containsString(Messages.UploadModule_ExceptionStorageService())); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/client/ClientFactoryTest.java b/src/test/java/com/google/jenkins/plugins/storage/client/ClientFactoryTest.java index d6fadf34..eb372df1 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/client/ClientFactoryTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/client/ClientFactoryTest.java @@ -15,8 +15,8 @@ */ package com.google.jenkins.plugins.storage.client; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; @@ -28,21 +28,27 @@ import com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig; import java.nio.charset.StandardCharsets; import java.util.Optional; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** Tests {@link ClientFactory}. */ -public class ClientFactoryTest { - public static final String ACCOUNT_ID = "test-account-id"; - public static final byte[] PK_BYTES = +@WithJenkins +class ClientFactoryTest { + private static final String ACCOUNT_ID = "test-account-id"; + private static final byte[] PK_BYTES = "{\"client_email\": \"example@example.com\"}".getBytes(StandardCharsets.UTF_8); - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Test - public void defaultTransport() throws Exception { + void defaultTransport() throws Exception { final String credentialId = "my-google-credential"; SecretBytes bytes = SecretBytes.fromBytes(PK_BYTES); diff --git a/src/test/java/com/google/jenkins/plugins/storage/client/StorageClientTest.java b/src/test/java/com/google/jenkins/plugins/storage/client/StorageClientTest.java index de16cdaa..76e46c15 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/client/StorageClientTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/client/StorageClientTest.java @@ -15,8 +15,9 @@ */ package com.google.jenkins.plugins.storage.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @@ -25,51 +26,57 @@ import com.google.api.services.storage.Storage; import java.io.IOException; import java.io.InputStream; -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.ArgumentMatchers; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; - -/** Tests {@link StorageClient}. */ -@RunWith(MockitoJUnitRunner.class) -public class StorageClientTest { +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +/** Tests {@link com.google.jenkins.plugins.storage.client.StorageClient}. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class StorageClientTest { private static final String TEST_BUCKET = "test-bucket"; private static final String TEST_PATTERN = "test-pattern"; private static final InputStreamContent TEST_CONTENT = new InputStreamContent("", Mockito.mock(InputStream.class)); - @Test(expected = IllegalArgumentException.class) - public void testInsertObjectErrorWithNullPattern() throws IOException { + @Test + void testInsertObjectErrorWithNullPattern() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.uploadToBucket(null, TEST_BUCKET, TEST_CONTENT); + assertThrows( + IllegalArgumentException.class, () -> storageClient.uploadToBucket(null, TEST_BUCKET, TEST_CONTENT)); } - @Test(expected = IllegalArgumentException.class) - public void testInsertObjectErrorWithNullBucket() throws IOException { + @Test + void testInsertObjectErrorWithNullBucket() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.uploadToBucket(TEST_PATTERN, null, TEST_CONTENT); + assertThrows( + IllegalArgumentException.class, () -> storageClient.uploadToBucket(TEST_PATTERN, null, TEST_CONTENT)); } - @Test(expected = NullPointerException.class) - public void testInsertObjectErrorWithNullContent() throws IOException { + @Test + void testInsertObjectErrorWithNullContent() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.uploadToBucket(TEST_PATTERN, TEST_BUCKET, null); + assertThrows(NullPointerException.class, () -> storageClient.uploadToBucket(TEST_PATTERN, TEST_BUCKET, null)); } - @Test(expected = IllegalArgumentException.class) - public void testInsertObjectErrorWithEmptyPattern() throws IOException { + @Test + void testInsertObjectErrorWithEmptyPattern() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.uploadToBucket("", TEST_BUCKET, TEST_CONTENT); + assertThrows(IllegalArgumentException.class, () -> storageClient.uploadToBucket("", TEST_BUCKET, TEST_CONTENT)); } - @Test(expected = IllegalArgumentException.class) - public void testInsertObjectErrorWithEmptyBucket() throws IOException { + @Test + void testInsertObjectErrorWithEmptyBucket() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.uploadToBucket(TEST_PATTERN, "", TEST_CONTENT); + assertThrows( + IllegalArgumentException.class, () -> storageClient.uploadToBucket(TEST_PATTERN, "", TEST_CONTENT)); } @Test - public void testInsertObjectReturnsCorrectly() throws IOException { + void testInsertObjectReturnsCorrectly() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); Storage.Objects.Insert insertRequest = storageClient.uploadToBucketRequest(TEST_PATTERN, TEST_BUCKET, TEST_CONTENT); @@ -77,52 +84,52 @@ public void testInsertObjectReturnsCorrectly() throws IOException { assertEquals(TEST_BUCKET, insertRequest.getBucket()); } - @Test(expected = IllegalArgumentException.class) - public void testDeleteObjectErrorWithNullPattern() throws IOException { + @Test + void testDeleteObjectErrorWithNullPattern() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.deleteFromBucket(TEST_BUCKET, null); + assertThrows(IllegalArgumentException.class, () -> storageClient.deleteFromBucket(TEST_BUCKET, null)); } - @Test(expected = IllegalArgumentException.class) - public void testDeleteObjectErrorWithNullBucket() throws IOException { + @Test + void testDeleteObjectErrorWithNullBucket() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.deleteFromBucket(null, TEST_PATTERN); + assertThrows(IllegalArgumentException.class, () -> storageClient.deleteFromBucket(null, TEST_PATTERN)); } - @Test(expected = IllegalArgumentException.class) - public void testDeleteObjectErrorWithEmptyPattern() throws IOException { + @Test + void testDeleteObjectErrorWithEmptyPattern() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.deleteFromBucket(TEST_BUCKET, ""); + assertThrows(IllegalArgumentException.class, () -> storageClient.deleteFromBucket(TEST_BUCKET, "")); } - @Test(expected = IllegalArgumentException.class) - public void testDeleteObjectErrorWithEmptyBucket() throws IOException { + @Test + void testDeleteObjectErrorWithEmptyBucket() throws IOException { StorageClient storageClient = setUpObjectInsertClient(); - storageClient.deleteFromBucket("", TEST_PATTERN); + assertThrows(IllegalArgumentException.class, () -> storageClient.deleteFromBucket("", TEST_PATTERN)); } @Test - public void testDeleteObjectReturnsCorrectly() throws IOException { + void testDeleteObjectReturnsCorrectly() throws IOException { StorageClient storageClient = setUpObjectDeleteClient(); Storage.Objects.Delete deleteRequest = storageClient.deleteFromBucketRequest(TEST_BUCKET, TEST_PATTERN); assertNotNull(deleteRequest); assertEquals(TEST_BUCKET, deleteRequest.getBucket()); } - @Test(expected = IllegalArgumentException.class) - public void testDeleteBucketErrorWithNullBucket() throws IOException { + @Test + void testDeleteBucketErrorWithNullBucket() throws IOException { StorageClient storageClient = setUpBucketDeleteClient(); - storageClient.deleteBucket(null); + assertThrows(IllegalArgumentException.class, () -> storageClient.deleteBucket(null)); } - @Test(expected = IllegalArgumentException.class) - public void testDeleteBucketErrorWithEmptyBucket() throws IOException { + @Test + void testDeleteBucketErrorWithEmptyBucket() throws IOException { StorageClient storageClient = setUpBucketDeleteClient(); - storageClient.deleteBucket(""); + assertThrows(IllegalArgumentException.class, () -> storageClient.deleteBucket("")); } @Test - public void testDeleteBucketReturnsCorrectly() throws IOException { + void testDeleteBucketReturnsCorrectly() throws IOException { StorageClient storageClient = setUpBucketDeleteClient(); Storage.Buckets.Delete deleteRequest = storageClient.deleteBucketRequest(TEST_BUCKET); assertNotNull(deleteRequest); diff --git a/src/test/java/com/google/jenkins/plugins/storage/integration/ClassicUploadStepPipelineIT.java b/src/test/java/com/google/jenkins/plugins/storage/integration/ClassicUploadStepPipelineIT.java index 8194e30e..33666a01 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/integration/ClassicUploadStepPipelineIT.java +++ b/src/test/java/com/google/jenkins/plugins/storage/integration/ClassicUploadStepPipelineIT.java @@ -20,8 +20,9 @@ import static com.google.jenkins.plugins.storage.integration.ITUtil.formatRandomName; import static com.google.jenkins.plugins.storage.integration.ITUtil.initializePipelineITEnvironment; import static com.google.jenkins.plugins.storage.integration.ITUtil.loadResource; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.google.jenkins.plugins.storage.ClassicUploadStep; import com.google.jenkins.plugins.storage.client.ClientFactory; import com.google.jenkins.plugins.storage.client.StorageClient; import hudson.EnvVars; @@ -30,18 +31,18 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** Tests the {@link ClassicUploadStep} for use-cases involving the Jenkins Pipeline DSL. */ -public class ClassicUploadStepPipelineIT { +@WithJenkins +class ClassicUploadStepPipelineIT { private static final Logger LOGGER = Logger.getLogger(ClassicUploadStepPipelineIT.class.getName()); - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); + private static JenkinsRule jenkinsRule; private static String credentialsId; private static final String pattern = "build_environment.txt"; @@ -49,10 +50,11 @@ public class ClassicUploadStepPipelineIT { private static StorageClient storageClient; private static EnvVars envVars; - @BeforeClass - public static void init() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule) throws Exception { LOGGER.info("Initializing ClassicUploadStepPipelineIT"); + jenkinsRule = rule; envVars = initializePipelineITEnvironment(pattern, jenkinsRule); credentialsId = envVars.get("CREDENTIALS_ID"); storageClient = new ClientFactory(jenkinsRule.jenkins, credentialsId).storageClient(); @@ -61,7 +63,7 @@ public static void init() throws Exception { } @Test - public void testClassicUploadStepSuccessful() throws Exception { + void testClassicUploadStepSuccessful() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition( @@ -74,7 +76,7 @@ public void testClassicUploadStepSuccessful() throws Exception { } @Test - public void testClassicUploadPostStepSuccessful() throws Exception { + void testClassicUploadPostStepSuccessful() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition( @@ -87,7 +89,7 @@ public void testClassicUploadPostStepSuccessful() throws Exception { } @Test - public void testMalformedClassicUploadStepFailure() throws Exception { + void testMalformedClassicUploadStepFailure() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition( @@ -98,8 +100,8 @@ public void testMalformedClassicUploadStepFailure() throws Exception { dumpLog(LOGGER, run); } - @AfterClass - public static void cleanUp() throws Exception { + @AfterAll + static void afterAll() throws Exception { storageClient.deleteBucket(bucket); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/integration/DownloadStepPipelineIT.java b/src/test/java/com/google/jenkins/plugins/storage/integration/DownloadStepPipelineIT.java index dbf844e9..00e59d96 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/integration/DownloadStepPipelineIT.java +++ b/src/test/java/com/google/jenkins/plugins/storage/integration/DownloadStepPipelineIT.java @@ -21,7 +21,7 @@ import static com.google.jenkins.plugins.storage.integration.ITUtil.getBucket; import static com.google.jenkins.plugins.storage.integration.ITUtil.initializePipelineITEnvironment; import static com.google.jenkins.plugins.storage.integration.ITUtil.loadResource; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.api.client.http.InputStreamContent; import com.google.jenkins.plugins.storage.DownloadStep; @@ -35,18 +35,18 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** Tests the {@link DownloadStep} for use-cases involving the Jenkins Pipeline DSL. */ -public class DownloadStepPipelineIT { +@WithJenkins +class DownloadStepPipelineIT { private static final Logger LOGGER = Logger.getLogger(DownloadStepPipelineIT.class.getName()); - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); + private static JenkinsRule jenkinsRule; private static String credentialsId; private static final String pattern = "downloadstep_test.txt"; @@ -54,10 +54,11 @@ public class DownloadStepPipelineIT { private static StorageClient storageClient; private static EnvVars envVars; - @BeforeClass - public static void init() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule) throws Exception { LOGGER.info("Initializing DownloadStepPipelineIT"); + jenkinsRule = rule; envVars = initializePipelineITEnvironment(pattern, jenkinsRule); credentialsId = envVars.get("CREDENTIALS_ID"); storageClient = new ClientFactory(jenkinsRule.jenkins, credentialsId).storageClient(); @@ -71,7 +72,7 @@ public static void init() throws Exception { } @Test - public void testDownloadStepSuccessful() throws Exception { + void testDownloadStepSuccessful() throws Exception { String jobName = formatRandomName("test"); envVars.put("DIR", jobName); WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, jobName); @@ -83,7 +84,7 @@ public void testDownloadStepSuccessful() throws Exception { } @Test - public void testMalformedDownloadStepFailure() throws Exception { + void testMalformedDownloadStepFailure() throws Exception { String jobName = formatRandomName("test"); WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, jobName); envVars.put("DIR", jobName); @@ -95,8 +96,8 @@ public void testMalformedDownloadStepFailure() throws Exception { dumpLog(LOGGER, run); } - @AfterClass - public static void cleanUp() throws Exception { + @AfterAll + static void afterAll() throws Exception { storageClient.deleteFromBucket(bucket, pattern); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/integration/ExpiringBucketLifeCycleManagerIT.java b/src/test/java/com/google/jenkins/plugins/storage/integration/ExpiringBucketLifeCycleManagerIT.java index 0a68696f..e0ee6b11 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/integration/ExpiringBucketLifeCycleManagerIT.java +++ b/src/test/java/com/google/jenkins/plugins/storage/integration/ExpiringBucketLifeCycleManagerIT.java @@ -19,7 +19,7 @@ import static com.google.jenkins.plugins.storage.integration.ITUtil.formatRandomName; import static com.google.jenkins.plugins.storage.integration.ITUtil.initializePipelineITEnvironment; import static com.google.jenkins.plugins.storage.integration.ITUtil.loadResource; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.jenkins.plugins.storage.client.ClientFactory; import com.google.jenkins.plugins.storage.client.StorageClient; @@ -29,17 +29,17 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class ExpiringBucketLifeCycleManagerIT { - private static final Logger LOGGER = Logger.getLogger(ClassicUploadStepPipelineIT.class.getName()); +@WithJenkins +class ExpiringBucketLifeCycleManagerIT { + private static final Logger LOGGER = Logger.getLogger(ExpiringBucketLifeCycleManagerIT.class.getName()); - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); + private static JenkinsRule jenkinsRule; private static String credentialsId; // This IT does not need to make explicit use of pattern. @@ -48,10 +48,11 @@ public class ExpiringBucketLifeCycleManagerIT { private static StorageClient storageClient; private static EnvVars envVars; - @BeforeClass - public static void init() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule) throws Exception { LOGGER.info("Initializing ExpiringBucketLifeCycleManagerIT"); + jenkinsRule = rule; envVars = initializePipelineITEnvironment(pattern, jenkinsRule); credentialsId = envVars.get("CREDENTIALS_ID"); storageClient = new ClientFactory(jenkinsRule.jenkins, credentialsId).storageClient(); @@ -61,7 +62,7 @@ public static void init() throws Exception { } @Test - public void testClassicUploadStepSuccessful() throws Exception { + void testClassicUploadStepSuccessful() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition(new CpsFlowDefinition( @@ -73,7 +74,7 @@ public void testClassicUploadStepSuccessful() throws Exception { } @Test - public void testMalformedClassicUploadStepFailure() throws Exception { + void testMalformedClassicUploadStepFailure() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition(new CpsFlowDefinition( @@ -84,8 +85,8 @@ public void testMalformedClassicUploadStepFailure() throws Exception { dumpLog(LOGGER, run); } - @AfterClass - public static void cleanUp() throws Exception { + @AfterAll + static void afterAll() throws Exception { storageClient.deleteBucket(bucket); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/integration/ITUtil.java b/src/test/java/com/google/jenkins/plugins/storage/integration/ITUtil.java index 9d198f84..b2a50e41 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/integration/ITUtil.java +++ b/src/test/java/com/google/jenkins/plugins/storage/integration/ITUtil.java @@ -16,7 +16,7 @@ package com.google.jenkins.plugins.storage.integration; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; @@ -40,8 +40,8 @@ /** Provides a library of utility functions for integration tests. */ public class ITUtil { - private static String projectId = System.getenv("GOOGLE_PROJECT_ID"); - private static String bucket = System.getenv("GOOGLE_BUCKET"); + private static final String PROJECT_ID = System.getenv("GOOGLE_PROJECT_ID"); + private static final String BUCKET = System.getenv("GOOGLE_BUCKET"); // DEV MEMO: // In previous versions of google-oauth-plugin, the credentialId was actually the projectId, @@ -70,7 +70,7 @@ static String formatRandomName(String prefix) { * @return The contents of the loaded resource. * @throws IOException If an error occurred during loading. */ - static String loadResource(Class testClass, String name) throws IOException { + static String loadResource(Class testClass, String name) throws IOException { return new String(IOUtils.toByteArray(testClass.getResourceAsStream(name))); } @@ -83,14 +83,14 @@ static String loadResource(Class testClass, String name) throws IOException { */ static void dumpLog(Logger logger, Run run) throws IOException { BufferedReader reader = new BufferedReader(run.getLogReader()); - String line = null; + String line; while ((line = reader.readLine()) != null) { logger.info(line); } } static String getBucket() { - return bucket; + return BUCKET; } /** @@ -102,15 +102,15 @@ static String getBucket() { * @throws Exception If there was an issue initializing or storing credentials. */ static EnvVars initializePipelineITEnvironment(String pattern, JenkinsRule jenkinsRule) throws Exception { - assertNotNull("GOOGLE_PROJECT_ID env var must be set", projectId); + assertNotNull(PROJECT_ID, "GOOGLE_PROJECT_ID env var must be set"); // This bucket is only used for DownloadStepPipelineIT to download objects from. - assertNotNull("GOOGLE_BUCKET env var must be set", bucket); + assertNotNull(BUCKET, "GOOGLE_BUCKET env var must be set"); String serviceAccountKeyJson = System.getenv("GOOGLE_CREDENTIALS"); - assertNotNull("GOOGLE_CREDENTIALS env var must be set", serviceAccountKeyJson); + assertNotNull(serviceAccountKeyJson, "GOOGLE_CREDENTIALS env var must be set"); Preconditions.checkArgument(!Strings.isNullOrEmpty(pattern)); if (credentialId == null || credentialId.isEmpty()) { - credentialId = projectId; + credentialId = PROJECT_ID; } SecretBytes secretBytes = SecretBytes.fromBytes(serviceAccountKeyJson.getBytes(StandardCharsets.UTF_8)); @@ -118,7 +118,7 @@ static EnvVars initializePipelineITEnvironment(String pattern, JenkinsRule jenki sac.setSecretJsonKey(secretBytes); GoogleRobotPrivateKeyCredentials c = - new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, credentialId, projectId, sac, null); + new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, credentialId, PROJECT_ID, sac, null); CredentialsStore store = new SystemCredentialsProvider.ProviderImpl().getStore(jenkinsRule.jenkins); assertNotNull(store); store.addCredentials(Domain.global(), c); @@ -126,7 +126,7 @@ static EnvVars initializePipelineITEnvironment(String pattern, JenkinsRule jenki EnvironmentVariablesNodeProperty prop = new EnvironmentVariablesNodeProperty(); EnvVars envVars = prop.getEnvVars(); envVars.put("CREDENTIALS_ID", credentialId); - envVars.put("BUCKET", bucket); + envVars.put("BUCKET", BUCKET); envVars.put("PATTERN", pattern); jenkinsRule.jenkins.getGlobalNodeProperties().add(prop); return envVars; diff --git a/src/test/java/com/google/jenkins/plugins/storage/integration/StdoutUploadStepPipelineIT.java b/src/test/java/com/google/jenkins/plugins/storage/integration/StdoutUploadStepPipelineIT.java index 93196505..e755acd5 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/integration/StdoutUploadStepPipelineIT.java +++ b/src/test/java/com/google/jenkins/plugins/storage/integration/StdoutUploadStepPipelineIT.java @@ -20,8 +20,9 @@ import static com.google.jenkins.plugins.storage.integration.ITUtil.formatRandomName; import static com.google.jenkins.plugins.storage.integration.ITUtil.initializePipelineITEnvironment; import static com.google.jenkins.plugins.storage.integration.ITUtil.loadResource; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.google.jenkins.plugins.storage.StdoutUploadStep; import com.google.jenkins.plugins.storage.client.ClientFactory; import com.google.jenkins.plugins.storage.client.StorageClient; import hudson.EnvVars; @@ -30,18 +31,18 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** Tests the {@link StdoutUploadStep} for use-cases involving the Jenkins Pipeline DSL. */ -public class StdoutUploadStepPipelineIT { +@WithJenkins +class StdoutUploadStepPipelineIT { private static final Logger LOGGER = Logger.getLogger(StdoutUploadStepPipelineIT.class.getName()); - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); + private static JenkinsRule jenkinsRule; public static String credentialsId; private static final String pattern = "build_log.txt"; @@ -49,10 +50,11 @@ public class StdoutUploadStepPipelineIT { private static StorageClient storageClient; private static EnvVars envVars; - @BeforeClass - public static void init() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule) throws Exception { LOGGER.info("Initializing StdoutUploadStepPipelineIT"); + jenkinsRule = rule; envVars = initializePipelineITEnvironment(pattern, jenkinsRule); credentialsId = envVars.get("CREDENTIALS_ID"); storageClient = new ClientFactory(jenkinsRule.jenkins, credentialsId).storageClient(); @@ -61,7 +63,7 @@ public static void init() throws Exception { } @Test - public void testStdoutUploadStepSuccessful() throws Exception { + void testStdoutUploadStepSuccessful() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition( @@ -74,7 +76,7 @@ public void testStdoutUploadStepSuccessful() throws Exception { } @Test - public void testMalformedStdoutUploadStepFailure() throws Exception { + void testMalformedStdoutUploadStepFailure() throws Exception { WorkflowJob testProject = jenkinsRule.createProject(WorkflowJob.class, formatRandomName("test")); testProject.setDefinition( @@ -85,8 +87,8 @@ public void testMalformedStdoutUploadStepFailure() throws Exception { dumpLog(LOGGER, run); } - @AfterClass - public static void cleanUp() throws Exception { + @AfterAll + static void afterAll() throws Exception { storageClient.deleteBucket(bucket); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/reports/AbstractGcsUploadReportTest.java b/src/test/java/com/google/jenkins/plugins/storage/reports/AbstractGcsUploadReportTest.java index af65bf66..d1edf982 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/reports/AbstractGcsUploadReportTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/reports/AbstractGcsUploadReportTest.java @@ -15,27 +15,28 @@ */ package com.google.jenkins.plugins.storage.reports; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import hudson.model.Actionable; import java.util.Set; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; /** Unit test for {@link AbstractGcsUploadReport}. */ -public class AbstractGcsUploadReportTest { +@ExtendWith(MockitoExtension.class) +class AbstractGcsUploadReportTest { @Mock private Actionable parent; private AbstractGcsUploadReport underTest; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach() { underTest = new AbstractGcsUploadReport(parent) { @Override public Set getStorageObjects() { @@ -55,7 +56,7 @@ public Set getBuckets() { } @Test - public void getters() { + void getters() { assertEquals(parent, underTest.getParent()); assertEquals(Messages.AbstractGcsUploadReport_DisplayName(), underTest.getDisplayName()); assertNotNull(underTest.getIconFileName()); diff --git a/src/test/java/com/google/jenkins/plugins/storage/reports/BuildGcsUploadReportTest.java b/src/test/java/com/google/jenkins/plugins/storage/reports/BuildGcsUploadReportTest.java index 06bba6c3..cb323f87 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/reports/BuildGcsUploadReportTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/reports/BuildGcsUploadReportTest.java @@ -15,9 +15,9 @@ */ package com.google.jenkins.plugins.storage.reports; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Iterables; import com.google.jenkins.plugins.storage.util.BucketPath; @@ -26,46 +26,47 @@ import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import java.util.concurrent.ExecutionException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; -import org.mockito.MockitoAnnotations; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import org.mockito.junit.jupiter.MockitoExtension; /** Unit test for {@link BuildGcsUploadReport}. */ -public class BuildGcsUploadReportTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class BuildGcsUploadReportTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; private AbstractProject project; private AbstractBuild build; private BuildGcsUploadReport underTest; - @Before - public void setup() throws Exception { - MockitoAnnotations.initMocks(this); - + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + jenkins = rule; project = jenkins.createFreeStyleProject(); build = new FreeStyleBuild((FreeStyleProject) project); underTest = new BuildGcsUploadReport(build); } @Test - public void getters() { + void getters() { assertEquals(build, underTest.getParent()); assertEquals(build.getNumber(), underTest.getBuildNumber().intValue()); } @Test - public void addBucket() { + void addBucket() { assertEquals(0, underTest.getBuckets().size()); underTest.addBucket("bucket"); assertEquals("bucket", Iterables.getLast(underTest.getBuckets())); } @Test - public void addUpload() throws Exception { + void addUpload() { String relativePath = "relative/path"; assertEquals(0, underTest.getStorageObjects().size()); underTest.addUpload(relativePath, new BucketPath("gs://myBucket/helloworld/18")); @@ -73,24 +74,24 @@ public void addUpload() throws Exception { } @Test - public void of() { + void of() { BuildGcsUploadReport report = BuildGcsUploadReport.of(build); assertNotNull(report); } @Test - public void of_existing() { + void of_existing() { build.addAction(underTest); assertEquals(underTest, BuildGcsUploadReport.of(build)); } @Test - public void of_project_noLastBuild() { + void of_project_noLastBuild() { assertNull(BuildGcsUploadReport.of(project)); } @Test - public void of_project_hasLastBuild() throws InterruptedException, ExecutionException { + void of_project_hasLastBuild() throws InterruptedException, ExecutionException { project.scheduleBuild2(0).get(); project.getLastBuild().addAction(underTest); assertEquals(underTest, BuildGcsUploadReport.of(project)); diff --git a/src/test/java/com/google/jenkins/plugins/storage/reports/ProjectGcsUploadReportTest.java b/src/test/java/com/google/jenkins/plugins/storage/reports/ProjectGcsUploadReportTest.java index a1d8f744..3b6d81c4 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/reports/ProjectGcsUploadReportTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/reports/ProjectGcsUploadReportTest.java @@ -15,7 +15,7 @@ */ package com.google.jenkins.plugins.storage.reports; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableSet; @@ -24,15 +24,19 @@ import hudson.model.FreeStyleProject; import hudson.tasks.Publisher; import hudson.util.DescribableList; -import java.io.IOException; import java.util.Set; -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.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** Unit test for {@link ProjectGcsUploadReport}. */ -public class ProjectGcsUploadReportTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class ProjectGcsUploadReportTest { @Mock private FreeStyleProject project; @@ -52,9 +56,8 @@ public class ProjectGcsUploadReportTest { @Mock private DescribableList> noUploadPublishers; - @Before - public void setup() throws IOException { - MockitoAnnotations.initMocks(this); + @BeforeEach + void beforeEach() { // set up for a case where the last build did have some uploads. when(project.getLastBuild()).thenReturn(build); when(build.getAction(BuildGcsUploadReport.class)).thenReturn(buildUploadReport); @@ -65,7 +68,7 @@ public void setup() throws IOException { } @Test - public void getters_noUpload() { + void getters_noUpload() { /* in case there are no upload, test that empty lists are returned */ ProjectGcsUploadReport underTest = new ProjectGcsUploadReport(noUploadProject); assertEquals(0, underTest.getBuckets().size()); @@ -73,7 +76,7 @@ public void getters_noUpload() { } @Test - public void getters_hasUploads() { + void getters_hasUploads() { /* In case there are uploads, test that the project report delegates to * the report of the last build. */ ProjectGcsUploadReport underTest = new ProjectGcsUploadReport(project); diff --git a/src/test/java/com/google/jenkins/plugins/storage/util/CredentialsUtilTest.java b/src/test/java/com/google/jenkins/plugins/storage/util/CredentialsUtilTest.java index e1b6900c..a7eae802 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/util/CredentialsUtilTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/util/CredentialsUtilTest.java @@ -15,38 +15,45 @@ */ package com.google.jenkins.plugins.storage.util; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SecretBytes; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; -import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.google.common.collect.ImmutableList; import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials; import com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentials; import com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig; import hudson.AbortException; import java.nio.charset.StandardCharsets; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class CredentialsUtilTest { +@WithJenkins +class CredentialsUtilTest { private static final String TEST_CREDENTIALS_ID = "test-credentials-id"; private static final String TEST_INVALID_CREDENTIALS_ID = "test-invalid-credentials-id"; - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Test(expected = AbortException.class) - public void testGetRobotCredentialsInvalidCredentialsIdAbortException() throws AbortException { - CredentialsUtil.getRobotCredentials( - r.jenkins, ImmutableList.of(), TEST_INVALID_CREDENTIALS_ID); + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; } - @Test(expected = GoogleRobotPrivateKeyCredentials.PrivateKeyNotSetException.class) - public void testGetGoogleCredentialAbortException() throws Exception { + @Test + void testGetRobotCredentialsInvalidCredentialsIdAbortException() { + assertThrows( + AbortException.class, + () -> CredentialsUtil.getRobotCredentials(r.jenkins, ImmutableList.of(), TEST_INVALID_CREDENTIALS_ID)); + } + + @Test + void testGetGoogleCredentialAbortException() throws Exception { SecretBytes bytes = SecretBytes.fromBytes("{\"client_email\": \"example@example.com\"}".getBytes(StandardCharsets.UTF_8)); JsonServiceAccountConfig serviceAccountConfig = new JsonServiceAccountConfig(); @@ -56,26 +63,36 @@ public void testGetGoogleCredentialAbortException() throws Exception { new GoogleRobotPrivateKeyCredentials(TEST_INVALID_CREDENTIALS_ID, serviceAccountConfig, null); CredentialsStore store = new SystemCredentialsProvider.ProviderImpl().getStore(r.jenkins); store.addCredentials(Domain.global(), robotCreds); - CredentialsUtil.getGoogleCredential(robotCreds); + assertThrows( + GoogleRobotPrivateKeyCredentials.PrivateKeyNotSetException.class, + () -> CredentialsUtil.getGoogleCredential(robotCreds)); } - @Test(expected = NullPointerException.class) - public void testGetRobotCredentialsWithEmptyItemGroup() throws AbortException { - CredentialsUtil.getRobotCredentials(null, ImmutableList.of(), TEST_CREDENTIALS_ID); + @Test + void testGetRobotCredentialsWithEmptyItemGroup() { + assertThrows( + NullPointerException.class, + () -> CredentialsUtil.getRobotCredentials(null, ImmutableList.of(), TEST_CREDENTIALS_ID)); } - @Test(expected = NullPointerException.class) - public void testGetRobotCredentialsWithEmptyDomainRequirements() throws AbortException { - CredentialsUtil.getRobotCredentials(r.jenkins, null, TEST_CREDENTIALS_ID); + @Test + void testGetRobotCredentialsWithEmptyDomainRequirements() { + assertThrows( + NullPointerException.class, + () -> CredentialsUtil.getRobotCredentials(r.jenkins, null, TEST_CREDENTIALS_ID)); } - @Test(expected = IllegalArgumentException.class) - public void testGetRobotCredentialsWithNullCredentialsId() throws AbortException { - CredentialsUtil.getRobotCredentials(r.jenkins, ImmutableList.of(), null); + @Test + void testGetRobotCredentialsWithNullCredentialsId() { + assertThrows( + IllegalArgumentException.class, + () -> CredentialsUtil.getRobotCredentials(r.jenkins, ImmutableList.of(), null)); } - @Test(expected = IllegalArgumentException.class) - public void testGetRobotCredentialsWithEmptyCredentialsId() throws AbortException { - CredentialsUtil.getRobotCredentials(r.jenkins, ImmutableList.of(), ""); + @Test + void testGetRobotCredentialsWithEmptyCredentialsId() { + assertThrows( + IllegalArgumentException.class, + () -> CredentialsUtil.getRobotCredentials(r.jenkins, ImmutableList.of(), "")); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/util/RetryStorageOperationTest.java b/src/test/java/com/google/jenkins/plugins/storage/util/RetryStorageOperationTest.java index 5de9134b..deac076c 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/util/RetryStorageOperationTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/util/RetryStorageOperationTest.java @@ -16,7 +16,8 @@ package com.google.jenkins.plugins.storage.util; import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_UNAUTHORIZED; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.StubHttpResponseException; @@ -24,18 +25,16 @@ import com.google.jenkins.plugins.storage.util.RetryStorageOperation.RepeatOperation; import com.google.jenkins.plugins.util.MockExecutor; import java.io.IOException; -import org.junit.Assert; -import org.junit.Test; -import org.jvnet.hudson.test.WithoutJenkins; +import org.junit.jupiter.api.Test; /** Tests for {@link StorageUtil}. */ -public class RetryStorageOperationTest { +class RetryStorageOperationTest { private final MockExecutor executor = new MockExecutor(); // An action that fails the given number of times before succeeding // and then counts the number of successes - private class FailOperation implements Operation { + private static class FailOperation implements Operation { public int fails; public int succeeded; @@ -55,23 +54,16 @@ public void act() throws IOException { } @Test - @WithoutJenkins - public void retryNoBudgetTest() throws Exception { + void retryNoBudgetTest() { FailOperation action = new FailOperation(1); - try { - // Fail immediately if there is no retry budget - RetryStorageOperation.performRequestWithRetry(executor, action, 1); - } catch (IOException e) { - assertEquals(0, action.fails); - assertEquals(0, action.succeeded); - return; - } - Assert.fail("Expected exception"); + // Fail immediately if there is no retry budget + assertThrows(IOException.class, () -> RetryStorageOperation.performRequestWithRetry(executor, action, 1)); + assertEquals(0, action.fails); + assertEquals(0, action.succeeded); } @Test - @WithoutJenkins - public void retrySuccessTest() throws Exception { + void retrySuccessTest() throws Exception { // Succeed if there is enough budget FailOperation action = new FailOperation(1); RetryStorageOperation.performRequestWithRetry(executor, action, 2); @@ -80,8 +72,7 @@ public void retrySuccessTest() throws Exception { } @Test - @WithoutJenkins - public void retryMoreTimesTest() throws Exception { + void retryMoreTimesTest() throws Exception { // Correctly count retries for larger numbers FailOperation action = new FailOperation(1); RetryStorageOperation.performRequestWithRetry(executor, action, 10); @@ -90,23 +81,16 @@ public void retryMoreTimesTest() throws Exception { } @Test - @WithoutJenkins - public void retryMoreTimesFailTest() throws Exception { + void retryMoreTimesFailTest() { FailOperation action = new FailOperation(9); - try { - // Fail immediately if there is no retry budget - RetryStorageOperation.performRequestWithRetry(executor, action, 5); - } catch (IOException e) { - assertEquals(4, action.fails); - assertEquals(0, action.succeeded); - return; - } - Assert.fail("Expected exception"); + // Fail immediately if there is no retry budget + assertThrows(IOException.class, () -> RetryStorageOperation.performRequestWithRetry(executor, action, 5)); + assertEquals(4, action.fails); + assertEquals(0, action.succeeded); } @Test - @WithoutJenkins - public void retryLostOfBudgetTest() throws Exception { + void retryLostOfBudgetTest() throws Exception { // Succeed only once even if there is lots of budget FailOperation action = new FailOperation(1); RetryStorageOperation.performRequestWithRetry(executor, action, 10); @@ -115,8 +99,7 @@ public void retryLostOfBudgetTest() throws Exception { } @Test - @WithoutJenkins - public void retryInterruptedException() throws Exception { + void retryInterruptedException() throws Exception { // Interrupted exception is handled as well class MixOperation implements Operation { @@ -148,7 +131,7 @@ public void act() throws InterruptedException, IOException { assertEquals(1, action.succeeded); } - private class FailingCredentials implements RepeatOperation { + private static class FailingCredentials implements RepeatOperation { public int credLength; public int usesLeft; @@ -184,8 +167,7 @@ public boolean moreWork() { } @Test - @WithoutJenkins - public void credsRetry() throws Exception { + void credsRetry() throws Exception { // Perform successful retries FailingCredentials cr = new FailingCredentials(2, 10); @@ -195,24 +177,17 @@ public void credsRetry() throws Exception { } @Test - @WithoutJenkins - public void credsNoBudget() throws Exception { + void credsNoBudget() { // No retry budget quits after first failure (here that's after credentials // expire after 2 steps) FailingCredentials cr = new FailingCredentials(2, 10); - try { - RetryStorageOperation.performRequestWithReinitCredentials(cr, 0); - } catch (IOException e) { - assertEquals(8, cr.stepsLeft); - return; - } - Assert.fail("Expected exception"); + assertThrows(IOException.class, () -> RetryStorageOperation.performRequestWithReinitCredentials(cr, 0)); + assertEquals(8, cr.stepsLeft); } @Test - @WithoutJenkins - public void testStuck() throws Exception { + void testStuck() { // This Operation gets stuck reloading credentials when 5 steps remaining. class StuckCreds extends FailingCredentials { @@ -229,12 +204,7 @@ public void act() throws HttpResponseException { } StuckCreds cr = new StuckCreds(2, 10); - try { - RetryStorageOperation.performRequestWithReinitCredentials(cr, 2); - } catch (IOException e) { - assertEquals(5, cr.stepsLeft); - return; - } - Assert.fail("Expected exception"); + assertThrows(IOException.class, () -> RetryStorageOperation.performRequestWithReinitCredentials(cr, 2)); + assertEquals(5, cr.stepsLeft); } } diff --git a/src/test/java/com/google/jenkins/plugins/storage/util/StorageUtilTest.java b/src/test/java/com/google/jenkins/plugins/storage/util/StorageUtilTest.java index 45c1aa85..21f6b5a5 100644 --- a/src/test/java/com/google/jenkins/plugins/storage/util/StorageUtilTest.java +++ b/src/test/java/com/google/jenkins/plugins/storage/util/StorageUtilTest.java @@ -15,42 +15,38 @@ */ package com.google.jenkins.plugins.storage.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import hudson.FilePath; import java.io.File; -import java.io.IOException; import org.apache.commons.lang3.SystemUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.WithoutJenkins; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** Tests for {@link StorageUtil}. */ -public class StorageUtilTest { +class StorageUtilTest { private FilePath workspace; private FilePath nonWorkspace; - @Rule - public TemporaryFolder tempDir = new TemporaryFolder(); + @TempDir + private File tempDir; - @BeforeClass - public static void init() { + @BeforeAll + static void beforeAll() { assumeFalse(SystemUtils.IS_OS_WINDOWS); } - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() { workspace = new FilePath(makeTempDir("workspace")); nonWorkspace = new FilePath(makeTempDir("non-workspace")); } @Test - @WithoutJenkins - public void getRelativePositiveTest() throws Exception { + void getRelativePositiveTest() throws Exception { FilePath one = workspace.child(FIRST_NAME); assertEquals(FIRST_NAME, StorageUtil.getRelative(one, workspace)); @@ -61,16 +57,15 @@ public void getRelativePositiveTest() throws Exception { } @Test - @WithoutJenkins - public void getRelativeNegativeTest() throws Exception { + void getRelativeNegativeTest() throws Exception { FilePath one = workspace.child(FIRST_NAME); assertEquals(workspace.getRemote(), "/" + StorageUtil.getRelative(workspace, one)); assertEquals(nonWorkspace.getRemote(), "/" + StorageUtil.getRelative(nonWorkspace, workspace)); } - private File makeTempDir(String name) throws IOException { - File dir = new File(tempDir.getRoot(), name); + private File makeTempDir(String name) { + File dir = new File(tempDir, name); dir.mkdir(); return dir; }