From 7f4c68ccf4c416e49be338baa185cc9871d1d654 Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Tue, 11 Mar 2025 12:12:45 +0100 Subject: [PATCH] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor code cleanup --- pom.xml | 15 +- .../jenkins/GoogleOAuthPluginTestSuite.java | 26 --- .../plugins/CredentialsOAuthTestSuite.java | 42 ---- .../google/jenkins/plugins/UtilTestSuite.java | 36 --- .../oauth/ConfigurationAsCodeTest.java | 28 ++- .../GoogleOAuth2ScopeSpecificationTest.java | 42 ++-- .../oauth/GoogleRobotCredentialsTest.java | 183 ++++++++-------- .../GoogleRobotMetadataCredentialsTest.java | 170 +++++++-------- .../GoogleRobotPrivateKeyCredentialsTest.java | 206 ++++++++---------- .../oauth/JsonServiceAccountConfigTest.java | 48 ++-- .../JsonServiceAccountConfigTestUtil.java | 17 +- .../LegacyJsonServiceAccountConfigUtil.java | 35 +-- .../oauth/P12ServiceAccountConfigTest.java | 50 ++--- .../P12ServiceAccountConfigTestUtil.java | 11 +- .../oauth/RemotableGoogleCredentialsTest.java | 75 ++++--- .../credentials/oauth/SerializationUtil.java | 24 +- .../TestGoogleOAuth2DomainRequirement.java | 2 + .../credentials/oauth/TestRobotBuilder.java | 3 + .../jenkins/plugins/util/ExecutorTest.java | 59 +++-- .../plugins/util/MetadataReaderTest.java | 110 +++++----- .../plugins/util/MockExecutorTest.java | 144 ++++++------ .../plugins/util/NameValuePairTest.java | 15 +- .../jenkins/plugins/util/ResolveTest.java | 30 ++- 23 files changed, 578 insertions(+), 793 deletions(-) delete mode 100644 src/test/java/com/google/jenkins/GoogleOAuthPluginTestSuite.java delete mode 100644 src/test/java/com/google/jenkins/plugins/CredentialsOAuthTestSuite.java delete mode 100644 src/test/java/com/google/jenkins/plugins/UtilTestSuite.java diff --git a/pom.xml b/pom.xml index 2037584..ffa6d48 100644 --- a/pom.xml +++ b/pom.xml @@ -76,7 +76,6 @@ 151 1.42.2 Max - **/GoogleOAuthPluginTestSuite.class false @@ -85,7 +84,7 @@ io.jenkins.tools.bom bom-${jenkins.baseline}.x - 3944.v1a_e4f8b_452db_ + 4136.vca_c3202a_7fd1 pom import @@ -284,7 +283,7 @@ org.mockito - mockito-core + mockito-junit-jupiter test @@ -343,16 +342,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - - - ${runSuite} - - false - - diff --git a/src/test/java/com/google/jenkins/GoogleOAuthPluginTestSuite.java b/src/test/java/com/google/jenkins/GoogleOAuthPluginTestSuite.java deleted file mode 100644 index 5e181d7..0000000 --- a/src/test/java/com/google/jenkins/GoogleOAuthPluginTestSuite.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.jenkins; - -import com.google.jenkins.plugins.CredentialsOAuthTestSuite; -import com.google.jenkins.plugins.UtilTestSuite; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** Defines the full test suite for the Google Oauth Plugin. */ -@RunWith(Suite.class) -@Suite.SuiteClasses(value = {CredentialsOAuthTestSuite.class, UtilTestSuite.class}) -public class GoogleOAuthPluginTestSuite {} diff --git a/src/test/java/com/google/jenkins/plugins/CredentialsOAuthTestSuite.java b/src/test/java/com/google/jenkins/plugins/CredentialsOAuthTestSuite.java deleted file mode 100644 index e387237..0000000 --- a/src/test/java/com/google/jenkins/plugins/CredentialsOAuthTestSuite.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.jenkins.plugins; - -import com.google.jenkins.plugins.credentials.oauth.ConfigurationAsCodeTest; -import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2ScopeSpecificationTest; -import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentialsTest; -import com.google.jenkins.plugins.credentials.oauth.GoogleRobotMetadataCredentialsTest; -import com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentialsTest; -import com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfigTest; -import com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTest; -import com.google.jenkins.plugins.credentials.oauth.RemotableGoogleCredentialsTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** Defines the full test suite involving OAuth credentials. */ -@RunWith(Suite.class) -@Suite.SuiteClasses( - value = { - ConfigurationAsCodeTest.class, - GoogleOAuth2ScopeSpecificationTest.class, - GoogleRobotCredentialsTest.class, - GoogleRobotMetadataCredentialsTest.class, - GoogleRobotPrivateKeyCredentialsTest.class, - JsonServiceAccountConfigTest.class, - P12ServiceAccountConfigTest.class, - RemotableGoogleCredentialsTest.class - }) -public class CredentialsOAuthTestSuite {} diff --git a/src/test/java/com/google/jenkins/plugins/UtilTestSuite.java b/src/test/java/com/google/jenkins/plugins/UtilTestSuite.java deleted file mode 100644 index da24e35..0000000 --- a/src/test/java/com/google/jenkins/plugins/UtilTestSuite.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.jenkins.plugins; - -import com.google.jenkins.plugins.util.ExecutorTest; -import com.google.jenkins.plugins.util.MetadataReaderTest; -import com.google.jenkins.plugins.util.MockExecutorTest; -import com.google.jenkins.plugins.util.NameValuePairTest; -import com.google.jenkins.plugins.util.ResolveTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** Defines the full test suite for utility classes. */ -@RunWith(Suite.class) -@Suite.SuiteClasses( - value = { - ExecutorTest.class, - MetadataReaderTest.class, - MockExecutorTest.class, - NameValuePairTest.class, - ResolveTest.class - }) -public class UtilTestSuite {} diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/ConfigurationAsCodeTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/ConfigurationAsCodeTest.java index 79ef22c..096fff5 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/ConfigurationAsCodeTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/ConfigurationAsCodeTest.java @@ -16,34 +16,32 @@ package com.google.jenkins.plugins.credentials.oauth; -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.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.SecretBytes; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.IOUtils; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests that the credentials are correctly processed by the Configuration as Code plugin. */ -public class ConfigurationAsCodeTest { - - @Rule - public JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); +@WithJenkinsConfiguredWithCode +class ConfigurationAsCodeTest { @Test @ConfiguredWithCode("json-service-account-config.yml") - public void supportsConfigurationWithJsonServiceAccountConfig() throws IOException { + void supportsConfigurationWithJsonServiceAccountConfig(JenkinsConfiguredWithCodeRule r) throws IOException { List credentialsList = CredentialsProvider.lookupCredentials(GoogleRobotPrivateKeyCredentials.class); assertNotNull(credentialsList); - assertEquals("No credentials created", 1, credentialsList.size()); + assertEquals(1, credentialsList.size(), "No credentials created"); GoogleRobotPrivateKeyCredentials credentials = credentialsList.get(0); assertNotNull(credentials); JsonServiceAccountConfig config = (JsonServiceAccountConfig) credentials.getServiceAccountConfig(); @@ -57,16 +55,16 @@ public void supportsConfigurationWithJsonServiceAccountConfig() throws IOExcepti String actualBytes = new String(bytes.getPlainData(), StandardCharsets.UTF_8); String expectedBytes = IOUtils.toString(this.getClass().getResourceAsStream("test-key.json"), StandardCharsets.UTF_8); - assertEquals("Failed to configure secretJsonKey correctly.", expectedBytes, actualBytes); + assertEquals(expectedBytes, actualBytes, "Failed to configure secretJsonKey correctly."); } @Test @ConfiguredWithCode("p12-service-account-config.yml") - public void supportsConfigurationWithP12ServiceAccountConfig() { + void supportsConfigurationWithP12ServiceAccountConfig(JenkinsConfiguredWithCodeRule r) { List credentialsList = CredentialsProvider.lookupCredentials(GoogleRobotPrivateKeyCredentials.class); assertNotNull(credentialsList); - assertEquals("No credentials created", 1, credentialsList.size()); + assertEquals(1, credentialsList.size(), "No credentials created"); GoogleRobotPrivateKeyCredentials credentials = credentialsList.get(0); assertNotNull(credentials); P12ServiceAccountConfig config = (P12ServiceAccountConfig) credentials.getServiceAccountConfig(); @@ -81,6 +79,6 @@ public void supportsConfigurationWithP12ServiceAccountConfig() { SecretBytes bytes = config.getSecretP12Key(); String actualBytes = new String(bytes.getPlainData(), StandardCharsets.UTF_8); String expectedBytes = "test-p12-key"; - assertEquals("Failed to configure secretP12Key correctly", expectedBytes, actualBytes); + assertEquals(expectedBytes, actualBytes, "Failed to configure secretP12Key correctly"); } } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleOAuth2ScopeSpecificationTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleOAuth2ScopeSpecificationTest.java index 5354f1b..7c134e1 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleOAuth2ScopeSpecificationTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleOAuth2ScopeSpecificationTest.java @@ -15,41 +15,41 @@ */ package com.google.jenkins.plugins.credentials.oauth; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.cloudbees.plugins.credentials.domains.DomainSpecification.Result; -import com.google.common.collect.ImmutableList; import java.util.Collection; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import java.util.List; +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.mockito.MockitoAnnotations; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link GoogleOAuth2ScopeSpecification}. */ -public class GoogleOAuth2ScopeSpecificationTest { - // Allow for testing using JUnit4, instead of JUnit3. - @Rule - public JenkinsRule jenkins = new JenkinsRule(); +@WithJenkins +@ExtendWith(MockitoExtension.class) +class GoogleOAuth2ScopeSpecificationTest { - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } + private static final String GOOD_SCOPE1 = "foo"; + private static final String GOOD_SCOPE2 = "baz"; + private static final String BAD_SCOPE = "bar"; + private static final Collection GOOD_SCOPES = List.of(GOOD_SCOPE1, GOOD_SCOPE2); + private static final Collection BAD_SCOPES = List.of(GOOD_SCOPE1, BAD_SCOPE); @Test @WithoutJenkins - public void testBasics() throws Exception { + void testBasics() { GoogleOAuth2ScopeSpecification spec = new GoogleOAuth2ScopeSpecification(GOOD_SCOPES); assertThat(spec.getSpecifiedScopes(), hasItems(GOOD_SCOPE1, GOOD_SCOPE2)); } @Test - public void testUnknownRequirement() throws Exception { + void testUnknownRequirement(JenkinsRule jenkins) { GoogleOAuth2ScopeSpecification spec = new GoogleOAuth2ScopeSpecification(GOOD_SCOPES); OAuth2ScopeRequirement requirement = new OAuth2ScopeRequirement() { @@ -65,7 +65,7 @@ public Collection getScopes() { } @Test - public void testKnownRequirements() throws Exception { + void testKnownRequirements(JenkinsRule jenkins) throws Exception { GoogleOAuth2ScopeSpecification spec = new GoogleOAuth2ScopeSpecification(GOOD_SCOPES); GoogleOAuth2ScopeRequirement goodReq = new GoogleOAuth2ScopeRequirement() { @@ -86,10 +86,4 @@ public Collection getScopes() { assertEquals(Result.POSITIVE, spec.test(goodReq)); assertEquals(Result.NEGATIVE, spec.test(badReq)); } - - private static String GOOD_SCOPE1 = "foo"; - private static String GOOD_SCOPE2 = "baz"; - private static String BAD_SCOPE = "bar"; - private static Collection GOOD_SCOPES = ImmutableList.of(GOOD_SCOPE1, GOOD_SCOPE2); - private static Collection BAD_SCOPES = ImmutableList.of(GOOD_SCOPE1, BAD_SCOPE); } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotCredentialsTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotCredentialsTest.java index 7061ed7..199e97b 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotCredentialsTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotCredentialsTest.java @@ -16,13 +16,13 @@ package com.google.jenkins.plugins.credentials.oauth; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.cloudbees.plugins.credentials.CredentialsNameProvider; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -31,94 +31,46 @@ import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.common.collect.ImmutableList; import com.google.jenkins.plugins.credentials.domains.RequiresDomain; +import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Descriptor; import hudson.util.ListBoxModel; import hudson.util.Secret; import java.security.GeneralSecurityException; import java.util.Collection; -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.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link GoogleRobotCredentials}. */ -public class GoogleRobotCredentialsTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class GoogleRobotCredentialsTest { - // Allow for testing using JUnit4, instead of JUnit3. - @Rule - public JenkinsRule jenkins = new JenkinsRule(); - - /** */ - public static class TestRequirement extends TestGoogleOAuth2DomainRequirement { - public TestRequirement() { - super(FAKE_SCOPE); - } - } - - /** */ - public static class NameProvider extends CredentialsNameProvider { - @Override - public String getName(GoogleRobotCredentials credentials) { - return NAME; - } - } - - /** */ - @NameWith(value = NameProvider.class, priority = 100) - @RequiresDomain(value = TestRequirement.class) - public static class FakeGoogleCredentials extends GoogleRobotCredentials { - public FakeGoogleCredentials(String projectId, GoogleCredential credential) { - super(CredentialsScope.GLOBAL, "", projectId, new GoogleRobotCredentialsModule()); - - this.credential = credential; - } - - @Override - public GoogleCredential getGoogleCredential(GoogleOAuth2ScopeRequirement requirement) - throws GeneralSecurityException { - if (credential == null) { - throw new GeneralSecurityException("asdf"); - } - return credential; - } - - private GoogleCredential credential; - - @Override - public String getUsername() { - return USERNAME; - } - - /** */ - @Extension - public static class DescriptorImpl extends AbstractGoogleRobotCredentialsDescriptor { - public DescriptorImpl() { - super(FakeGoogleCredentials.class); - } - - @Override - public String getDisplayName() { - return DISPLAY_NAME; - } - } - } + private static final String NAME = "my credential name"; + private static final String FAKE_SCOPE = "my.fake.scope"; + private static final String DISPLAY_NAME = "blah"; + private static final String PROJECT_ID = "foo.com:bar-baz"; + private static final String MIGRATION_PROJECT_ID = "my-google-project"; + private static final String USERNAME = "mattomata"; + private static final String ACCESS_TOKEN = "ThE.ToKeN"; + private static final long EXPIRATION_SECONDS = 1234; private GoogleCredential fakeCredential; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - + @BeforeEach + void setUp() { fakeCredential = new GoogleCredential(); } @Test @WithoutJenkins - public void testGettersNullId() throws Exception { + void testGettersNullId() throws Exception { FakeGoogleCredentials credentials = new FakeGoogleCredentials(PROJECT_ID, fakeCredential); assertEquals(PROJECT_ID, credentials.getProjectId()); @@ -128,7 +80,7 @@ public void testGettersNullId() throws Exception { } @Test - public void testGetDescriptor() throws Exception { + void testGetDescriptor(JenkinsRule jenkins) { FakeGoogleCredentials credentials = new FakeGoogleCredentials(PROJECT_ID, fakeCredential); Descriptor descriptor = credentials.getDescriptor(); @@ -138,7 +90,7 @@ public void testGetDescriptor() throws Exception { @Test @WithoutJenkins - public void testGetAccessToken() throws Exception { + void testGetAccessToken() { FakeGoogleCredentials credentials = new FakeGoogleCredentials(PROJECT_ID, fakeCredential); fakeCredential.setAccessToken(ACCESS_TOKEN); @@ -148,7 +100,7 @@ public void testGetAccessToken() throws Exception { @Test @WithoutJenkins - public void testGetAccessTokenNoCredential() throws Exception { + void testGetAccessTokenNoCredential() { FakeGoogleCredentials credentials = new FakeGoogleCredentials(PROJECT_ID, null /* credential */); assertNull(credentials.getAccessToken(null)); @@ -156,7 +108,7 @@ public void testGetAccessTokenNoCredential() throws Exception { @Test @WithoutJenkins - public void testForRemote() throws Exception { + void testForRemote() throws Exception { FakeGoogleCredentials credentials = new FakeGoogleCredentials(PROJECT_ID, fakeCredential); fakeCredential.setAccessToken(ACCESS_TOKEN); @@ -176,7 +128,7 @@ public Collection getScopes() { } @Test - public void testListBoxEmpty() throws Exception { + void testListBoxEmpty(JenkinsRule jenkins) { ListBoxModel list = GoogleRobotCredentials.getCredentialsListBox(FakeGoogleCredentials.class); assertEquals(0, list.size()); @@ -194,7 +146,7 @@ public void testListBoxEmpty() throws Exception { } @Test - public void testGetById() throws Exception { + void testGetById(JenkinsRule jenkins) { FakeGoogleCredentials credentials = new FakeGoogleCredentials(PROJECT_ID, fakeCredential); assertNull(GoogleRobotCredentials.getById(credentials.getId())); @@ -206,7 +158,7 @@ public void testGetById() throws Exception { @LocalData @Test - public void testMigration() { + void testMigration(JenkinsRule jenkins) { /* LocalData contains an old credential with no id field and the project id my-google-project. On deserialization the id should be filled with the project id. We didn't specify description in credentials.xml and it should be empty @@ -217,18 +169,67 @@ public void testMigration() { } @Test - public void testMultipleCredentials() { + void testMultipleCredentials(JenkinsRule jenkins) { FakeGoogleCredentials credential1 = new FakeGoogleCredentials(PROJECT_ID, null); FakeGoogleCredentials credential2 = new FakeGoogleCredentials(PROJECT_ID, null); assertNotEquals(credential1, credential2); } - private static final String NAME = "my credential name"; - private static final String FAKE_SCOPE = "my.fake.scope"; - private static final String DISPLAY_NAME = "blah"; - private static final String PROJECT_ID = "foo.com:bar-baz"; - private static final String MIGRATION_PROJECT_ID = "my-google-project"; - private static final String USERNAME = "mattomata"; - private static final String ACCESS_TOKEN = "ThE.ToKeN"; - private static final long EXPIRATION_SECONDS = 1234; + /** */ + @NameWith(value = NameProvider.class, priority = 100) + @RequiresDomain(value = TestRequirement.class) + public static class FakeGoogleCredentials extends GoogleRobotCredentials { + public FakeGoogleCredentials(String projectId, GoogleCredential credential) { + super(CredentialsScope.GLOBAL, "", projectId, new GoogleRobotCredentialsModule()); + + this.credential = credential; + } + + @Override + public GoogleCredential getGoogleCredential(GoogleOAuth2ScopeRequirement requirement) + throws GeneralSecurityException { + if (credential == null) { + throw new GeneralSecurityException("asdf"); + } + return credential; + } + + private final GoogleCredential credential; + + @Override + @NonNull + public String getUsername() { + return USERNAME; + } + + /** */ + @Extension + public static class DescriptorImpl extends AbstractGoogleRobotCredentialsDescriptor { + public DescriptorImpl() { + super(FakeGoogleCredentials.class); + } + + @Override + @NonNull + public String getDisplayName() { + return DISPLAY_NAME; + } + } + } + + /** */ + public static class TestRequirement extends TestGoogleOAuth2DomainRequirement { + public TestRequirement() { + super(FAKE_SCOPE); + } + } + + /** */ + public static class NameProvider extends CredentialsNameProvider { + @Override + @NonNull + public String getName(@NonNull GoogleRobotCredentials credentials) { + return NAME; + } + } } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotMetadataCredentialsTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotMetadataCredentialsTest.java index d72a4dd..e7a0775 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotMetadataCredentialsTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotMetadataCredentialsTest.java @@ -18,10 +18,11 @@ import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_NOT_FOUND; import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_OK; import static com.google.common.collect.Iterables.getOnlyElement; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -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.assertNull; +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.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -37,72 +38,44 @@ import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; import com.google.jenkins.plugins.util.MetadataReader; import hudson.Extension; import hudson.util.FormValidation; import java.io.IOException; import java.util.List; import jenkins.model.Jenkins; -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.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 GoogleRobotMetadataCredentials}. */ -public class GoogleRobotMetadataCredentialsTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class GoogleRobotMetadataCredentialsTest { - // Allow for testing using JUnit4, instead of JUnit3. - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private static final String METADATA_ENDPOINT = + OAuth2Utils.getMetadataServerUrl() + "/computeMetadata/v1/" + "instance/service-accounts/default/token"; + private static final String USERNAME = "bazinga"; + private static final String ACCESS_TOKEN = "ThE.ToKeN"; + private static final String PROJECT_ID = "foo.com:bar-baz"; + private static final String FAKE_SCOPE = "my.fake.scope"; + private static final String CREDENTIAL_ID = "credential.id"; + private static final String DESCRIPTION = "credential.description"; + private static final List SCOPES = List.of("scope1", "scope2", "scope3"); @Mock private GoogleCredential credential; - /** */ - public static class Module extends GoogleRobotMetadataCredentialsModule { - @Override - public MetadataReader getMetadataReader() { - return reader; - } - - public final MockHttpTransport transport = spy(new MockHttpTransport()); - public final MetadataReader reader = new MetadataReader.Default(transport.createRequestFactory()); - public final MockLowLevelHttpRequest request = spy(new MockLowLevelHttpRequest()); - - public void stubRequest(String url, int statusCode, String responseContent) throws IOException { - request.setResponse( - new MockLowLevelHttpResponse().setStatusCode(statusCode).setContent(responseContent)); - doReturn(request).when(transport).buildRequest("GET", url); - } - - private void verifyRequest(String url) throws IOException { - verify(transport).buildRequest("GET", url); - verify(request).execute(); - assertEquals("Google", getOnlyElement(request.getHeaderValues("Metadata-Flavor"))); - } - - @Override - public HttpTransport getHttpTransport() { - return transport; - } - } - - /** */ - @Extension - public static class MockDescriptor extends GoogleRobotMetadataCredentials.Descriptor { - public MockDescriptor() { - super(new Module()); - } - } - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - + @BeforeEach + void setUp() { // Make sure that OUR @Extension creates the descriptor when // Jenkins starts up by disabling the factory method. GoogleRobotMetadataCredentials.Descriptor.disableForTesting = true; @@ -110,7 +83,7 @@ public void setUp() throws Exception { @Test @WithoutJenkins - public void accessTokenTest() throws Exception { + void accessTokenTest() throws Exception { final Module module = new Module(); GoogleRobotMetadataCredentials newCreds = @@ -133,7 +106,7 @@ public void accessTokenTest() throws Exception { @Test @WithoutJenkins - public void getUsernameTest() throws Exception { + void getUsernameTest() throws Exception { final Module module = new Module(); GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", module); @@ -146,38 +119,34 @@ public void getUsernameTest() throws Exception { assertEquals(CredentialsScope.GLOBAL, credentials.getScope()); } - @Test(expected = IllegalStateException.class) + @Test @WithoutJenkins - public void getUsernameWithNotFoundExceptionTest() throws Exception { + void getUsernameWithNotFoundExceptionTest() throws Exception { final Module module = new Module(); GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", module); - module.stubRequest( "http://metadata/computeMetadata/v1/instance/" + "service-accounts/default/email", STATUS_CODE_NOT_FOUND, USERNAME); - // Expected to throw - credentials.getUsername(); + assertThrows(IllegalStateException.class, credentials::getUsername); } - @Test(expected = IllegalStateException.class) + @Test @WithoutJenkins - public void getUsernameWithUnknownIOExceptionTest() throws Exception { + void getUsernameWithUnknownIOExceptionTest() throws Exception { final Module module = new Module(); GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", module); - module.stubRequest( "http://metadata/computeMetadata/v1/instance/" + "service-accounts/default/email", 409, USERNAME); - // Expected to throw - credentials.getUsername(); + assertThrows(IllegalStateException.class, credentials::getUsername); } @Test - public void defaultProjectTest() throws Exception { + void defaultProjectTest(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials( CredentialsScope.GLOBAL, "", "doesn't matter", "", null /* module */); @@ -190,7 +159,7 @@ public void defaultProjectTest() throws Exception { } @Test - public void defaultProjectNotFoundTest() throws Exception { + void defaultProjectNotFoundTest(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials( CredentialsScope.GLOBAL, "", "doesn't matter", "", null /* module */); @@ -204,7 +173,7 @@ public void defaultProjectNotFoundTest() throws Exception { } @Test - public void defaultProjectUnknownIOExceptionTest() throws Exception { + void defaultProjectUnknownIOExceptionTest(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials( CredentialsScope.GLOBAL, "", "doesn't matter", "", null /* module */); @@ -218,7 +187,7 @@ public void defaultProjectUnknownIOExceptionTest() throws Exception { } @Test - public void defaultScopesTest() throws Exception { + void defaultScopesTest(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials( CredentialsScope.GLOBAL, "", "doesn't matter", "", null /* module */); @@ -234,7 +203,7 @@ public void defaultScopesTest() throws Exception { } @Test - public void defaultScopesNotFoundTest() throws Exception { + void defaultScopesNotFoundTest(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials( CredentialsScope.GLOBAL, "", "doesn't matter", "", null /* module */); @@ -250,7 +219,7 @@ public void defaultScopesNotFoundTest() throws Exception { } @Test - public void defaultScopesUnknownIOExceptionTest() throws Exception { + void defaultScopesUnknownIOExceptionTest(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials( CredentialsScope.GLOBAL, "", "doesn't matter", "", null /* module */); @@ -266,7 +235,7 @@ public void defaultScopesUnknownIOExceptionTest() throws Exception { } @Test - public void testGetById() throws Exception { + void testGetById(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null /* module */); SystemCredentialsProvider.getInstance().getCredentials().add(credentials); @@ -282,7 +251,7 @@ public void testGetById() throws Exception { // TODO(mattmoor): Figure out why this flakes out so much under testing @Test - public void testName() throws Exception { + void testName(JenkinsRule jenkins) throws Exception { GoogleRobotMetadataCredentials credentials = new GoogleRobotMetadataCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null /* module */); SystemCredentialsProvider.getInstance().getCredentials().add(credentials); @@ -292,7 +261,7 @@ public void testName() throws Exception { } @Test - public void testProjectIdValidation() throws Exception { + void testProjectIdValidation(JenkinsRule jenkins) { GoogleRobotMetadataCredentials.Descriptor descriptor = (GoogleRobotMetadataCredentials.Descriptor) Jenkins.getInstance().getDescriptorOrDie(GoogleRobotMetadataCredentials.class); @@ -302,7 +271,7 @@ public void testProjectIdValidation() throws Exception { } @Test - public void testCredentialCreationWithNonEmptyIdAndDescription() throws Exception { + void testCredentialCreationWithNonEmptyIdAndDescription(JenkinsRule jenkins) throws Exception { final Module module = new Module(); // WHEN: creating credential with defined id and description @@ -320,7 +289,7 @@ public void testCredentialCreationWithNonEmptyIdAndDescription() throws Exceptio } @Test - public void testCredentialCreationWithSystemScope() throws Exception { + void testCredentialCreationWithSystemScope(JenkinsRule jenkins) throws Exception { final Module module = new Module(); // WHEN: creating a credential with SYSTEM scope @@ -338,7 +307,7 @@ public void testCredentialCreationWithSystemScope() throws Exception { } @Test - public void testCredentialCreationWithGlobalScope() throws Exception { + void testCredentialCreationWithGlobalScope(JenkinsRule jenkins) throws Exception { final Module module = new Module(); // WHEN: creating a credential with GLOBAL scope @@ -355,13 +324,40 @@ public void testCredentialCreationWithGlobalScope() throws Exception { assertEquals(USERNAME, credentials.getUsername()); } - private static String METADATA_ENDPOINT = - OAuth2Utils.getMetadataServerUrl() + "/computeMetadata/v1/" + "instance/service-accounts/default/token"; - private static final String USERNAME = "bazinga"; - private static final String ACCESS_TOKEN = "ThE.ToKeN"; - private static final String PROJECT_ID = "foo.com:bar-baz"; - private static final String FAKE_SCOPE = "my.fake.scope"; - private static final String CREDENTIAL_ID = "credential.id"; - private static final String DESCRIPTION = "credential.description"; - private static final List SCOPES = ImmutableList.of("scope1", "scope2", "scope3"); + /** */ + public static class Module extends GoogleRobotMetadataCredentialsModule { + @Override + public MetadataReader getMetadataReader() { + return reader; + } + + public final MockHttpTransport transport = spy(new MockHttpTransport()); + public final MetadataReader reader = new MetadataReader.Default(transport.createRequestFactory()); + public final MockLowLevelHttpRequest request = spy(new MockLowLevelHttpRequest()); + + public void stubRequest(String url, int statusCode, String responseContent) throws IOException { + request.setResponse( + new MockLowLevelHttpResponse().setStatusCode(statusCode).setContent(responseContent)); + doReturn(request).when(transport).buildRequest("GET", url); + } + + private void verifyRequest(String url) throws IOException { + verify(transport).buildRequest("GET", url); + verify(request).execute(); + assertEquals("Google", getOnlyElement(request.getHeaderValues("Metadata-Flavor"))); + } + + @Override + public HttpTransport getHttpTransport() { + return transport; + } + } + + /** */ + @Extension + public static class MockDescriptor extends GoogleRobotMetadataCredentials.Descriptor { + public MockDescriptor() { + super(new Module()); + } + } } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotPrivateKeyCredentialsTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotPrivateKeyCredentialsTest.java index b77ff11..fe472f7 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotPrivateKeyCredentialsTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/GoogleRobotPrivateKeyCredentialsTest.java @@ -15,11 +15,11 @@ */ package com.google.jenkins.plugins.credentials.oauth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +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.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -43,16 +43,23 @@ import jenkins.model.Jenkins; import org.apache.commons.fileupload.FileItem; import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +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.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 GoogleRobotPrivateKeyCredentials}. */ -public class GoogleRobotPrivateKeyCredentialsTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class GoogleRobotPrivateKeyCredentialsTest { + private static final String SERVICE_ACCOUNT_EMAIL_ADDRESS = "service@account.com"; private static final String ACCESS_TOKEN = "ThE.ToKeN"; private static final String PROJECT_ID = "foo.com:bar-baz"; @@ -64,9 +71,6 @@ public class GoogleRobotPrivateKeyCredentialsTest { private static String p12KeyPath; private static String legacyJsonKeyPath; - @Rule - public JenkinsRule jenkins = new JenkinsRule(); - private MockHttpTransport transport; private MockLowLevelHttpRequest request; @@ -75,8 +79,8 @@ public class GoogleRobotPrivateKeyCredentialsTest { private GoogleRobotCredentialsModule module; - @BeforeClass - public static void preparePrivateKey() throws Exception { + @BeforeAll + static void preparePrivateKey() throws Exception { keyPair = P12ServiceAccountConfigTestUtil.generateKeyPair(); jsonKeyPath = JsonServiceAccountConfigTestUtil.createTempJsonKeyFile( SERVICE_ACCOUNT_EMAIL_ADDRESS, keyPair.getPrivate()); @@ -85,16 +89,8 @@ public static void preparePrivateKey() throws Exception { LegacyJsonServiceAccountConfigUtil.createTempLegacyJsonKeyFile(SERVICE_ACCOUNT_EMAIL_ADDRESS); } - private static void setPrivateField(GoogleRobotPrivateKeyCredentials credentials, String fieldName, Object value) - throws NoSuchFieldException, IllegalAccessException { - Field field = GoogleRobotPrivateKeyCredentials.class.getDeclaredField(fieldName); - field.setAccessible(true); - field.set(credentials, value); - } - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void setUp() throws Exception { transport = spy(new MockHttpTransport()); request = spy(new MockLowLevelHttpRequest()); @@ -107,7 +103,7 @@ public HttpTransport getHttpTransport() { } @Test - public void testCreatePrivateKeyCredentialsWithJsonKeyType() throws Exception { + void testCreatePrivateKeyCredentialsWithJsonKeyType(JenkinsRule jenkins) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(jsonKeyPath); when(mockFileItem.getInputStream()).thenReturn(new FileInputStream(jsonKeyPath)); @@ -138,7 +134,7 @@ public void testCreatePrivateKeyCredentialsWithJsonKeyType() throws Exception { } @Test - public void testCreatePrivateKeyCredentialsWithP12KeyType() throws Exception { + void testCreatePrivateKeyCredentialsWithP12KeyType(JenkinsRule jenkins) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(p12KeyPath); when(mockFileItem.get()).thenReturn(FileUtils.readFileToByteArray(new File(p12KeyPath))); @@ -167,37 +163,19 @@ public void testCreatePrivateKeyCredentialsWithP12KeyType() throws Exception { } } - private void stubRequest(String url, int statusCode, String responseContent) throws IOException { - request.setResponse( - new MockLowLevelHttpResponse().setStatusCode(statusCode).setContent(responseContent)); - doReturn(request).when(transport).buildRequest("POST", url); - } - - private void verifyRequest(String url) throws IOException { - verify(transport).buildRequest("POST", url); - verify(request).execute(); - } - @Test - public void testCreatePrivateKeyCredentialsWithNullKeyType() throws Exception { + void testCreatePrivateKeyCredentialsWithNullKeyType(JenkinsRule jenkins) throws Exception { GoogleRobotPrivateKeyCredentials credentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, module); - try { - credentials.getUsername(); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.KeyTypeNotSetException ignored) { - } - - try { - credentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.KeyTypeNotSetException ignored) { - } + assertThrows(GoogleRobotPrivateKeyCredentials.KeyTypeNotSetException.class, credentials::getUsername); + assertThrows( + GoogleRobotPrivateKeyCredentials.KeyTypeNotSetException.class, + () -> credentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testUpgradeLegacyCredentials() throws Exception { + void testUpgradeLegacyCredentials(JenkinsRule jenkins) throws Exception { GoogleRobotPrivateKeyCredentials legacyCredentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, null); setPrivateField(legacyCredentials, "secretsFile", legacyJsonKeyPath); @@ -212,27 +190,21 @@ public void testUpgradeLegacyCredentials() throws Exception { } @Test - public void testUpgradeLegacyCredentialsWithoutSecretsFile() throws Exception { + void testUpgradeLegacyCredentialsWithoutSecretsFile(JenkinsRule jenkins) throws Exception { GoogleRobotPrivateKeyCredentials legacyCredentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, null); setPrivateField(legacyCredentials, "p12File", p12KeyPath); GoogleRobotPrivateKeyCredentials upgradedCredentials = (GoogleRobotPrivateKeyCredentials) legacyCredentials.readResolve(); - try { - upgradedCredentials.getUsername(); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } - try { - upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } + assertThrows(GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, upgradedCredentials::getUsername); + assertThrows( + GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, + () -> upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testUpgradeLegacyCredentialsWithMissingWebObject() throws Exception { + void testUpgradeLegacyCredentialsWithMissingWebObject(JenkinsRule jenkins) throws Exception { String legacyJsonKeyFileWithMissingWebObject = LegacyJsonServiceAccountConfigUtil.createTempLegacyJsonKeyFileWithMissingWebObject(); GoogleRobotPrivateKeyCredentials legacyCredentials = @@ -242,20 +214,14 @@ public void testUpgradeLegacyCredentialsWithMissingWebObject() throws Exception GoogleRobotPrivateKeyCredentials upgradedCredentials = (GoogleRobotPrivateKeyCredentials) legacyCredentials.readResolve(); - try { - upgradedCredentials.getUsername(); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } - try { - upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } + assertThrows(GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, upgradedCredentials::getUsername); + assertThrows( + GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, + () -> upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testUpgradeLegacyCredentialsWithMissingClientEmail() throws Exception { + void testUpgradeLegacyCredentialsWithMissingClientEmail(JenkinsRule jenkins) throws Exception { String legacyJsonKeyFileWithMissingClientEmail = LegacyJsonServiceAccountConfigUtil.createTempLegacyJsonKeyFileWithMissingClientEmail(); GoogleRobotPrivateKeyCredentials legacyCredentials = @@ -265,20 +231,14 @@ public void testUpgradeLegacyCredentialsWithMissingClientEmail() throws Exceptio GoogleRobotPrivateKeyCredentials upgradedCredentials = (GoogleRobotPrivateKeyCredentials) legacyCredentials.readResolve(); - try { - upgradedCredentials.getUsername(); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } - try { - upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } + assertThrows(GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, upgradedCredentials::getUsername); + assertThrows( + GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, + () -> upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testUpgradeLegacyCredentialsWithInvalidSecretsFile() throws Exception { + void testUpgradeLegacyCredentialsWithInvalidSecretsFile(JenkinsRule jenkins) throws Exception { String invalidLegacyJsonKeyFile = LegacyJsonServiceAccountConfigUtil.createTempInvalidLegacyJsonKeyFile(); GoogleRobotPrivateKeyCredentials legacyCredentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, null); @@ -287,41 +247,29 @@ public void testUpgradeLegacyCredentialsWithInvalidSecretsFile() throws Exceptio GoogleRobotPrivateKeyCredentials upgradedCredentials = (GoogleRobotPrivateKeyCredentials) legacyCredentials.readResolve(); - try { - upgradedCredentials.getUsername(); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } - try { - upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } + assertThrows(GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, upgradedCredentials::getUsername); + assertThrows( + GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, + () -> upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testUpgradeLegacyCredentialsWithNotExistendSecretsFile() throws Exception { + void testUpgradeLegacyCredentialsWithNonExistentSecretsFile(JenkinsRule jenkins) throws Exception { GoogleRobotPrivateKeyCredentials legacyCredentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, null); - setPrivateField(legacyCredentials, "secretsFile", "/notExistendSecretsFile"); + setPrivateField(legacyCredentials, "secretsFile", "/nonExistentSecretsFile"); setPrivateField(legacyCredentials, "p12File", p12KeyPath); GoogleRobotPrivateKeyCredentials upgradedCredentials = (GoogleRobotPrivateKeyCredentials) legacyCredentials.readResolve(); - try { - upgradedCredentials.getUsername(); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } - try { - upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.AccountIdNotSetException ignored) { - } + assertThrows(GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, upgradedCredentials::getUsername); + assertThrows( + GoogleRobotPrivateKeyCredentials.AccountIdNotSetException.class, + () -> upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testUpgradeLegacyCredentialsWithoutP12File() throws Exception { + void testUpgradeLegacyCredentialsWithoutP12File(JenkinsRule jenkins) throws Exception { GoogleRobotPrivateKeyCredentials legacyCredentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, null); setPrivateField(legacyCredentials, "secretsFile", legacyJsonKeyPath); @@ -329,15 +277,13 @@ public void testUpgradeLegacyCredentialsWithoutP12File() throws Exception { (GoogleRobotPrivateKeyCredentials) legacyCredentials.readResolve(); assertEquals(SERVICE_ACCOUNT_EMAIL_ADDRESS, upgradedCredentials.getUsername()); - try { - upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE)); - fail(); - } catch (GoogleRobotPrivateKeyCredentials.PrivateKeyNotSetException ignored) { - } + assertThrows( + GoogleRobotPrivateKeyCredentials.PrivateKeyNotSetException.class, + () -> upgradedCredentials.getGoogleCredential(new TestGoogleOAuth2DomainRequirement(FAKE_SCOPE))); } @Test - public void testGetById() throws Exception { + void testGetById(JenkinsRule jenkins) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(jsonKeyPath); when(mockFileItem.getInputStream()).thenReturn(new FileInputStream(jsonKeyPath)); @@ -355,7 +301,7 @@ public void testGetById() throws Exception { // TODO(mattmoor): redundant with GoogleRobotMetadataCredentials since there // isn't a shared descriptor for validating common fields. @Test - public void testProjectIdValidation() throws Exception { + void testProjectIdValidation(JenkinsRule jenkins) { GoogleRobotPrivateKeyCredentials.Descriptor descriptor = (GoogleRobotPrivateKeyCredentials.Descriptor) Jenkins.getInstance().getDescriptorOrDie(GoogleRobotPrivateKeyCredentials.class); @@ -365,7 +311,7 @@ public void testProjectIdValidation() throws Exception { } @Test - public void testName() throws Exception { + void testName(JenkinsRule jenkins) throws Exception { GoogleRobotPrivateKeyCredentials credentials = new GoogleRobotPrivateKeyCredentials(CredentialsScope.GLOBAL, "", PROJECT_ID, "", null, module); SystemCredentialsProvider.getInstance().getCredentials().add(credentials); @@ -375,7 +321,7 @@ public void testName() throws Exception { } @Test - public void testCredentialCreationWithNonEmptyIdAndDescriptionAndJsonKey() throws Exception { + void testCredentialCreationWithNonEmptyIdAndDescriptionAndJsonKey(JenkinsRule jenkins) throws Exception { // GIVEN: Setup the mock and configuration for JSON key when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(jsonKeyPath); @@ -394,7 +340,7 @@ public void testCredentialCreationWithNonEmptyIdAndDescriptionAndJsonKey() throw } @Test - public void testCredentialCreationWithNonEmptyIdAndDescriptionAndP12() throws Exception { + void testCredentialCreationWithNonEmptyIdAndDescriptionAndP12(JenkinsRule jenkins) throws Exception { // GIVEN: Setup the mock and configuration for P12 key when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(p12KeyPath); @@ -413,7 +359,7 @@ public void testCredentialCreationWithNonEmptyIdAndDescriptionAndP12() throws Ex } @Test - public void testCredentialCreationWithSystemScope() throws Exception { + void testCredentialCreationWithSystemScope(JenkinsRule jenkins) throws Exception { // GIVEN: Setup the mock and configuration when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(jsonKeyPath); @@ -431,7 +377,7 @@ public void testCredentialCreationWithSystemScope() throws Exception { } @Test - public void testCredentialCreationWithGlobalScope() throws Exception { + void testCredentialCreationWithGlobalScope(JenkinsRule jenkins) throws Exception { // GIVEN: Setup the mock and configuration when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(jsonKeyPath); @@ -447,4 +393,22 @@ public void testCredentialCreationWithGlobalScope() throws Exception { // THEN: the resulting credential should have GLOBAL scope assertEquals(CredentialsScope.GLOBAL, credentials.getScope()); } + + private static void setPrivateField(GoogleRobotPrivateKeyCredentials credentials, String fieldName, Object value) + throws NoSuchFieldException, IllegalAccessException { + Field field = GoogleRobotPrivateKeyCredentials.class.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(credentials, value); + } + + private void stubRequest(String url, int statusCode, String responseContent) throws IOException { + request.setResponse( + new MockLowLevelHttpResponse().setStatusCode(statusCode).setContent(responseContent)); + doReturn(request).when(transport).buildRequest("POST", url); + } + + private void verifyRequest(String url) throws IOException { + verify(transport).buildRequest("POST", url); + verify(request).execute(); + } } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTest.java index b1a7e93..a141b2b 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTest.java @@ -15,8 +15,8 @@ */ package com.google.jenkins.plugins.credentials.oauth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; import com.cloudbees.plugins.credentials.SecretBytes; @@ -27,39 +27,33 @@ import java.security.PrivateKey; import org.apache.commons.fileupload.FileItem; import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +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; /** Tests for {@link JsonServiceAccountConfig}. */ -public class JsonServiceAccountConfigTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class JsonServiceAccountConfigTest { private static final String SERVICE_ACCOUNT_EMAIL_ADDRESS = "service@account.com"; private static PrivateKey privateKey; private static String jsonKeyPath; - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); - @Mock private FileItem mockFileItem; - @BeforeClass - public static void preparePrivateKey() throws Exception { + @BeforeAll + static void preparePrivateKey() throws Exception { privateKey = JsonServiceAccountConfigTestUtil.generatePrivateKey(); jsonKeyPath = JsonServiceAccountConfigTestUtil.createTempJsonKeyFile(SERVICE_ACCOUNT_EMAIL_ADDRESS, privateKey); } - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - @Test - public void testCreateJsonKeyTypeWithNewJsonKeyFile() throws Exception { + void testCreateJsonKeyTypeWithNewJsonKeyFile(JenkinsRule jenkinsRule) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getInputStream()).thenReturn(new FileInputStream(jsonKeyPath)); when(mockFileItem.getName()).thenReturn(jsonKeyPath); @@ -72,7 +66,7 @@ public void testCreateJsonKeyTypeWithNewJsonKeyFile() throws Exception { } @Test - public void testCreateJsonKeyTypeWithNullParameters() { + void testCreateJsonKeyTypeWithNullParameters(JenkinsRule jenkinsRule) { JsonServiceAccountConfig jsonServiceAccountConfig = new JsonServiceAccountConfig(); assertNull(jsonServiceAccountConfig.getAccountId()); @@ -80,7 +74,7 @@ public void testCreateJsonKeyTypeWithNullParameters() { } @Test - public void testCreateJsonKeyTypeWithEmptyJsonKeyFile() throws Exception { + void testCreateJsonKeyTypeWithEmptyJsonKeyFile(JenkinsRule jenkinsRule) { when(mockFileItem.getSize()).thenReturn(0L); JsonServiceAccountConfig jsonKeyType = new JsonServiceAccountConfig(); jsonKeyType.setJsonKeyFileUpload(mockFileItem); @@ -91,7 +85,7 @@ public void testCreateJsonKeyTypeWithEmptyJsonKeyFile() throws Exception { } @Test - public void testCreateJsonKeyTypeWithInvalidJsonKeyFile() throws Exception { + void testCreateJsonKeyTypeWithInvalidJsonKeyFile(JenkinsRule jenkinsRule) throws Exception { byte[] bytes = "invalidJsonKeyFile".getBytes(); when(mockFileItem.getSize()).thenReturn((long) bytes.length); when(mockFileItem.getInputStream()).thenReturn(new ByteArrayInputStream(bytes)); @@ -103,7 +97,7 @@ public void testCreateJsonKeyTypeWithInvalidJsonKeyFile() throws Exception { } @Test - public void testCreateJsonKeyTypeWithPrevJsonKeyFileForCompatibility() { + void testCreateJsonKeyTypeWithPrevJsonKeyFileForCompatibility(JenkinsRule jenkinsRule) { JsonServiceAccountConfig jsonServiceAccountConfig = new JsonServiceAccountConfig(null, jsonKeyPath); assertEquals(SERVICE_ACCOUNT_EMAIL_ADDRESS, jsonServiceAccountConfig.getAccountId()); @@ -111,7 +105,7 @@ public void testCreateJsonKeyTypeWithPrevJsonKeyFileForCompatibility() { } @Test - public void testCreateJsonKeyTypeWithPrevJsonKeyFile() throws Exception { + void testCreateJsonKeyTypeWithPrevJsonKeyFile(JenkinsRule jenkinsRule) throws Exception { SecretBytes prev = SecretBytes.fromBytes(FileUtils.readFileToByteArray(new File(jsonKeyPath))); JsonServiceAccountConfig jsonServiceAccountConfig = new JsonServiceAccountConfig(); jsonServiceAccountConfig.setFilename(jsonKeyPath); @@ -122,7 +116,7 @@ public void testCreateJsonKeyTypeWithPrevJsonKeyFile() throws Exception { } @Test - public void testCreateJsonKeyTypeWithEmptyPrevJsonKeyFile() { + void testCreateJsonKeyTypeWithEmptyPrevJsonKeyFile(JenkinsRule jenkinsRule) { SecretBytes prev = SecretBytes.fromString(""); JsonServiceAccountConfig jsonServiceAccountConfig = new JsonServiceAccountConfig(); jsonServiceAccountConfig.setFilename(""); @@ -133,7 +127,7 @@ public void testCreateJsonKeyTypeWithEmptyPrevJsonKeyFile() { } @Test - public void testCreateJsonKeyTypeWithInvalidPrevJsonKeyFile() { + void testCreateJsonKeyTypeWithInvalidPrevJsonKeyFile(JenkinsRule jenkinsRule) { JsonServiceAccountConfig jsonServiceAccountConfig = new JsonServiceAccountConfig(null, "invalidPrevJsonKeyFile.json"); @@ -142,7 +136,7 @@ public void testCreateJsonKeyTypeWithInvalidPrevJsonKeyFile() { } @Test - public void testSerialization() throws Exception { + void testSerialization(JenkinsRule jenkinsRule) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(jsonKeyPath); when(mockFileItem.getInputStream()).thenReturn(new FileInputStream(jsonKeyPath)); diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTestUtil.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTestUtil.java index 3290a2c..b95c6f1 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTestUtil.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/JsonServiceAccountConfigTestUtil.java @@ -21,7 +21,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.security.KeyPair; import java.security.KeyPairGenerator; @@ -33,7 +33,7 @@ import org.bouncycastle.openssl.PEMWriter; /** Util class for {@link JsonServiceAccountConfigTest}. */ -public class JsonServiceAccountConfigTestUtil { +class JsonServiceAccountConfigTestUtil { private static File tempFolder; public static PrivateKey generatePrivateKey() throws NoSuchProviderException, NoSuchAlgorithmException { @@ -46,24 +46,17 @@ public static PrivateKey generatePrivateKey() throws NoSuchProviderException, No public static String createTempJsonKeyFile(String clientEmail, PrivateKey privateKey) throws IOException { final File tempJsonKey = File.createTempFile("temp-key", ".json", getTempFolder()); - JsonGenerator jsonGenerator = null; - try { - jsonGenerator = new JacksonFactory() - .createJsonGenerator(new FileOutputStream(tempJsonKey), Charset.forName("UTF-8")); + try (JsonGenerator jsonGenerator = + new JacksonFactory().createJsonGenerator(new FileOutputStream(tempJsonKey), StandardCharsets.UTF_8)) { jsonGenerator.enablePrettyPrint(); jsonGenerator.serialize(createJsonKey(clientEmail, privateKey)); - } finally { - if (jsonGenerator != null) { - jsonGenerator.close(); - } } return tempJsonKey.getAbsolutePath(); } private static File getTempFolder() throws IOException { if (tempFolder == null) { - tempFolder = Files.createTempDirectory("temp" + Long.toString(System.nanoTime())) - .toFile(); + tempFolder = Files.createTempDirectory("temp" + System.nanoTime()).toFile(); tempFolder.deleteOnExit(); } return tempFolder; diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/LegacyJsonServiceAccountConfigUtil.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/LegacyJsonServiceAccountConfigUtil.java index 6f71152..cee1271 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/LegacyJsonServiceAccountConfigUtil.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/LegacyJsonServiceAccountConfigUtil.java @@ -20,20 +20,20 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; /** * Util class for {@link com.google.jenkins.plugins.credentials.oauth * .GoogleRobotPrivateKeyCredentials}. */ -public class LegacyJsonServiceAccountConfigUtil { +class LegacyJsonServiceAccountConfigUtil { private static File tempFolder; public static String createTempLegacyJsonKeyFile(String clientEmail) throws IOException { final File tempLegacyJsonKey = File.createTempFile("temp-legacykey", ".json", getTempFolder()); final JsonGenerator jsonGenerator = new JacksonFactory() - .createJsonGenerator(new FileOutputStream(tempLegacyJsonKey), Charset.forName("UTF-8")); + .createJsonGenerator(new FileOutputStream(tempLegacyJsonKey), StandardCharsets.UTF_8); jsonGenerator.enablePrettyPrint(); jsonGenerator.serialize(createLegacyJsonKey(clientEmail)); jsonGenerator.close(); @@ -43,7 +43,7 @@ public static String createTempLegacyJsonKeyFile(String clientEmail) throws IOEx public static String createTempLegacyJsonKeyFileWithMissingWebObject() throws IOException { final File tempLegacyJsonKey = File.createTempFile("temp-legacykey", ".json", getTempFolder()); final JsonGenerator jsonGenerator = new JacksonFactory() - .createJsonGenerator(new FileOutputStream(tempLegacyJsonKey), Charset.forName("UTF-8")); + .createJsonGenerator(new FileOutputStream(tempLegacyJsonKey), StandardCharsets.UTF_8); jsonGenerator.enablePrettyPrint(); jsonGenerator.serialize(createLegacyJsonKeyWithMissingWebObject()); jsonGenerator.close(); @@ -52,46 +52,33 @@ public static String createTempLegacyJsonKeyFileWithMissingWebObject() throws IO public static String createTempLegacyJsonKeyFileWithMissingClientEmail() throws IOException { final File tempLegacyJsonKey = File.createTempFile("temp-legacykey", ".json", getTempFolder()); - JsonGenerator jsonGenerator = null; - try { - jsonGenerator = new JacksonFactory() - .createJsonGenerator(new FileOutputStream(tempLegacyJsonKey), Charset.forName("UTF-8")); + try (JsonGenerator jsonGenerator = new JacksonFactory() + .createJsonGenerator(new FileOutputStream(tempLegacyJsonKey), StandardCharsets.UTF_8)) { jsonGenerator.enablePrettyPrint(); jsonGenerator.serialize(createLegacyJsonKeyWithMissingClientEmail()); - } finally { - if (jsonGenerator != null) { - jsonGenerator.close(); - } } return tempLegacyJsonKey.getAbsolutePath(); } public static String createTempInvalidLegacyJsonKeyFile() throws IOException { final File tempLegacyJsonKey = File.createTempFile("temp-legacykey", ".json", getTempFolder()); - FileOutputStream out = null; - try { - out = new FileOutputStream(tempLegacyJsonKey); + try (FileOutputStream out = new FileOutputStream(tempLegacyJsonKey)) { out.write("InvalidLegacyJsonKeyFile".getBytes()); out.flush(); - } finally { - if (out != null) { - out.close(); - } } return tempLegacyJsonKey.getAbsolutePath(); } private static File getTempFolder() throws IOException { if (tempFolder == null) { - tempFolder = Files.createTempDirectory("temp" + Long.toString(System.nanoTime())) - .toFile(); + tempFolder = Files.createTempDirectory("temp" + System.nanoTime()).toFile(); tempFolder.deleteOnExit(); } return tempFolder; } @SuppressWarnings("deprecation") - private static LegacyJsonKey createLegacyJsonKey(String clientEmail) throws IOException { + private static LegacyJsonKey createLegacyJsonKey(String clientEmail) { final LegacyJsonKey legacyJsonKey = new LegacyJsonKey(); LegacyJsonKey.Details web = new LegacyJsonKey.Details(); web.setClientEmail(clientEmail); @@ -100,12 +87,12 @@ private static LegacyJsonKey createLegacyJsonKey(String clientEmail) throws IOEx } @SuppressWarnings("deprecation") - private static LegacyJsonKey createLegacyJsonKeyWithMissingWebObject() throws IOException { + private static LegacyJsonKey createLegacyJsonKeyWithMissingWebObject() { return new LegacyJsonKey(); } @SuppressWarnings("deprecation") - private static LegacyJsonKey createLegacyJsonKeyWithMissingClientEmail() throws IOException { + private static LegacyJsonKey createLegacyJsonKeyWithMissingClientEmail() { final LegacyJsonKey legacyJsonKey = new LegacyJsonKey(); legacyJsonKey.setWeb(new LegacyJsonKey.Details()); return legacyJsonKey; diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTest.java index 9e448cc..97f5af4 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTest.java @@ -15,8 +15,8 @@ */ package com.google.jenkins.plugins.credentials.oauth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.when; import com.cloudbees.plugins.credentials.SecretBytes; @@ -26,40 +26,34 @@ import java.security.KeyPair; import org.apache.commons.fileupload.FileItem; import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +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; /** Tests for {@link P12ServiceAccountConfig}. */ -public class P12ServiceAccountConfigTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class P12ServiceAccountConfigTest { private static final String SERVICE_ACCOUNT_EMAIL_ADDRESS = "service@account.com"; private static KeyPair keyPair; private static String p12KeyPath; - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); - @Mock private FileItem mockFileItem; - @BeforeClass - public static void preparePrivateKey() throws Exception { + @BeforeAll + static void preparePrivateKey() throws Exception { keyPair = P12ServiceAccountConfigTestUtil.generateKeyPair(); p12KeyPath = P12ServiceAccountConfigTestUtil.createTempP12KeyFile(keyPair); } - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - @Test - public void testCreateWithNewP12KeyFile() throws Exception { + void testCreateWithNewP12KeyFile(JenkinsRule jenkinsRule) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(p12KeyPath); when(mockFileItem.get()).thenReturn(FileUtils.readFileToByteArray(new File(p12KeyPath))); @@ -71,7 +65,7 @@ public void testCreateWithNewP12KeyFile() throws Exception { } @Test - public void testCreateWithNullAccountId() throws Exception { + void testCreateWithNullAccountId(JenkinsRule jenkinsRule) throws Exception { SecretBytes prev = SecretBytes.fromBytes(FileUtils.readFileToByteArray(new File(p12KeyPath))); P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(null); p12ServiceAccountConfig.setFilename(p12KeyPath); @@ -83,7 +77,7 @@ public void testCreateWithNullAccountId() throws Exception { @Test @WithoutJenkins - public void testCreateWithNullP12KeyFile() { + void testCreateWithNullP12KeyFile(JenkinsRule jenkinsRule) { P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(SERVICE_ACCOUNT_EMAIL_ADDRESS); assertEquals(SERVICE_ACCOUNT_EMAIL_ADDRESS, p12ServiceAccountConfig.getAccountId()); @@ -92,7 +86,7 @@ public void testCreateWithNullP12KeyFile() { @Test @WithoutJenkins - public void testCreateWithEmptyP12KeyFile() throws Exception { + void testCreateWithEmptyP12KeyFile(JenkinsRule jenkinsRule) { when(mockFileItem.getSize()).thenReturn(0L); P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(SERVICE_ACCOUNT_EMAIL_ADDRESS); p12ServiceAccountConfig.setP12KeyFileUpload(mockFileItem); @@ -102,7 +96,7 @@ public void testCreateWithEmptyP12KeyFile() throws Exception { } @Test - public void testCreateWithInvalidP12KeyFile() { + void testCreateWithInvalidP12KeyFile(JenkinsRule jenkinsRule) { byte[] bytes = "invalidP12KeyFile".getBytes(); when(mockFileItem.getSize()).thenReturn((long) bytes.length); when(mockFileItem.getName()).thenReturn("invalidP12KeyFile"); @@ -115,7 +109,7 @@ public void testCreateWithInvalidP12KeyFile() { } @Test - public void testCreateWithPrevP12KeyFileForCompatibility() { + void testCreateWithPrevP12KeyFileForCompatibility(JenkinsRule jenkinsRule) { P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(SERVICE_ACCOUNT_EMAIL_ADDRESS, null, p12KeyPath); @@ -124,7 +118,7 @@ public void testCreateWithPrevP12KeyFileForCompatibility() { } @Test - public void testCreateWithPrevP12KeyFile() throws Exception { + void testCreateWithPrevP12KeyFile(JenkinsRule jenkinsRule) throws Exception { SecretBytes prev = SecretBytes.fromBytes(FileUtils.readFileToByteArray(new File(p12KeyPath))); P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(SERVICE_ACCOUNT_EMAIL_ADDRESS); p12ServiceAccountConfig.setFilename(p12KeyPath); @@ -135,7 +129,7 @@ public void testCreateWithPrevP12KeyFile() throws Exception { } @Test - public void testCreateWithEmptyPrevP12KeyFile() { + void testCreateWithEmptyPrevP12KeyFile(JenkinsRule jenkinsRule) { SecretBytes prev = SecretBytes.fromString(""); P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(SERVICE_ACCOUNT_EMAIL_ADDRESS); p12ServiceAccountConfig.setFilename(""); @@ -147,7 +141,7 @@ public void testCreateWithEmptyPrevP12KeyFile() { @Test @WithoutJenkins - public void testCreateWithInvalidPrevP12KeyFile() { + void testCreateWithInvalidPrevP12KeyFile(JenkinsRule jenkinsRule) { P12ServiceAccountConfig p12ServiceAccountConfig = new P12ServiceAccountConfig(SERVICE_ACCOUNT_EMAIL_ADDRESS); p12ServiceAccountConfig.setFilename("invalidPrevP12KeyFile.p12"); @@ -156,7 +150,7 @@ public void testCreateWithInvalidPrevP12KeyFile() { } @Test - public void testSerialization() throws Exception { + void testSerialization(JenkinsRule jenkinsRule) throws Exception { when(mockFileItem.getSize()).thenReturn(1L); when(mockFileItem.getName()).thenReturn(p12KeyPath); when(mockFileItem.get()).thenReturn(FileUtils.readFileToByteArray(new File(p12KeyPath))); diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTestUtil.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTestUtil.java index 02e4779..d92e625 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTestUtil.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/P12ServiceAccountConfigTestUtil.java @@ -43,7 +43,7 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; /** Util class for {@link P12ServiceAccountConfigTest}. */ -public class P12ServiceAccountConfigTestUtil { +class P12ServiceAccountConfigTestUtil { private static final String DEFAULT_P12_SECRET = "notasecret"; private static final String DEFAULT_P12_ALIAS = "privatekey"; private static File tempFolder; @@ -57,7 +57,7 @@ public static KeyPair generateKeyPair() throws NoSuchProviderException, NoSuchAl public static String createTempP12KeyFile(KeyPair keyPair) throws IOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException, - KeyStoreException, NoSuchProviderException { + KeyStoreException { File tempP12Key = File.createTempFile("temp-key", ".p12", getTempFolder()); writeKeyToFile(keyPair, tempP12Key); return tempP12Key.getAbsolutePath(); @@ -65,8 +65,7 @@ public static String createTempP12KeyFile(KeyPair keyPair) private static File getTempFolder() throws IOException { if (tempFolder == null) { - tempFolder = Files.createTempDirectory("temp" + Long.toString(System.nanoTime())) - .toFile(); + tempFolder = Files.createTempDirectory("temp" + System.nanoTime()).toFile(); tempFolder.deleteOnExit(); } return tempFolder; @@ -74,7 +73,7 @@ private static File getTempFolder() throws IOException { private static void writeKeyToFile(KeyPair keyPair, File tempP12Key) throws IOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException, - KeyStoreException, NoSuchProviderException { + KeyStoreException { FileOutputStream out = null; try { out = new FileOutputStream(tempP12Key); @@ -87,7 +86,7 @@ private static void writeKeyToFile(KeyPair keyPair, File tempP12Key) private static KeyStore createKeyStore(KeyPair keyPair) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, - OperatorCreationException, NoSuchProviderException { + OperatorCreationException { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null, null); keyStore.setKeyEntry( diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/RemotableGoogleCredentialsTest.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/RemotableGoogleCredentialsTest.java index 0470216..0489993 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/RemotableGoogleCredentialsTest.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/RemotableGoogleCredentialsTest.java @@ -15,9 +15,11 @@ */ package com.google.jenkins.plugins.credentials.oauth; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.closeTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import com.cloudbees.plugins.credentials.CredentialsNameProvider; @@ -27,13 +29,24 @@ import java.security.GeneralSecurityException; import org.joda.time.DateTime; import org.joda.time.DateTimeUtils; -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; /** Tests for {@link RemotableGoogleCredentials}. */ -public class RemotableGoogleCredentialsTest { +@ExtendWith(MockitoExtension.class) +class RemotableGoogleCredentialsTest { + + private static final long ERROR = 1; // 1 second error + private static final long IMMINENT_EXPIRATION_SECONDS = 60; + private static final long EXPIRATION_SECONDS = 1234; + private static final String USERNAME = "theUserName"; + private static final String PROJECT_ID = "foo.com:bar-baz"; + private static final String THE_SCOPE = "my.scope"; + private static final String BAD_SCOPE = "NOT.my.scope"; + private static final String ACCESS_TOKEN = "ThE.ToKeN"; private GoogleCredential fakeCredential; @@ -44,10 +57,8 @@ public class RemotableGoogleCredentialsTest { private GoogleRobotCredentialsModule module; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - + @BeforeEach + void setUp() throws Exception { // Freeze time DateTime now = new DateTime(); DateTimeUtils.setCurrentMillisFixed(now.getMillis()); @@ -63,7 +74,7 @@ public void setUp() throws Exception { } @Test - public void testUsername() throws Exception { + void testUsername() throws Exception { fakeCredential.setAccessToken(ACCESS_TOKEN); fakeCredential.setExpiresInSeconds(EXPIRATION_SECONDS); @@ -74,19 +85,23 @@ public void testUsername() throws Exception { assertEquals(CredentialsScope.GLOBAL, credentials.getScope()); } - @Test(expected = GeneralSecurityException.class) - public void testNullExpirationBadRefresh() throws Exception { - new RemotableGoogleCredentials(mockCredentials, testConsumer, module); + @Test + void testNullExpirationBadRefresh() { + assertThrows( + GeneralSecurityException.class, + () -> new RemotableGoogleCredentials(mockCredentials, testConsumer, module)); } - @Test(expected = GeneralSecurityException.class) - public void testImminentExpirationBadRefresh() throws Exception { + @Test + void testImminentExpirationBadRefresh() { fakeCredential.setExpiresInSeconds(IMMINENT_EXPIRATION_SECONDS); - new RemotableGoogleCredentials(mockCredentials, testConsumer, module); + assertThrows( + GeneralSecurityException.class, + () -> new RemotableGoogleCredentials(mockCredentials, testConsumer, module)); } @Test - public void testReasonableExpiration() throws Exception { + void testReasonableExpiration() throws Exception { fakeCredential.setAccessToken(ACCESS_TOKEN); fakeCredential.setExpiresInSeconds(EXPIRATION_SECONDS); @@ -97,31 +112,23 @@ public void testReasonableExpiration() throws Exception { assertThat(credential.getExpiresInSeconds().doubleValue(), closeTo(EXPIRATION_SECONDS, 2)); } - public void testName() throws Exception { + @Test + void testName() throws Exception { fakeCredential.setAccessToken(ACCESS_TOKEN); fakeCredential.setExpiresInSeconds(EXPIRATION_SECONDS); GoogleRobotCredentials credentials = new RemotableGoogleCredentials(mockCredentials, testConsumer, module); - assertEquals("RemotableGoogleCredentials", CredentialsNameProvider.name(credentials)); + assertThat( + CredentialsNameProvider.name(credentials), + matchesPattern("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")); } - @Test(expected = UnsupportedOperationException.class) - public void testUnsupportedDescriptor() throws Exception { + @Test + void testUnsupportedDescriptor() throws GeneralSecurityException { fakeCredential.setAccessToken(ACCESS_TOKEN); fakeCredential.setExpiresInSeconds(EXPIRATION_SECONDS); - GoogleRobotCredentials credentials = new RemotableGoogleCredentials(mockCredentials, testConsumer, module); - - credentials.getDescriptor(); + assertThrows(UnsupportedOperationException.class, credentials::getDescriptor); } - - private static final long ERROR = 1; // 1 second error - private static final long IMMINENT_EXPIRATION_SECONDS = 60; - private static final long EXPIRATION_SECONDS = 1234; - private static final String USERNAME = "theUserName"; - private static final String PROJECT_ID = "foo.com:bar-baz"; - private static final String THE_SCOPE = "my.scope"; - private static final String BAD_SCOPE = "NOT.my.scope"; - private static final String ACCESS_TOKEN = "ThE.ToKeN"; } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/SerializationUtil.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/SerializationUtil.java index ffdfd1c..a9c44cc 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/SerializationUtil.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/SerializationUtil.java @@ -18,35 +18,17 @@ import java.io.*; /** Helper class for Serialization */ -public class SerializationUtil { +class SerializationUtil { public static void serialize(Object object, OutputStream out) throws IOException { - ObjectOutputStream objectOut = null; - try { - objectOut = new ObjectOutputStream(out); + try (ObjectOutputStream objectOut = new ObjectOutputStream(out)) { objectOut.writeObject(object); - } finally { - if (objectOut != null) { - try { - objectOut.close(); - } catch (IOException ignored) { - } - } } } public static T deserialize(Class clazz, InputStream in) throws IOException, ClassNotFoundException, ClassCastException { - ObjectInputStream objectIn = null; - try { - objectIn = new ObjectInputStream(in); + try (ObjectInputStream objectIn = new ObjectInputStream(in)) { return clazz.cast(objectIn.readObject()); - } finally { - if (objectIn != null) { - try { - objectIn.close(); - } catch (IOException ignored) { - } - } } } } diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestGoogleOAuth2DomainRequirement.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestGoogleOAuth2DomainRequirement.java index c183a2d..e778db9 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestGoogleOAuth2DomainRequirement.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestGoogleOAuth2DomainRequirement.java @@ -15,11 +15,13 @@ */ package com.google.jenkins.plugins.credentials.oauth; +import java.io.Serial; import java.util.Collection; import java.util.Collections; /** This is a trivial implementation of a {@link GoogleOAuth2ScopeRequirement}. */ public class TestGoogleOAuth2DomainRequirement extends GoogleOAuth2ScopeRequirement { + @Serial private static final long serialVersionUID = 2234181311205118742L; public TestGoogleOAuth2DomainRequirement(String scope) { diff --git a/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestRobotBuilder.java b/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestRobotBuilder.java index c49cc9a..127c561 100644 --- a/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestRobotBuilder.java +++ b/src/test/java/com/google/jenkins/plugins/credentials/oauth/TestRobotBuilder.java @@ -16,6 +16,7 @@ package com.google.jenkins.plugins.credentials.oauth; import com.google.jenkins.plugins.credentials.domains.RequiresDomain; +import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Descriptor; import hudson.tasks.Builder; @@ -25,6 +26,7 @@ */ @RequiresDomain(value = TestGoogleOAuth2DomainRequirement.class) public class TestRobotBuilder extends Builder { + public TestRobotBuilder() {} @Override @@ -35,6 +37,7 @@ public DescriptorImpl getDescriptor() { /** Descriptor for our trivial builder */ public static final class DescriptorImpl extends Descriptor { @Override + @NonNull public String getDisplayName() { return "Test Robot Builder"; } diff --git a/src/test/java/com/google/jenkins/plugins/util/ExecutorTest.java b/src/test/java/com/google/jenkins/plugins/util/ExecutorTest.java index 4b370e7..f716770 100644 --- a/src/test/java/com/google/jenkins/plugins/util/ExecutorTest.java +++ b/src/test/java/com/google/jenkins/plugins/util/ExecutorTest.java @@ -18,19 +18,24 @@ import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_FORBIDDEN; import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_NOT_FOUND; import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_SERVER_ERROR; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest; import com.google.api.client.http.HttpResponseException; import java.net.SocketTimeoutException; -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; /** Tests for {@link Executor}. */ -public class ExecutorTest { +@ExtendWith(MockitoExtension.class) +class ExecutorTest { + + private static final String STATUS_MESSAGE = "doesn't matter"; private HttpResponseException notFoundJsonException; private HttpResponseException conflictJsonException; @@ -46,10 +51,8 @@ public class ExecutorTest { private Executor underTest; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - + @BeforeEach + void setUp() { notFoundJsonException = new HttpResponseException.Builder(STATUS_CODE_NOT_FOUND, STATUS_MESSAGE, headers).build(); conflictJsonException = @@ -70,55 +73,49 @@ public void sleep() { } @Test - public void testVanillaNewExecutor() throws Exception { + void testVanillaNewExecutor() throws Exception { assertNotNull(underTest); - when(mockRequest.execute()).thenReturn((Void) null); + when(mockRequest.execute()).thenReturn(null); underTest.execute(mockRequest); } - @Test(expected = NotFoundException.class) - public void testNewExecutorWithNotFound() throws Exception { + @Test + void testNewExecutorWithNotFound() throws Exception { assertNotNull(underTest); when(mockRequest.execute()).thenThrow(notFoundJsonException); - - underTest.execute(mockRequest); + assertThrows(NotFoundException.class, () -> underTest.execute(mockRequest)); } - @Test(expected = ConflictException.class) - public void testNewExecutorWithConflict() throws Exception { + @Test + void testNewExecutorWithConflict() throws Exception { assertNotNull(underTest); when(mockRequest.execute()).thenThrow(conflictJsonException); - - underTest.execute(mockRequest); + assertThrows(ConflictException.class, () -> underTest.execute(mockRequest)); } - @Test(expected = ForbiddenException.class) - public void testNewExecutorWithForbidden() throws Exception { + @Test + void testNewExecutorWithForbidden() throws Exception { assertNotNull(underTest); when(mockRequest.execute()).thenThrow(forbiddenJsonException); - - underTest.execute(mockRequest); + assertThrows(ForbiddenException.class, () -> underTest.execute(mockRequest)); } - @Test(expected = HttpResponseException.class) - public void testNewExecutorWithAllErrors() throws Exception { + @Test + void testNewExecutorWithAllErrors() throws Exception { assertNotNull(underTest); when(mockRequest.execute()).thenThrow(errorJsonException); - - underTest.execute(mockRequest); + assertThrows(HttpResponseException.class, () -> underTest.execute(mockRequest)); } @Test - public void testNewExecutorWithErrorsThenSuccess() throws Exception { + void testNewExecutorWithErrorsThenSuccess() throws Exception { assertNotNull(underTest); when(mockRequest.execute()) .thenThrow(errorJsonException) .thenThrow(timeoutException) - .thenReturn((Void) null); + .thenReturn(null); underTest.execute(mockRequest); } - - private static final String STATUS_MESSAGE = "doesn't matter"; } diff --git a/src/test/java/com/google/jenkins/plugins/util/MetadataReaderTest.java b/src/test/java/com/google/jenkins/plugins/util/MetadataReaderTest.java index f5bf711..d3c7a8d 100644 --- a/src/test/java/com/google/jenkins/plugins/util/MetadataReaderTest.java +++ b/src/test/java/com/google/jenkins/plugins/util/MetadataReaderTest.java @@ -19,9 +19,10 @@ import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_OK; import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_UNAUTHORIZED; import static com.google.common.collect.Iterables.getOnlyElement; -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.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -30,32 +31,26 @@ import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; -import org.mockito.MockitoAnnotations; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link MetadataReader}. */ -public class MetadataReaderTest { - private MockHttpTransport transport; - private MockLowLevelHttpRequest request; +@ExtendWith(MockitoExtension.class) +class MetadataReaderTest { - private void stubRequest(String url, int statusCode, String responseContent) throws IOException { - request.setResponse( - new MockLowLevelHttpResponse().setStatusCode(statusCode).setContent(responseContent)); - doReturn(request).when(transport).buildRequest("GET", url); - } + private static final String METADATA_ENDPOINT = "http://metadata/computeMetadata/v1"; + private static final String MY_KEY = "/my/metadata/path"; + private static final String MY_VALUE = "RaNdOm value"; - private void verifyRequest(String key) throws IOException { - verify(transport).buildRequest("GET", METADATA_ENDPOINT + key); - verify(request).execute(); - assertEquals("Google", getOnlyElement(request.getHeaderValues("Metadata-Flavor"))); - } + private MockHttpTransport transport; + private MockLowLevelHttpRequest request; private MetadataReader underTest; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @BeforeEach + void setUp() { transport = spy(new MockHttpTransport()); request = spy(new MockLowLevelHttpRequest()); @@ -63,7 +58,7 @@ public void setUp() throws Exception { } @Test - public void testHasMetadata() throws Exception { + void testHasMetadata() throws Exception { stubRequest(METADATA_ENDPOINT, STATUS_CODE_OK, "hi"); assertTrue(underTest.hasMetadata()); @@ -71,7 +66,7 @@ public void testHasMetadata() throws Exception { } @Test - public void testHasNoMetadata() throws Exception { + void testHasNoMetadata() throws Exception { stubRequest(METADATA_ENDPOINT, STATUS_CODE_NOT_FOUND, "hi"); assertFalse(underTest.hasMetadata()); @@ -79,7 +74,7 @@ public void testHasNoMetadata() throws Exception { } @Test - public void testHasNoMetadata2() throws Exception { + void testHasNoMetadata2() throws Exception { stubRequest(METADATA_ENDPOINT, 409, "hi"); assertFalse(underTest.hasMetadata()); @@ -87,47 +82,58 @@ public void testHasNoMetadata2() throws Exception { } @Test - public void testReadMetadata() throws Exception { + void testReadMetadata() throws Exception { stubRequest(METADATA_ENDPOINT + MY_KEY, STATUS_CODE_OK, MY_VALUE); assertEquals(MY_VALUE, underTest.readMetadata(MY_KEY)); verifyRequest(MY_KEY); } - @Test(expected = NotFoundException.class) - public void testReadMissingMetadata() throws Exception { + @Test + void testReadMissingMetadata() throws Exception { stubRequest(METADATA_ENDPOINT + MY_KEY, STATUS_CODE_NOT_FOUND, MY_VALUE); - - try { - underTest.readMetadata(MY_KEY); - } finally { - verifyRequest(MY_KEY); - } + assertThrows(NotFoundException.class, () -> { + try { + underTest.readMetadata(MY_KEY); + } finally { + verifyRequest(MY_KEY); + } + }); } - @Test(expected = ForbiddenException.class) - public void testReadUnauthorizedMetadata() throws Exception { + @Test + void testReadUnauthorizedMetadata() throws Exception { stubRequest(METADATA_ENDPOINT + MY_KEY, STATUS_CODE_UNAUTHORIZED, MY_VALUE); - - try { - underTest.readMetadata(MY_KEY); - } finally { - verifyRequest(MY_KEY); - } + assertThrows(ForbiddenException.class, () -> { + try { + underTest.readMetadata(MY_KEY); + } finally { + verifyRequest(MY_KEY); + } + }); } - @Test(expected = IOException.class) - public void testReadUnrecognizedMetadataException() throws Exception { + @Test + void testReadUnrecognizedMetadataException() throws Exception { stubRequest(METADATA_ENDPOINT + MY_KEY, 409, MY_VALUE); + assertThrows(IOException.class, () -> { + try { + underTest.readMetadata(MY_KEY); + } finally { + verifyRequest(MY_KEY); + } + }); + } - try { - underTest.readMetadata(MY_KEY); - } finally { - verifyRequest(MY_KEY); - } + private void stubRequest(String url, int statusCode, String responseContent) throws IOException { + request.setResponse( + new MockLowLevelHttpResponse().setStatusCode(statusCode).setContent(responseContent)); + doReturn(request).when(transport).buildRequest("GET", url); } - private static String METADATA_ENDPOINT = "http://metadata/computeMetadata/v1"; - private static String MY_KEY = "/my/metadata/path"; - private static String MY_VALUE = "RaNdOm value"; + private void verifyRequest(String key) throws IOException { + verify(transport).buildRequest("GET", METADATA_ENDPOINT + key); + verify(request).execute(); + assertEquals("Google", getOnlyElement(request.getHeaderValues("Metadata-Flavor"))); + } } diff --git a/src/test/java/com/google/jenkins/plugins/util/MockExecutorTest.java b/src/test/java/com/google/jenkins/plugins/util/MockExecutorTest.java index 6d7958a..3e32409 100644 --- a/src/test/java/com/google/jenkins/plugins/util/MockExecutorTest.java +++ b/src/test/java/com/google/jenkins/plugins/util/MockExecutorTest.java @@ -15,94 +15,74 @@ */ package com.google.jenkins.plugins.util; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -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.Mockito.when; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient; import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest; import com.google.common.base.Predicates; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.Verifier; +import org.junit.jupiter.api.AfterEach; +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; /** Tests for the {@link MockExecutor}. */ -public class MockExecutorTest { +@ExtendWith(MockitoExtension.class) +class MockExecutorTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); + private static final String theString = "tHe StRiNg!"; + private static final String theOtherString = "tHe OtHeR sTrInG!"; @Mock private AbstractGoogleJsonClientRequest mockRequest; - private static class FakeRequest extends AbstractGoogleJsonClientRequest { - private FakeRequest(AbstractGoogleJsonClient client, String s, String t, Object o) { - super(client, s, t, o, String.class); - } - } - ; - @Mock private FakeRequest otherMockRequest; - private static final String theString = "tHe StRiNg!"; - private static final String theOtherString = "tHe OtHeR sTrInG!"; - - private MockExecutor executor = new MockExecutor(); + private final MockExecutor executor = new MockExecutor(); - @Rule - public Verifier verifySawAll = new Verifier() { - @Override - public void verify() { - assertTrue(executor.sawAll()); - } - }; - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + @AfterEach + void tearDown() { + assertTrue(executor.sawAll()); } @Test - public void testEmpty() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage(containsString("Unexpected request")); - - try { - executor.execute(mockRequest); - } finally { - assertTrue(executor.sawUnexpected()); - } + void testEmpty() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + try { + executor.execute(mockRequest); + } finally { + assertTrue(executor.sawUnexpected()); + } + }); + assertThat(exception.getMessage(), containsString("Unexpected request")); } @Test - public void testFailingPredicate() throws Exception { - // Make sure that when a false predicate occurs, we throw - // an exception - executor.when( - mockRequest.getClass(), - theOtherString, - Predicates.>alwaysFalse()); - - thrown.expect(IllegalStateException.class); - thrown.expectMessage(containsString("User predicate")); - - try { - executor.execute(mockRequest); - } finally { - assertTrue(executor.sawUnexpected()); - } + void testFailingPredicate() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + // Make sure that when a false predicate occurs, we throw + // an exception + executor.when(mockRequest.getClass(), theOtherString, Predicates.alwaysFalse()); + + try { + executor.execute(mockRequest); + } finally { + assertTrue(executor.sawUnexpected()); + } + }); + assertThat(exception.getMessage(), containsString("User predicate")); } @Test - public void testWhen() throws Exception { + void testWhen() throws Exception { executor.when(mockRequest.getClass(), theOtherString); assertEquals(theOtherString, executor.execute(mockRequest)); @@ -110,14 +90,14 @@ public void testWhen() throws Exception { } @Test - public void testOutOfOrder() throws Exception { - executor.when(otherMockRequest.getClass(), theOtherString); + void testOutOfOrder() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + executor.when(otherMockRequest.getClass(), theOtherString); - thrown.expect(IllegalStateException.class); - thrown.expectMessage(containsString("out of order")); - - executor.execute(mockRequest); - assertFalse(executor.sawUnexpected()); + executor.execute(mockRequest); + assertFalse(executor.sawUnexpected()); + }); + assertThat(exception.getMessage(), containsString("out of order")); } private static final class MyException extends IOException { @@ -127,21 +107,21 @@ public MyException(String message) { } @Test - public void testThrowWhen() throws Exception { - executor.throwWhen(mockRequest.getClass(), new MyException(theString)); - - thrown.expect(MyException.class); - thrown.expectMessage(theString); - - try { - executor.execute(mockRequest); - } finally { - assertFalse(executor.sawUnexpected()); - } + void testThrowWhen() { + Throwable exception = assertThrows(MyException.class, () -> { + executor.throwWhen(mockRequest.getClass(), new MyException(theString)); + + try { + executor.execute(mockRequest); + } finally { + assertFalse(executor.sawUnexpected()); + } + }); + assertTrue(exception.getMessage().contains(theString)); } @Test - public void testPassThruWhen() throws Exception { + void testPassThruWhen() throws Exception { when(mockRequest.getJsonContent()).thenReturn(theString); executor.passThruWhen(mockRequest.getClass()); @@ -151,4 +131,10 @@ public void testPassThruWhen() throws Exception { assertFalse(executor.sawUnexpected()); } } + + private static class FakeRequest extends AbstractGoogleJsonClientRequest { + private FakeRequest(AbstractGoogleJsonClient client, String s, String t, Object o) { + super(client, s, t, o, String.class); + } + } } diff --git a/src/test/java/com/google/jenkins/plugins/util/NameValuePairTest.java b/src/test/java/com/google/jenkins/plugins/util/NameValuePairTest.java index 259fcff..7c408e9 100644 --- a/src/test/java/com/google/jenkins/plugins/util/NameValuePairTest.java +++ b/src/test/java/com/google/jenkins/plugins/util/NameValuePairTest.java @@ -15,27 +15,28 @@ */ package com.google.jenkins.plugins.util; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link NameValuePair} */ -public class NameValuePairTest { +class NameValuePairTest { + @Test - public void testBasicString() { + void testBasicString() { final String first = "a"; final String second = "b"; - NameValuePair pair = new NameValuePair(first, second); + NameValuePair pair = new NameValuePair<>(first, second); assertSame(first, pair.getName()); assertSame(second, pair.getValue()); } @Test - public void testBasicWithObject() { + void testBasicWithObject() { final String first = "a"; final Object second = new Object(); - NameValuePair pair = new NameValuePair(first, second); + NameValuePair pair = new NameValuePair<>(first, second); assertSame(first, pair.getName()); assertSame(second, pair.getValue()); diff --git a/src/test/java/com/google/jenkins/plugins/util/ResolveTest.java b/src/test/java/com/google/jenkins/plugins/util/ResolveTest.java index bd85c47..0aabb41 100644 --- a/src/test/java/com/google/jenkins/plugins/util/ResolveTest.java +++ b/src/test/java/com/google/jenkins/plugins/util/ResolveTest.java @@ -15,32 +15,31 @@ */ package com.google.jenkins.plugins.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.mockito.MockitoAnnotations; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link Resolve}'s static methods. */ -public class ResolveTest { +@ExtendWith(MockitoExtension.class) +class ResolveTest { - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } + private static final String OVERRIDE = "my variable override"; + private static final String UNKNOWN_VAR = "$foo"; @Test - public void testBasicResolve() { + void testBasicResolve() { String basicInput = "la dee da $BUILD_NUMBER"; assertThat(Resolve.resolveBuiltin(basicInput), Matchers.not(Matchers.containsString("BUILD_NUMBER"))); } @Test - public void testUserOverride() { + void testUserOverride() { String basicInput = "$BUILD_NUMBER"; assertEquals( @@ -49,17 +48,14 @@ public void testUserOverride() { } @Test - public void testJustUserOverrides() { + void testJustUserOverrides() { String basicInput = "$bar"; assertEquals(OVERRIDE, Resolve.resolveCustom(basicInput, Collections.singletonMap("bar", OVERRIDE))); } @Test - public void testNoVariable() { + void testNoVariable() { assertEquals(UNKNOWN_VAR, Resolve.resolveBuiltin(UNKNOWN_VAR)); } - - private static final String OVERRIDE = "my variable override"; - private static final String UNKNOWN_VAR = "$foo"; }