From 8e8c73a21fdfc70cd0f257021e7ce116d1e14866 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 30 Sep 2021 22:04:18 +0000 Subject: [PATCH 1/9] chore: release 1.2.1-SNAPSHOT (#753) :robot: I have created a release \*beep\* \*boop\* --- ### Updating meta-information for bleeding-edge SNAPSHOT release. --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- appengine/pom.xml | 2 +- bom/pom.xml | 2 +- credentials/pom.xml | 2 +- oauth2_http/pom.xml | 2 +- pom.xml | 2 +- versions.txt | 12 ++++++------ 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/appengine/pom.xml b/appengine/pom.xml index 6f59c330f..1a24b88af 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.0 + 1.2.1-SNAPSHOT ../pom.xml diff --git a/bom/pom.xml b/bom/pom.xml index 88ec76dff..ccdc4161b 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.auth google-auth-library-bom - 1.2.0 + 1.2.1-SNAPSHOT pom Google Auth Library for Java BOM diff --git a/credentials/pom.xml b/credentials/pom.xml index c71bf74de..e7ebb44d7 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -4,7 +4,7 @@ com.google.auth google-auth-library-parent - 1.2.0 + 1.2.1-SNAPSHOT ../pom.xml diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index b2a37442e..6852cce09 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.0 + 1.2.1-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index 7300b9994..619cf1ec2 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.auth google-auth-library-parent - 1.2.0 + 1.2.1-SNAPSHOT pom Google Auth Library for Java Client libraries providing authentication and diff --git a/versions.txt b/versions.txt index f76a192d8..bedd86331 100644 --- a/versions.txt +++ b/versions.txt @@ -1,9 +1,9 @@ # Format: # module:released-version:current-version -google-auth-library:1.2.0:1.2.0 -google-auth-library-bom:1.2.0:1.2.0 -google-auth-library-parent:1.2.0:1.2.0 -google-auth-library-appengine:1.2.0:1.2.0 -google-auth-library-credentials:1.2.0:1.2.0 -google-auth-library-oauth2-http:1.2.0:1.2.0 +google-auth-library:1.2.0:1.2.1-SNAPSHOT +google-auth-library-bom:1.2.0:1.2.1-SNAPSHOT +google-auth-library-parent:1.2.0:1.2.1-SNAPSHOT +google-auth-library-appengine:1.2.0:1.2.1-SNAPSHOT +google-auth-library-credentials:1.2.0:1.2.1-SNAPSHOT +google-auth-library-oauth2-http:1.2.0:1.2.1-SNAPSHOT From ac70a279bdaf681507d7815264a3f5e92fd2aaa6 Mon Sep 17 00:00:00 2001 From: Timur Sadykov Date: Mon, 4 Oct 2021 13:13:57 -0700 Subject: [PATCH 2/9] fix: disabling self-signed jwt for domain wide delegation (#754) * disabling self-signed jwt for domain wide delegation * fix: nit fixes --- .../oauth2/ServiceAccountCredentials.java | 3 +- .../oauth2/ServiceAccountCredentialsTest.java | 40 +++++++++++++++++-- .../google/auth/oauth2/TokenVerifierTest.java | 2 - 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java b/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java index 27d67f809..201fdf593 100644 --- a/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java +++ b/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java @@ -1018,7 +1018,8 @@ public Map> getRequestMetadata(URI uri) throws IOException // If scopes are provided but we cannot use self signed JWT, then use scopes to get access // token. - if (!createScopedRequired() && !useJwtAccessWithScope) { + if ((!createScopedRequired() && !useJwtAccessWithScope) + || (serviceAccountUser != null && serviceAccountUser.length() > 0)) { return super.getRequestMetadata(uri); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 803d4fc8f..1e0be6b3f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -1355,7 +1355,6 @@ public void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { .setPrivateKey(privateKey) .setPrivateKeyId(PRIVATE_KEY_ID) .setScopes(SCOPES) - .setServiceAccountUser(USER) .setProjectId(PROJECT_ID) .setHttpTransportFactory(new MockTokenServerTransportFactory()) .setUseJwtAccessWithScope(true) @@ -1366,7 +1365,11 @@ public void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { } @Test - public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { + public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { + final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; + final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; + MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); + MockTokenServerTransport transport = transportFactory.transport; PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1374,8 +1377,39 @@ public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { .setClientEmail(CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(PRIVATE_KEY_ID) + .setScopes(SCOPES) .setServiceAccountUser(USER) .setProjectId(PROJECT_ID) + .setHttpTransportFactory(transportFactory) + .setUseJwtAccessWithScope(true) + .build(); + + transport.addServiceAccount(CLIENT_EMAIL, accessToken1); + Map> metadata = credentials.getRequestMetadata(CALL_URI); + TestUtils.assertContainsBearerToken(metadata, accessToken1); + + try { + verifyJwtAccess(metadata, "dummy.scope"); + fail("jwt access should fail with ServiceAccountUser"); + } catch (Exception ex) { + // expected + } + + transport.addServiceAccount(CLIENT_EMAIL, accessToken2); + credentials.refresh(); + TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); + } + + @Test + public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { + PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); + GoogleCredentials credentials = + ServiceAccountCredentials.newBuilder() + .setClientId(CLIENT_ID) + .setClientEmail(CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(PRIVATE_KEY_ID) + .setProjectId(PROJECT_ID) .setHttpTransportFactory(new MockTokenServerTransportFactory()) .build(); @@ -1393,7 +1427,6 @@ public void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOExcept .setPrivateKey(privateKey) .setPrivateKeyId(PRIVATE_KEY_ID) .setScopes(null, SCOPES) - .setServiceAccountUser(USER) .setProjectId(PROJECT_ID) .setHttpTransportFactory(new MockTokenServerTransportFactory()) .setUseJwtAccessWithScope(true) @@ -1412,7 +1445,6 @@ public void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { .setClientEmail(CLIENT_EMAIL) .setPrivateKey(privateKey) .setPrivateKeyId(PRIVATE_KEY_ID) - .setServiceAccountUser(USER) .setProjectId(PROJECT_ID) .setQuotaProjectId("my-quota-project-id") .setHttpTransportFactory(new MockTokenServerTransportFactory()) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index 7255be4c3..e779828ff 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java @@ -242,8 +242,6 @@ public void verifyRs256TokenWithLegacyCertificateUrlFormat() @Test public void verifyServiceAccountRs256Token() throws TokenVerifier.VerificationException, IOException { - HttpTransportFactory httpTransportFactory = - mockTransport(SERVICE_ACCOUNT_CERT_URL, readResourceAsString("service_account_keys.json")); TokenVerifier tokenVerifier = TokenVerifier.newBuilder() .setClock(FIXED_CLOCK) From 567367844a0f4f132c329a5741d359a1f5a40cf7 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Fri, 8 Oct 2021 03:18:22 +0200 Subject: [PATCH 3/9] chore(deps): update dependency com.google.http-client:google-http-client-bom to v1.40.1 (#758) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 619cf1ec2..4ce843c1a 100644 --- a/pom.xml +++ b/pom.xml @@ -59,7 +59,7 @@ UTF-8 - 1.40.0 + 1.40.1 4.13.2 31.0.1-android 1.9.91 From cccaa4414ea26b5641ff233b8ffeddadf4a1b780 Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Fri, 8 Oct 2021 22:23:40 +0300 Subject: [PATCH 4/9] refactor: migration tests in appengine module from JUnit4 to JUnit5 (#756) (#760) --- .../appengine/AppEngineCredentialsTest.java | 61 ++++++++----------- appengine/pom.xml | 4 +- pom.xml | 8 +++ 3 files changed, 35 insertions(+), 38 deletions(-) diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index d37038d5e..41b52384a 100644 --- a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java +++ b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.appengine; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; @@ -51,13 +51,10 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for AppEngineCredentials */ -@RunWith(JUnit4.class) -public class AppEngineCredentialsTest extends BaseSerializationTest { +class AppEngineCredentialsTest extends BaseSerializationTest { private static Collection SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope1", "scope2")); @@ -65,7 +62,7 @@ public class AppEngineCredentialsTest extends BaseSerializationTest { private static final String EXPECTED_ACCOUNT = "serviceAccount"; @Test - public void constructor_usesAppIdentityService() throws IOException { + void constructor_usesAppIdentityService() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -83,7 +80,7 @@ public void constructor_usesAppIdentityService() throws IOException { } @Test - public void refreshAccessToken_sameAs() throws IOException { + void refreshAccessToken_sameAs() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -100,7 +97,7 @@ public void refreshAccessToken_sameAs() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() { MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setServiceAccountName(EXPECTED_ACCOUNT); AppEngineCredentials credentials = @@ -112,7 +109,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setSignature(expectedSignature); @@ -125,7 +122,7 @@ public void sign_sameAs() throws IOException { } @Test - public void createScoped_clonesWithScopes() throws IOException { + void createScoped_clonesWithScopes() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; Collection emptyScopes = Collections.emptyList(); @@ -138,11 +135,10 @@ public void createScoped_clonesWithScopes() throws IOException { .setAppIdentityService(appIdentity) .build(); assertTrue(credentials.createScopedRequired()); - try { - credentials.getRequestMetadata(CALL_URI); - fail("Should not be able to use credential without scopes."); - } catch (Exception expected) { - } + assertThrows( + Exception.class, + () -> credentials.getRequestMetadata(CALL_URI), + "Should not be able to use credential without scopes."); assertEquals(0, appIdentity.getGetAccessTokenCallCount()); GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); @@ -155,7 +151,7 @@ public void createScoped_clonesWithScopes() throws IOException { } @Test - public void equals_true() throws IOException { + void equals_true() { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -175,7 +171,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() { Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -195,7 +191,7 @@ public void equals_false_scopes() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() { String expectedToString = String.format( "AppEngineCredentials{scopes=[%s], scopesRequired=%b, appIdentityServiceClassName=%s}", @@ -213,7 +209,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -230,7 +226,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -249,14 +245,7 @@ private static void assertContainsBearerToken(Map> metadata assertNotNull(token); String expectedValue = "Bearer " + token; List authorizations = metadata.get("Authorization"); - assertNotNull("Authorization headers not found", authorizations); - boolean found = false; - for (String authorization : authorizations) { - if (expectedValue.equals(authorization)) { - found = true; - break; - } - } - assertTrue("Bearer token not found", found); + assertNotNull(authorizations, "Authorization headers not found"); + assertTrue(authorizations.contains(expectedValue), "Bearer token not found"); } } diff --git a/appengine/pom.xml b/appengine/pom.xml index 1a24b88af..4d4f77010 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -68,8 +68,8 @@ guava - junit - junit + org.junit.jupiter + junit-jupiter-api test diff --git a/pom.xml b/pom.xml index 4ce843c1a..aa9f36c67 100644 --- a/pom.xml +++ b/pom.xml @@ -61,6 +61,7 @@ UTF-8 1.40.1 4.13.2 + 5.8.1 31.0.1-android 1.9.91 3.0.2 @@ -71,6 +72,13 @@ + + org.junit + junit-bom + ${project.junit.bom.version} + pom + import + com.google.auth google-auth-library-credentials From a64d35cb8c099ec5d48185711866f306de9a1b6f Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Fri, 8 Oct 2021 22:47:27 +0300 Subject: [PATCH 5/9] refactor: migration tests in credentials module from JUnit4 to JUnit5 (#756) (#761) --- .../com/google/auth/SigningExceptionTest.java | 23 +++++++++---------- credentials/pom.xml | 4 ++-- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/credentials/javatests/com/google/auth/SigningExceptionTest.java b/credentials/javatests/com/google/auth/SigningExceptionTest.java index 0d7aa48c5..e498924a3 100644 --- a/credentials/javatests/com/google/auth/SigningExceptionTest.java +++ b/credentials/javatests/com/google/auth/SigningExceptionTest.java @@ -31,29 +31,28 @@ package com.google.auth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.auth.ServiceAccountSigner.SigningException; -import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SigningExceptionTest { +class SigningExceptionTest { private static final String EXPECTED_MESSAGE = "message"; private static final RuntimeException EXPECTED_CAUSE = new RuntimeException(); @Test - public void constructor() { + void constructor() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertEquals(EXPECTED_MESSAGE, signingException.getMessage()); assertSame(EXPECTED_CAUSE, signingException.getCause()); } @Test - public void equals_true() throws IOException { + void equals_true() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertTrue(signingException.equals(otherSigningException)); @@ -61,7 +60,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_message() throws IOException { + void equals_false_message() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException("otherMessage", EXPECTED_CAUSE); assertFalse(signingException.equals(otherSigningException)); @@ -69,7 +68,7 @@ public void equals_false_message() throws IOException { } @Test - public void equals_false_cause() throws IOException { + void equals_false_cause() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException("otherMessage", new RuntimeException()); @@ -78,7 +77,7 @@ public void equals_false_cause() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertEquals(signingException.hashCode(), otherSigningException.hashCode()); diff --git a/credentials/pom.xml b/credentials/pom.xml index e7ebb44d7..9ead18aa2 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -50,8 +50,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api test From 4e6576f3c0a883ec0b70051417dbd2166f15681d Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Sat, 9 Oct 2021 16:39:15 +0300 Subject: [PATCH 6/9] chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - first iteration (#756) (#762) * chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - first iteration (#756) * chore: expand imports (#756) --- .../auth/http/HttpCredentialsAdapterTest.java | 19 +- .../google/auth/oauth2/AccessTokenTest.java | 27 +-- .../auth/oauth2/AppEngineCredentialsTest.java | 78 +++---- .../auth/oauth2/AwsCredentialsTest.java | 160 ++++++------- .../auth/oauth2/AwsRequestSignerTest.java | 40 ++-- .../com/google/auth/oauth2/ClientIdTest.java | 62 ++--- .../oauth2/CloudShellCredentialsTest.java | 32 ++- .../oauth2/ComputeEngineCredentialsTest.java | 217 ++++++++---------- .../oauth2/CredentialAccessBoundaryTest.java | 201 ++++++++-------- .../FTServiceAccountCredentialsTest.java | 57 +++-- oauth2_http/pom.xml | 13 +- 11 files changed, 428 insertions(+), 478 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index 723cec837..96673b787 100644 --- a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java +++ b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java @@ -32,8 +32,8 @@ package com.google.auth.http; import static org.hamcrest.CoreMatchers.instanceOf; -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 com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; @@ -47,20 +47,17 @@ import com.google.auth.oauth2.OAuth2Credentials; import com.google.auth.oauth2.UserCredentials; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link HttpCredentialsAdapter}. */ -@RunWith(JUnit4.class) -public class HttpCredentialsAdapterTest { +class HttpCredentialsAdapterTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @Test - public void initialize_populatesOAuth2Credentials() throws IOException { + void initialize_populatesOAuth2Credentials() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -87,7 +84,7 @@ public void initialize_populatesOAuth2Credentials() throws IOException { } @Test - public void initialize_populatesOAuth2Credentials_handle401() throws IOException { + void initialize_populatesOAuth2Credentials_handle401() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; @@ -125,7 +122,7 @@ public void initialize_populatesOAuth2Credentials_handle401() throws IOException } @Test - public void initialize_noURI() throws IOException { + void initialize_noURI() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory tokenServerTransportFactory = @@ -154,7 +151,7 @@ public void initialize_noURI() throws IOException { } @Test - public void getCredentials() { + void getCredentials() { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java index 58a9d0501..12aef9fbc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java @@ -31,25 +31,22 @@ package com.google.auth.oauth2; -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.assertTrue; import java.io.IOException; import java.util.Date; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for AccessToken */ -@RunWith(JUnit4.class) -public class AccessTokenTest extends BaseSerializationTest { +class AccessTokenTest extends BaseSerializationTest { private static final String TOKEN = "AccessToken"; private static final Date EXPIRATION_DATE = new Date(); @Test - public void constructor() { + void constructor() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(TOKEN, accessToken.getTokenValue()); assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); @@ -57,7 +54,7 @@ public void constructor() { } @Test - public void equals_true() throws IOException { + void equals_true() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertTrue(accessToken.equals(otherAccessToken)); @@ -65,7 +62,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_token() throws IOException { + void equals_false_token() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken("otherToken", EXPIRATION_DATE); assertFalse(accessToken.equals(otherAccessToken)); @@ -73,7 +70,7 @@ public void equals_false_token() throws IOException { } @Test - public void equals_false_expirationDate() throws IOException { + void equals_false_expirationDate() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, new Date(EXPIRATION_DATE.getTime() + 42)); assertFalse(accessToken.equals(otherAccessToken)); @@ -81,7 +78,7 @@ public void equals_false_expirationDate() throws IOException { } @Test - public void toString_containsFields() { + void toString_containsFields() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); String expectedToString = String.format( @@ -91,14 +88,14 @@ public void toString_containsFields() { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index 82b76d879..6ba82ef75 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -31,12 +31,12 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableMap; import java.io.IOException; @@ -47,12 +47,9 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class AppEngineCredentialsTest extends BaseSerializationTest { +class AppEngineCredentialsTest extends BaseSerializationTest { private static final String EXPECTED_ACCESS_TOKEN = "ExpectedAccessToken"; private static final Date EXPECTED_EXPIRATION_DATE = @@ -66,7 +63,7 @@ public class AppEngineCredentialsTest extends BaseSerializationTest { Collections.unmodifiableCollection(Arrays.asList("scope3")); @Test - public void constructor_usesAppIdentityService() throws IOException { + void constructor_usesAppIdentityService() throws IOException { Collection scopes = Collections.singleton("SomeScope"); TestAppEngineCredentials credentials = new TestAppEngineCredentials(scopes); List forNameArgs = credentials.getForNameArgs(); @@ -78,23 +75,24 @@ public void constructor_usesAppIdentityService() throws IOException { } @Test - public void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { - try { - new TestAppEngineCredentialsNoSdk(); - fail("Credential expected to fail to load if credential class not present."); - } catch (IOException e) { - String message = e.getMessage(); - assertTrue(message.contains("Check that the App Engine SDK is deployed.")); - assertTrue(e.getCause() instanceof ClassNotFoundException); - assertTrue( - e.getCause() - .getMessage() - .contains(AppEngineCredentials.APP_IDENTITY_SERVICE_FACTORY_CLASS)); - } + void constructor_noAppEngineRuntime_throwsHelpfulLoadError() { + IOException exception = + assertThrows( + IOException.class, + TestAppEngineCredentialsNoSdk::new, + "Credential expected to fail to load if credential class not present."); + String message = exception.getMessage(); + assertTrue(message.contains("Check that the App Engine SDK is deployed.")); + assertTrue(exception.getCause() instanceof ClassNotFoundException); + assertTrue( + exception + .getCause() + .getMessage() + .contains(AppEngineCredentials.APP_IDENTITY_SERVICE_FACTORY_CLASS)); } @Test - public void refreshAccessToken_sameAs() throws IOException { + void refreshAccessToken_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); @@ -102,27 +100,25 @@ public void refreshAccessToken_sameAs() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(EXPECTED_ACCOUNT, credentials.getAccount()); } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertArrayEquals(EXPECTED_SIGNATURE, credentials.sign("Bytes to sign".getBytes())); } @Test - public void createScoped_clonesWithScopes() throws IOException { + void createScoped_clonesWithScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); - try { - credentials.refreshAccessToken(); - fail("Should not be able to use credential without scopes."); - } catch (Exception expected) { - // Expected - } + assertThrows( + Exception.class, + credentials::refreshAccessToken, + "Should not be able to use credential without scopes."); GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); assertNotSame(credentials, scopedCredentials); @@ -133,7 +129,7 @@ public void createScoped_clonesWithScopes() throws IOException { } @Test - public void createScoped_defaultScopes() throws IOException { + void createScoped_defaultScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); @@ -152,7 +148,7 @@ public void createScoped_defaultScopes() throws IOException { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { GoogleCredentials credentials = new TestAppEngineCredentials(SCOPES); GoogleCredentials otherCredentials = new TestAppEngineCredentials(SCOPES); assertTrue(credentials.equals(credentials)); @@ -161,7 +157,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() throws IOException { final Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(emptyScopes); @@ -171,7 +167,7 @@ public void equals_false_scopes() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { String expectedToString = String.format( "TestAppEngineCredentials{scopes=[%s], scopesRequired=%b}", "SomeScope", false); @@ -181,13 +177,13 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { AppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(credentials.hashCode(), credentials.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(scopes); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java index 213052c4e..16fcb61f9 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonParser; @@ -50,13 +50,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link AwsCredentials}. */ -@RunWith(JUnit4.class) -public class AwsCredentialsTest { +class AwsCredentialsTest { private static final String STS_URL = "https://sts.googleapis.com"; @@ -91,7 +88,7 @@ public class AwsCredentialsTest { .build(); @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -109,7 +106,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc } @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -132,7 +129,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept } @Test - public void retrieveSubjectToken() throws IOException { + void retrieveSubjectToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -164,7 +161,7 @@ public void retrieveSubjectToken() throws IOException { } @Test - public void retrieveSubjectToken_noRegion_expectThrows() { + void retrieveSubjectToken_noRegion_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -178,16 +175,14 @@ public void retrieveSubjectToken_noRegion_expectThrows() { .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); - try { - awsCredential.retrieveSubjectToken(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals("Failed to retrieve AWS region.", e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); + assertEquals("Failed to retrieve AWS region.", exception.getMessage()); } @Test - public void retrieveSubjectToken_noRole_expectThrows() { + void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -202,16 +197,14 @@ public void retrieveSubjectToken_noRole_expectThrows() { .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); - try { - awsCredential.retrieveSubjectToken(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals("Failed to retrieve AWS IAM role.", e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); + assertEquals("Failed to retrieve AWS IAM role.", exception.getMessage()); } @Test - public void retrieveSubjectToken_noCredentials_expectThrows() { + void retrieveSubjectToken_noCredentials_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -226,16 +219,14 @@ public void retrieveSubjectToken_noCredentials_expectThrows() { .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); - try { - awsCredential.retrieveSubjectToken(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals("Failed to retrieve AWS credentials.", e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); + assertEquals("Failed to retrieve AWS credentials.", exception.getMessage()); } @Test - public void retrieveSubjectToken_noRegionUrlProvided() { + void retrieveSubjectToken_noRegionUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -250,19 +241,17 @@ public void retrieveSubjectToken_noRegionUrlProvided() { .setCredentialSource(new AwsCredentialSource(credentialSource)) .build(); - try { - awsCredential.retrieveSubjectToken(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals( - "Unable to determine the AWS region. The credential source does not " - + "contain the region URL.", - e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); + assertEquals( + "Unable to determine the AWS region. The credential source does not " + + "contain the region URL.", + exception.getMessage()); } @Test - public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { + void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -282,7 +271,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws I } @Test - public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { + void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -303,7 +292,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws } @Test - public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { + void getAwsSecurityCredentials_fromMetadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -322,7 +311,7 @@ public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { } @Test - public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { + void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -337,18 +326,18 @@ public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { .setCredentialSource(new AwsCredentialSource(credentialSource)) .build(); - try { - awsCredential.getAwsSecurityCredentials(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals( - "Unable to determine the AWS IAM role name. The credential source does not contain the url field.", - e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, + awsCredential::getAwsSecurityCredentials, + "Exception should be thrown."); + assertEquals( + "Unable to determine the AWS IAM role name. The credential source does not contain the url field.", + exception.getMessage()); } @Test - public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { + void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_REGION", "region"); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -371,7 +360,7 @@ public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { } @Test - public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { + void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -393,7 +382,7 @@ public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOExceptio } @Test - public void getAwsRegion_metadataServer() throws IOException { + void getAwsRegion_metadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredentials = @@ -415,7 +404,7 @@ public void getAwsRegion_metadataServer() throws IOException { } @Test - public void createdScoped_clonedCredentialWithAddedScopes() { + void createdScoped_clonedCredentialWithAddedScopes() { AwsCredentials credentials = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) @@ -444,47 +433,46 @@ public void createdScoped_clonedCredentialWithAddedScopes() { } @Test - public void credentialSource_invalidAwsEnvironmentId() { + void credentialSource_invalidAwsEnvironmentId() { Map credentialSource = new HashMap<>(); credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "azure1"); - try { - new AwsCredentialSource(credentialSource); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals("Invalid AWS environment ID.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new AwsCredentialSource(credentialSource), + "Exception should be thrown."); + assertEquals("Invalid AWS environment ID.", exception.getMessage()); } @Test - public void credentialSource_invalidAwsEnvironmentVersion() { + void credentialSource_invalidAwsEnvironmentVersion() { Map credentialSource = new HashMap<>(); int environmentVersion = 2; credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "aws" + environmentVersion); - try { - new AwsCredentialSource(credentialSource); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - String.format( - "AWS version %s is not supported in the current build.", environmentVersion), - e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new AwsCredentialSource(credentialSource), + "Exception should be thrown."); + assertEquals( + String.format("AWS version %s is not supported in the current build.", environmentVersion), + exception.getMessage()); } @Test - public void credentialSource_missingRegionalCredVerificationUrl() { - try { - new AwsCredentialSource(new HashMap()); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "A regional_cred_verification_url representing the GetCallerIdentity action URL must be specified.", - e.getMessage()); - } + void credentialSource_missingRegionalCredVerificationUrl() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new AwsCredentialSource(new HashMap<>()), + "Exception should be thrown."); + assertEquals( + "A regional_cred_verification_url representing the GetCallerIdentity action URL must be specified.", + exception.getMessage()); } @Test diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java index ebb14091e..f7bdfb084 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java @@ -31,7 +31,7 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -42,8 +42,8 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link AwsRequestSigner}. @@ -51,7 +51,7 @@ *

Examples of sigv4 signed requests: * https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html */ -public class AwsRequestSignerTest { +class AwsRequestSignerTest { private static final String DATE = "Mon, 09 Sep 2011 23:36:00 GMT"; private static final String X_AMZ_DATE = "20200811T065522Z"; @@ -62,15 +62,15 @@ public class AwsRequestSignerTest { private AwsSecurityCredentials awsSecurityCredentials; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { awsSecurityCredentials = retrieveAwsSecurityCredentials(); } // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.sreq @Test - public void sign_getHost() { + void sign_getHost() { String url = "https://host.foo.com"; Map headers = new HashMap<>(); @@ -101,7 +101,7 @@ public void sign_getHost() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.sreq @Test - public void sign_getHostRelativePath() { + void sign_getHostRelativePath() { String url = "https://host.foo.com/foo/bar/../.."; Map headers = new HashMap<>(); @@ -132,7 +132,7 @@ public void sign_getHostRelativePath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.sreq @Test - public void sign_getHostInvalidPath() { + void sign_getHostInvalidPath() { String url = "https://host.foo.com/./"; Map headers = new HashMap<>(); @@ -163,7 +163,7 @@ public void sign_getHostInvalidPath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.sreq @Test - public void sign_getHostDotPath() { + void sign_getHostDotPath() { String url = "https://host.foo.com/./foo"; Map headers = new HashMap<>(); @@ -194,7 +194,7 @@ public void sign_getHostDotPath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.sreq @Test - public void sign_getHostUtf8Path() { + void sign_getHostUtf8Path() { String url = "https://host.foo.com/%E1%88%B4"; Map headers = new HashMap<>(); @@ -225,7 +225,7 @@ public void sign_getHostUtf8Path() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.sreq @Test - public void sign_getHostDuplicateQueryParam() { + void sign_getHostDuplicateQueryParam() { String url = "https://host.foo.com/?foo=Zoo&foo=aha"; Map headers = new HashMap<>(); @@ -256,7 +256,7 @@ public void sign_getHostDuplicateQueryParam() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.sreq @Test - public void sign_postWithUpperCaseHeaderKey() { + void sign_postWithUpperCaseHeaderKey() { String url = "https://host.foo.com/"; String headerKey = "ZOO"; String headerValue = "zoobar"; @@ -291,7 +291,7 @@ public void sign_postWithUpperCaseHeaderKey() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.sreq @Test - public void sign_postWithUpperCaseHeaderValue() { + void sign_postWithUpperCaseHeaderValue() { String url = "https://host.foo.com/"; String headerKey = "zoo"; String headerValue = "ZOOBAR"; @@ -326,7 +326,7 @@ public void sign_postWithUpperCaseHeaderValue() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.sreq @Test - public void sign_postWithHeader() { + void sign_postWithHeader() { String url = "https://host.foo.com/"; String headerKey = "p"; String headerValue = "phfft"; @@ -361,7 +361,7 @@ public void sign_postWithHeader() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.sreq @Test - public void sign_postWithBodyNoCustomHeaders() { + void sign_postWithBodyNoCustomHeaders() { String url = "https://host.foo.com/"; String headerKey = "Content-Type"; String headerValue = "application/x-www-form-urlencoded"; @@ -397,7 +397,7 @@ public void sign_postWithBodyNoCustomHeaders() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.sreq @Test - public void sign_postWithQueryString() { + void sign_postWithQueryString() { String url = "https://host.foo.com/?foo=bar"; Map headers = new HashMap<>(); @@ -426,7 +426,7 @@ public void sign_postWithQueryString() { } @Test - public void sign_getDescribeRegions() { + void sign_getDescribeRegions() { String url = "https://ec2.us-east-2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15"; Map additionalHeaders = new HashMap<>(); @@ -457,7 +457,7 @@ public void sign_getDescribeRegions() { } @Test - public void sign_postGetCallerIdentity() { + void sign_postGetCallerIdentity() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; Map additionalHeaders = new HashMap<>(); @@ -488,7 +488,7 @@ public void sign_postGetCallerIdentity() { } @Test - public void sign_postGetCallerIdentityNoToken() { + void sign_postGetCallerIdentityNoToken() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; AwsSecurityCredentials awsSecurityCredentialsWithoutToken = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java index d7a5ca015..1409507ea 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java @@ -31,25 +31,23 @@ package com.google.auth.oauth2; -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.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for ClientId */ -@RunWith(JUnit4.class) -public class ClientIdTest { +class ClientIdTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @Test - public void constructor() { + void constructor() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); @@ -57,20 +55,22 @@ public void constructor() { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test(expected = NullPointerException.class) - public void constructor_nullClientId_throws() { - ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build(); + @Test + void constructor_nullClientId_throws() { + assertThrows( + NullPointerException.class, + () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); } @Test - public void constructor_nullClientSecret() { + void constructor_nullClientSecret() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).build(); assertEquals(CLIENT_ID, clientId.getClientId()); assertNull(clientId.getClientSecret()); } @Test - public void fromJson_web() throws IOException { + void fromJson_web() throws IOException { GenericJson json = writeClientIdJson("web", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -80,7 +80,7 @@ public void fromJson_web() throws IOException { } @Test - public void fromJson_installed() throws IOException { + void fromJson_installed() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -90,7 +90,7 @@ public void fromJson_installed() throws IOException { } @Test - public void fromJson_installedNoSecret() throws IOException { + void fromJson_installedNoSecret() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, null); ClientId clientId = ClientId.fromJson(json); @@ -99,42 +99,44 @@ public void fromJson_installedNoSecret() throws IOException { assertNull(clientId.getClientSecret()); } - @Test(expected = IOException.class) - public void fromJson_invalidType_throws() throws IOException { + @Test + void fromJson_invalidType_throws() { GenericJson json = writeClientIdJson("invalid", CLIENT_ID, null); - ClientId.fromJson(json); + assertThrows(IOException.class, () -> ClientId.fromJson(json)); } - @Test(expected = IOException.class) - public void fromJson_noClientId_throws() throws IOException { + @Test + void fromJson_noClientId_throws() { GenericJson json = writeClientIdJson("web", null, null); - ClientId.fromJson(json); + assertThrows(IOException.class, () -> ClientId.fromJson(json)); } - @Test(expected = IOException.class) - public void fromJson_zeroLengthClientId_throws() throws IOException { + @Test + void fromJson_zeroLengthClientId_throws() { GenericJson json = writeClientIdJson("web", "", null); - ClientId.fromJson(json); + assertThrows(IOException.class, () -> ClientId.fromJson(json)); } @Test - public void fromResource() throws IOException { + void fromResource() throws IOException { ClientId clientId = ClientId.fromResource(ClientIdTest.class, "/client_secret.json"); assertEquals(CLIENT_ID, clientId.getClientId()); assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test(expected = NullPointerException.class) - public void fromResource_badResource() throws IOException { - ClientId.fromResource(ClientIdTest.class, "invalid.json"); + @Test + void fromResource_badResource() { + assertThrows( + NullPointerException.class, + () -> ClientId.fromResource(ClientIdTest.class, "invalid.json")); } @Test - public void fromStream() throws IOException { + void fromStream() throws IOException { String text = "{" + "\"web\": {" @@ -155,7 +157,7 @@ public void fromStream() throws IOException { } @Test - public void fromStream_invalidJson_doesNotThrow() throws IOException { + void fromStream_invalidJson_doesNotThrow() throws IOException { String invalidJson = "{" + "\"web\": {" diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java index 2dc075f17..110214508 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java @@ -31,10 +31,10 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.util.Clock; import java.io.BufferedReader; @@ -43,18 +43,14 @@ import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for CloudShellCredentials */ -@RunWith(JUnit4.class) -public class CloudShellCredentialsTest extends BaseSerializationTest { +class CloudShellCredentialsTest extends BaseSerializationTest { @Test - public void refreshAccessToken() throws IOException { - final ServerSocket authSocket = new ServerSocket(0); - try { + void refreshAccessToken() throws IOException { + try (ServerSocket authSocket = new ServerSocket(0)) { Runnable serverTask = new Runnable() { @Override @@ -80,13 +76,11 @@ public void run() { GoogleCredentials creds = CloudShellCredentials.newBuilder().setAuthPort(authSocket.getLocalPort()).build(); assertEquals("token", creds.refreshAccessToken().getTokenValue()); - } finally { - authSocket.close(); } } @Test - public void equals_true() throws IOException { + void equals_true() { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertTrue(credentials.equals(otherCredentials)); @@ -94,7 +88,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_authPort() throws IOException { + void equals_false_authPort() { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(43).build(); assertFalse(credentials.equals(otherCredentials)); @@ -102,21 +96,21 @@ public void equals_false_authPort() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() { String expectedToString = String.format("CloudShellCredentials{authPort=%d}", 42); GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(expectedToString, credentials.toString()); } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); assertEquals(credentials, deserializedCredentials); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java index 41ff946b0..26b57113b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -31,14 +31,14 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +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 com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -60,13 +60,10 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link ComputeEngineCredentials}. */ -@RunWith(JUnit4.class) -public class ComputeEngineCredentialsTest extends BaseSerializationTest { +class ComputeEngineCredentialsTest extends BaseSerializationTest { private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); @@ -119,7 +116,7 @@ public HttpTransport create() { } @Test - public void createTokenUrlWithScopes_null_scopes() { + void createTokenUrlWithScopes_null_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); Collection scopes = credentials.getScopes(); @@ -130,9 +127,9 @@ public void createTokenUrlWithScopes_null_scopes() { } @Test - public void createTokenUrlWithScopes_empty_scopes() { + void createTokenUrlWithScopes_empty_scopes() { ComputeEngineCredentials.Builder builder = - ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); + ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); ComputeEngineCredentials credentials = builder.build(); Collection scopes = credentials.getScopes(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -143,7 +140,7 @@ public void createTokenUrlWithScopes_empty_scopes() { } @Test - public void createTokenUrlWithScopes_single_scope() { + void createTokenUrlWithScopes_single_scope() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(Arrays.asList("foo")).build(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -155,7 +152,7 @@ public void createTokenUrlWithScopes_single_scope() { } @Test - public void createTokenUrlWithScopes_multiple_scopes() { + void createTokenUrlWithScopes_multiple_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(Arrays.asList(null, "foo", "", "bar")) @@ -170,7 +167,7 @@ public void createTokenUrlWithScopes_multiple_scopes() { } @Test - public void createTokenUrlWithScopes_defaultScopes() { + void createTokenUrlWithScopes_defaultScopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().build(); credentials = (ComputeEngineCredentials) @@ -185,7 +182,7 @@ public void createTokenUrlWithScopes_defaultScopes() { } @Test - public void createScoped() { + void createScoped() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials credentialsWithScopes = @@ -197,7 +194,7 @@ public void createScoped() { } @Test - public void createScoped_defaultScopes() { + void createScoped_defaultScopes() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); Collection scopes = ((ComputeEngineCredentials) credentials).getScopes(); @@ -207,7 +204,7 @@ public void createScoped_defaultScopes() { } @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + void getRequestMetadata_hasAccessToken() throws IOException { String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(accessToken); @@ -219,44 +216,45 @@ public void getRequestMetadata_hasAccessToken() throws IOException { } @Test - public void getRequestMetadata_missingServiceAccount_throws() { + void getRequestMetadata_missingServiceAccount_throws() { String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(accessToken); transportFactory.transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - credentials.getRequestMetadata(CALL_URI); - fail("Expected error refreshing token."); - } catch (IOException expected) { - String message = expected.getMessage(); - assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND))); - // Message should mention scopes are missing on the VM. - assertTrue(message.contains("scope")); - } + + IOException exception = + assertThrows( + IOException.class, + () -> credentials.getRequestMetadata(CALL_URI), + "Expected error refreshing token."); + String message = exception.getMessage(); + assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND))); + assertTrue(message.contains("scope"), "Message should mention scopes are missing on the VM."); } @Test - public void getRequestMetadata_serverError_throws() { + void getRequestMetadata_serverError_throws() { String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(accessToken); transportFactory.transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - credentials.getRequestMetadata(CALL_URI); - fail("Expected error refreshing token."); - } catch (IOException expected) { - String message = expected.getMessage(); - assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR))); - assertTrue(message.contains("Unexpected")); - } + + IOException exception = + assertThrows( + IOException.class, + () -> credentials.getRequestMetadata(CALL_URI), + "Expected error refreshing token."); + String message = exception.getMessage(); + assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR))); + assertTrue(message.contains("Unexpected")); } @Test - public void equals_true() throws IOException { + void equals_true() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -267,7 +265,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_transportFactory() throws IOException { + void equals_false_transportFactory() { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); @@ -282,7 +280,7 @@ public void equals_false_transportFactory() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); String expectedToString = @@ -297,7 +295,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -312,7 +310,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -333,7 +331,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -345,7 +343,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void getAccount_missing_throws() { + void getAccount_missing_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -370,18 +368,18 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - credentials.getAccount(); - fail("Fetching default service account should have failed"); - } catch (RuntimeException e) { - assertEquals("Failed to get service account", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("404")); - } + RuntimeException exception = + assertThrows( + RuntimeException.class, + credentials::getAccount, + "Fetching default service account should have failed"); + assertEquals("Failed to get service account", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("404")); } @Test - public void getAccount_emptyContent_throws() { + void getAccount_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -405,18 +403,18 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - credentials.getAccount(); - fail("Fetching default service account should have failed"); - } catch (RuntimeException e) { - assertEquals("Failed to get service account", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("Empty content")); - } + RuntimeException exception = + assertThrows( + RuntimeException.class, + credentials::getAccount, + "Fetching default service account should have failed"); + assertEquals("Failed to get service account", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("Empty content")); } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -432,7 +430,7 @@ public void sign_sameAs() throws IOException { } @Test - public void sign_getAccountFails() throws IOException { + void sign_getAccountFails() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -442,17 +440,14 @@ public void sign_getAccountFails() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - credentials.sign(expectedSignature); - fail(); - } catch (SigningException ex) { - assertNotNull(ex.getMessage()); - assertNotNull(ex.getCause()); - } + SigningException exception = + assertThrows(SigningException.class, () -> credentials.sign(expectedSignature)); + assertNotNull(exception.getMessage()); + assertNotNull(exception.getCause()); } @Test - public void sign_accessDenied_throws() { + void sign_accessDenied_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -481,19 +476,17 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - credentials.sign(bytes); - fail("Signing should have failed"); - } catch (SigningException e) { - assertEquals("Failed to sign the provided bytes", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("403")); - } + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + SigningException exception = + assertThrows( + SigningException.class, () -> credentials.sign(bytes), "Signing should have failed"); + assertEquals("Failed to sign the provided bytes", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("403")); } @Test - public void sign_serverError_throws() { + void sign_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -522,19 +515,17 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - credentials.sign(bytes); - fail("Signing should have failed"); - } catch (SigningException e) { - assertEquals("Failed to sign the provided bytes", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("500")); - } + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + SigningException exception = + assertThrows( + SigningException.class, () -> credentials.sign(bytes), "Signing should have failed"); + assertEquals("Failed to sign the provided bytes", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("500")); } @Test - public void sign_emptyContent_throws() { + void sign_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -562,19 +553,17 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - try { - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - credentials.sign(bytes); - fail("Signing should have failed"); - } catch (SigningException e) { - assertEquals("Failed to sign the provided bytes", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("Empty content")); - } + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + SigningException exception = + assertThrows( + SigningException.class, () -> credentials.sign(bytes), "Signing should have failed"); + assertEquals("Failed to sign the provided bytes", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("Empty content")); } @Test - public void idTokenWithAudience_sameAs() throws IOException { + void idTokenWithAudience_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(STANDARD_ID_TOKEN); ComputeEngineCredentials credentials = @@ -595,7 +584,7 @@ public void idTokenWithAudience_sameAs() throws IOException { } @Test - public void idTokenWithAudience_standard() throws IOException { + void idTokenWithAudience_standard() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -614,7 +603,7 @@ public void idTokenWithAudience_standard() throws IOException { @Test @SuppressWarnings("unchecked") - public void idTokenWithAudience_full() throws IOException { + void idTokenWithAudience_full() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -628,16 +617,14 @@ public void idTokenWithAudience_full() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - if (!p.containsKey("google")) { - assertFalse("Full ID Token format not provided", false); - } + assertTrue(p.containsKey("google"), "Full ID Token format not provided"); ArrayMap googleClaim = (ArrayMap) p.get("google"); - assert (googleClaim.containsKey("compute_engine")); + assertTrue(googleClaim.containsKey("compute_engine")); } @Test @SuppressWarnings("unchecked") - public void idTokenWithAudience_license() throws IOException { + void idTokenWithAudience_license() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -653,10 +640,8 @@ public void idTokenWithAudience_license() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - if (!p.containsKey("google")) { - assertFalse("Full ID Token format not provided", false); - } + assertTrue(p.containsKey("google"), "Full ID Token format not provided"); ArrayMap googleClaim = (ArrayMap) p.get("google"); - assert (googleClaim.containsKey("license")); + assertTrue(googleClaim.containsKey("license")); } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java index ac042e065..a43f8ac7a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java @@ -31,25 +31,22 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.auth.oauth2.CredentialAccessBoundary.AccessBoundaryRule; import com.google.auth.oauth2.CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link CredentialAccessBoundary} and encompassing classes. */ -@RunWith(JUnit4.class) -public class CredentialAccessBoundaryTest { +class CredentialAccessBoundaryTest { @Test - public void credentialAccessBoundary() { + void credentialAccessBoundary() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -92,27 +89,25 @@ public void credentialAccessBoundary() { } @Test - public void credentialAccessBoundary_nullRules_throws() { - try { - CredentialAccessBoundary.newBuilder().build(); - fail("Should fail."); - } catch (NullPointerException e) { - // Expected. - } + void credentialAccessBoundary_nullRules_throws() { + assertThrows( + NullPointerException.class, + () -> CredentialAccessBoundary.newBuilder().build(), + "Should fail."); } @Test - public void credentialAccessBoundary_withoutRules_throws() { - try { - CredentialAccessBoundary.newBuilder().setRules(new ArrayList()).build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("At least one access boundary rule must be provided.", e.getMessage()); - } + void credentialAccessBoundary_withoutRules_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> CredentialAccessBoundary.newBuilder().setRules(new ArrayList<>()).build(), + "Should fail."); + assertEquals("At least one access boundary rule must be provided.", exception.getMessage()); } @Test - public void credentialAccessBoundary_ruleCountExceeded_throws() { + void credentialAccessBoundary_ruleCountExceeded_throws() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -124,16 +119,14 @@ public void credentialAccessBoundary_ruleCountExceeded_throws() { builder.addRule(rule); } - try { - builder.build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("The provided list has more than 10 access boundary rules.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, builder::build, "Should fail."); + assertEquals( + "The provided list has more than 10 access boundary rules.", exception.getMessage()); } @Test - public void credentialAccessBoundary_toJson() { + void credentialAccessBoundary_toJson() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -172,7 +165,7 @@ public void credentialAccessBoundary_toJson() { } @Test - public void accessBoundaryRule_allFields() { + void accessBoundaryRule_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -192,7 +185,7 @@ public void accessBoundaryRule_allFields() { } @Test - public void accessBoundaryRule_requiredFields() { + void accessBoundaryRule_requiredFields() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -206,79 +199,83 @@ public void accessBoundaryRule_requiredFields() { } @Test - public void accessBoundaryRule_withEmptyAvailableResource_throws() { - try { - AccessBoundaryRule.newBuilder() - .setAvailableResource("") - .addAvailablePermission("permission") - .build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("The provided availableResource is empty.", e.getMessage()); - } + void accessBoundaryRule_withEmptyAvailableResource_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + AccessBoundaryRule.newBuilder() + .setAvailableResource("") + .addAvailablePermission("permission") + .build(); + }, + "Should fail."); + assertEquals("The provided availableResource is empty.", exception.getMessage()); } @Test - public void accessBoundaryRule_withoutAvailableResource_throws() { - try { - AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(); - fail("Should fail."); - } catch (NullPointerException e) { - // Expected. - } + void accessBoundaryRule_withoutAvailableResource_throws() { + assertThrows( + NullPointerException.class, + () -> AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(), + "Should fail."); } @Test - public void accessBoundaryRule_withoutAvailablePermissions_throws() { - try { - AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(); - fail("Should fail."); - } catch (NullPointerException e) { - // Expected. - } + void accessBoundaryRule_withoutAvailablePermissions_throws() { + assertThrows( + NullPointerException.class, + () -> AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(), + "Should fail."); } @Test - public void accessBoundaryRule_withEmptyAvailablePermissions_throws() { - try { - AccessBoundaryRule.newBuilder() - .setAvailableResource("resource") - .setAvailablePermissions(new ArrayList()) - .build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("The list of provided availablePermissions is empty.", e.getMessage()); - } + void accessBoundaryRule_withEmptyAvailablePermissions_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + AccessBoundaryRule.newBuilder() + .setAvailableResource("resource") + .setAvailablePermissions(new ArrayList()) + .build(); + }, + "Should fail."); + assertEquals("The list of provided availablePermissions is empty.", exception.getMessage()); } @Test - public void accessBoundaryRule_withNullAvailablePermissions_throws() { - try { - AccessBoundaryRule.newBuilder() - .setAvailableResource("resource") - .addAvailablePermission(null) - .build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("One of the provided available permissions is null.", e.getMessage()); - } + void accessBoundaryRule_withNullAvailablePermissions_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + AccessBoundaryRule.newBuilder() + .setAvailableResource("resource") + .addAvailablePermission(null) + .build(); + }, + "Should fail."); + assertEquals("One of the provided available permissions is null.", exception.getMessage()); } @Test - public void accessBoundaryRule_withEmptyAvailablePermission_throws() { - try { - AccessBoundaryRule.newBuilder() - .setAvailableResource("resource") - .addAvailablePermission("") - .build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("One of the provided available permissions is empty.", e.getMessage()); - } + void accessBoundaryRule_withEmptyAvailablePermission_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + AccessBoundaryRule.newBuilder() + .setAvailableResource("resource") + .addAvailablePermission("") + .build(); + }, + "Should fail."); + assertEquals("One of the provided available permissions is empty.", exception.getMessage()); } @Test - public void availabilityCondition_allFields() { + void availabilityCondition_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -292,7 +289,7 @@ public void availabilityCondition_allFields() { } @Test - public void availabilityCondition_expressionOnly() { + void availabilityCondition_expressionOnly() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -302,22 +299,20 @@ public void availabilityCondition_expressionOnly() { } @Test - public void availabilityCondition_nullExpression_throws() { - try { - AvailabilityCondition.newBuilder().setExpression(null).build(); - fail("Should fail."); - } catch (NullPointerException e) { - // Expected. - } + void availabilityCondition_nullExpression_throws() { + assertThrows( + NullPointerException.class, + () -> AvailabilityCondition.newBuilder().setExpression(null).build(), + "Should fail."); } @Test - public void availabilityCondition_emptyExpression_throws() { - try { - AvailabilityCondition.newBuilder().setExpression("").build(); - fail("Should fail."); - } catch (IllegalArgumentException e) { - assertEquals("The provided expression is empty.", e.getMessage()); - } + void availabilityCondition_emptyExpression_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> AvailabilityCondition.newBuilder().setExpression("").build(), + "Should fail."); + assertEquals("The provided expression is empty.", exception.getMessage()); } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java index e70db86a2..afe7eac7d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -49,11 +49,10 @@ import com.google.auth.oauth2.IdToken; import com.google.auth.oauth2.IdTokenCredentials; import com.google.auth.oauth2.IdTokenProvider; -import java.io.FileNotFoundException; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public final class FTServiceAccountCredentialsTest { +class FTServiceAccountCredentialsTest { private final String cloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"; private final String cloudTasksUrl = @@ -66,19 +65,19 @@ public final class FTServiceAccountCredentialsTest { "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; @Test - public void NoScopeNoAudienceComputeTest() throws Exception { + void NoScopeNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(computeUrl); assertEquals(200, response.getStatusCode()); } @Test - public void NoScopeNoAudienceBigQueryTest() throws Exception { + void NoScopeNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(bigQueryUrl); assertEquals(200, response.getStatusCode()); } @Test - public void NoScopeNoAudienceOnePlatformTest() throws Exception { + void NoScopeNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(cloudTasksUrl); assertEquals(200, response.getStatusCode()); } @@ -86,7 +85,7 @@ public void NoScopeNoAudienceOnePlatformTest() throws Exception { // TODO: add Storage case @Test - public void AudienceSetNoScopeTest() throws Exception { + void AudienceSetNoScopeTest() throws Exception { final GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); IdTokenCredentials tokenCredential = @@ -107,62 +106,62 @@ public void AudienceSetNoScopeTest() throws Exception { } @Test - public void ScopeSetNoAudienceStorageTest() throws Exception { + void ScopeSetNoAudienceStorageTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(storageUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - public void ScopeSetNoAudienceComputeTest() throws Exception { + void ScopeSetNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(computeUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - public void ScopeSetNoAudienceBigQueryTest() throws Exception { + void ScopeSetNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(bigQueryUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - public void ScopeSetNoAudienceOnePlatformTest() throws Exception { + void ScopeSetNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(cloudTasksUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - public void WrongScopeComputeTest() throws Exception { + void WrongScopeComputeTest() throws Exception { executeRequestWrongScope(computeUrl); } @Test - public void WrongScopeStorageTest() throws Exception { + void WrongScopeStorageTest() throws Exception { executeRequestWrongScope(storageUrl); } @Test - public void WrongScopeBigQueryTest() throws Exception { + void WrongScopeBigQueryTest() throws Exception { executeRequestWrongScope(bigQueryUrl); } @Test - public void WrongScopeOnePlatformTest() throws Exception { + void WrongScopeOnePlatformTest() throws Exception { executeRequestWrongScope(cloudTasksUrl); } - private void executeRequestWrongScope(String serviceUri) - throws FileNotFoundException, IOException { + private void executeRequestWrongScope(String serviceUri) { String expectedMessage = "403 Forbidden"; - try { - executeRequestWithCredentialsWithScope( - serviceUri, "https://www.googleapis.com/auth/adexchange.buyer"); - fail("Should throw exception: " + expectedMessage); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains(expectedMessage)); - } + IOException exception = + assertThrows( + IOException.class, + () -> + executeRequestWithCredentialsWithScope( + serviceUri, "https://www.googleapis.com/auth/adexchange.buyer"), + "Should throw exception: " + expectedMessage); + assertTrue(exception.getMessage().contains(expectedMessage)); } private HttpResponse executeRequestWithCredentialsWithoutScope(String serviceUrl) diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index 6852cce09..0e59a9890 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -81,7 +81,6 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M5 @@ -90,13 +89,6 @@ sponge_log - - - org.apache.maven.surefire - surefire-junit47 - 3.0.0-M5 - - org.apache.maven.plugins @@ -143,6 +135,11 @@ junit test + + org.junit.jupiter + junit-jupiter-api + test + org.hamcrest hamcrest-core From d045247162683ca8c3c562dd2300a625b27f824e Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Mon, 11 Oct 2021 17:53:45 +0300 Subject: [PATCH 7/9] chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - second iteration (#756) (#763) --- .../DefaultCredentialsProviderTest.java | 186 +++++------ .../oauth2/DownscopedCredentialsTest.java | 73 ++--- .../ExternalAccountCredentialsTest.java | 306 +++++++++--------- .../auth/oauth2/GoogleCredentialsTest.java | 91 +++--- 4 files changed, 316 insertions(+), 340 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java index 8db555318..c8f787d20 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.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.assertFalse; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; @@ -65,13 +65,10 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link DefaultCredentialsProvider}. */ -@RunWith(JUnit4.class) -public class DefaultCredentialsProviderTest { +class DefaultCredentialsProviderTest { private static final String USER_CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String USER_CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -101,36 +98,36 @@ public HttpTransport create() { } @Test - public void getDefaultCredentials_noCredentials_throws() throws Exception { + void getDefaultCredentials_noCredentials_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected."); - } catch (IOException e) { - String message = e.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); - } + IOException exception = + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected."); + String message = exception.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); } @Test - public void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() throws Exception { + void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setFileSandbox(true); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected."); - } catch (IOException e) { - String message = e.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); - } + IOException exception = + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected."); + String message = exception.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); } @Test - public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { + void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -141,43 +138,39 @@ public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exc testProvider.addFile(userPath, userStream); testProvider.setEnv(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR, userPath); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected."); - } catch (IOException e) { - String message = e.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); - } + IOException exception = + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected."); + String message = exception.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); } @Test - public void getDefaultCredentials_noCredentials_singleGceTestRequest() { + void getDefaultCredentials_noCredentials_singleGceTestRequest() { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected."); - } catch (IOException expected) { - // Expected - } + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected."); assertEquals( transportFactory.transport.getRequestCount(), ComputeEngineCredentials.MAX_COMPUTE_PING_TRIES); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected."); - } catch (IOException expected) { - // Expected - } + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected."); assertEquals( transportFactory.transport.getRequestCount(), ComputeEngineCredentials.MAX_COMPUTE_PING_TRIES); } @Test - public void getDefaultCredentials_caches() throws IOException { + void getDefaultCredentials_caches() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -189,43 +182,42 @@ public void getDefaultCredentials_caches() throws IOException { } @Test - public void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { + void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( DefaultCredentialsProvider.APP_ENGINE_SIGNAL_CLASS, MockOffAppEngineSystemProperty.class); testProvider.setProperty("isOnGAEStandard7", "true"); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected when not on App Engine."); - } catch (IOException e) { - String message = e.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); - } + IOException exception = + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected when not on App Engine."); + String message = exception.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); } @Test - public void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { + void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( DefaultCredentialsProvider.APP_ENGINE_SIGNAL_CLASS, MockAppEngineSystemProperty.class); testProvider.setProperty("isOnGAEStandard7", "true"); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("Credential expected to fail to load if credential class not present."); - } catch (IOException e) { - String message = e.getMessage(); - assertFalse(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); - assertTrue(message.contains("Check that the App Engine SDK is deployed.")); - } + IOException exception = + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "Credential expected to fail to load if credential class not present."); + String message = exception.getMessage(); + assertFalse(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + assertTrue(message.contains("Check that the App Engine SDK is deployed.")); } @Test - public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() - throws IOException { + void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -239,7 +231,7 @@ public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredenti } @Test - public void getDefaultCredentials_compute_providesToken() throws IOException { + void getDefaultCredentials_compute_providesToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(ACCESS_TOKEN); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -252,7 +244,7 @@ public void getDefaultCredentials_compute_providesToken() throws IOException { } @Test - public void getDefaultCredentials_cloudshell() throws IOException { + void getDefaultCredentials_cloudshell() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -264,7 +256,7 @@ public void getDefaultCredentials_cloudshell() throws IOException { } @Test - public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { + void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(ACCESS_TOKEN); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -277,24 +269,24 @@ public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() thro } @Test - public void getDefaultCredentials_envMissingFile_throws() { + void getDefaultCredentials_envMissingFile_throws() { final String invalidPath = "/invalid/path"; MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR, invalidPath); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("Non existent credential should throw exception"); - } catch (IOException e) { - String message = e.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR)); - assertTrue(message.contains(invalidPath)); - } + IOException exception = + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "Non existent credential should throw exception"); + String message = exception.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR)); + assertTrue(message.contains(invalidPath)); } @Test - public void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { + void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -314,7 +306,7 @@ public void getDefaultCredentials_envServiceAccount_providesToken() throws IOExc } @Test - public void getDefaultCredentials_envUser_providesToken() throws IOException { + void getDefaultCredentials_envUser_providesToken() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -327,23 +319,21 @@ public void getDefaultCredentials_envUser_providesToken() throws IOException { } @Test - public void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { + void getDefaultCredentials_envNoGceCheck_noGceRequest() { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.NO_GCE_CHECK_ENV_VAR, "true"); - try { - testProvider.getDefaultCredentials(transportFactory); - fail("No credential expected."); - } catch (IOException expected) { - // Expected - } + assertThrows( + IOException.class, + () -> testProvider.getDefaultCredentials(transportFactory), + "No credential expected."); assertEquals(transportFactory.transport.getRequestCount(), 0); } @Test - public void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { + void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -351,7 +341,7 @@ public void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { } @Test - public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { + void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -361,7 +351,7 @@ public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { } @Test - public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { + void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -376,7 +366,7 @@ public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOExce } @Test - public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { + void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File configDir = new File(homeDir, ".config"); File cloudConfigDir = new File(configDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); @@ -394,7 +384,7 @@ public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws } @Test - public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { + void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File cloudConfigDir = new File(homeDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); InputStream userStream = @@ -411,7 +401,7 @@ public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IO } @Test - public void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { + void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { final String refreshTokenEnv = "2/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; final String accessTokenEnv = "2/MkSJoj1xsli0AccessToken_NKPY2"; final String refreshTokenWkf = "3/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @@ -466,7 +456,7 @@ public void flush() {} } @Test - public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { + void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false); assertNotNull(message); assertEquals(Level.WARNING, message.getLevel()); @@ -474,7 +464,7 @@ public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOExc } @Test - public void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { + void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(true); assertNull(message); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index 77f34eac6..f77c0bb19 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.assertThrows; import com.google.api.client.http.HttpTransport; import com.google.auth.TestUtils; @@ -41,13 +41,10 @@ import java.io.IOException; import java.util.Date; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link DownscopedCredentials}. */ -@RunWith(JUnit4.class) -public class DownscopedCredentialsTest { +class DownscopedCredentialsTest { private static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n" @@ -83,7 +80,7 @@ public HttpTransport create() { } @Test - public void refreshAccessToken() throws IOException { + void refreshAccessToken() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -110,7 +107,7 @@ public void refreshAccessToken() throws IOException { } @Test - public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { + void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { // STS only returns expires_in if the source access token belongs to a service account. // For other source credential types, we can copy the source credentials expiration as // the generated downscoped token will always have the same expiration time as the source @@ -138,7 +135,7 @@ public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IO } @Test - public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { + void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -151,42 +148,42 @@ public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOEx .setHttpTransportFactory(transportFactory) .build(); - try { - downscopedCredentials.refreshAccessToken(); - fail("Should fail as the source credential should not be able to be refreshed."); - } catch (IOException e) { - assertEquals("Unable to refresh the provided source credential.", e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, + downscopedCredentials::refreshAccessToken, + "Should fail as the source credential should not be able to be refreshed."); + assertEquals("Unable to refresh the provided source credential.", exception.getMessage()); } @Test - public void builder_noSourceCredential_throws() { - try { - DownscopedCredentials.newBuilder() - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) - .build(); - fail("Should fail as the source credential is null."); - } catch (NullPointerException e) { - // Expected. - } + void builder_noSourceCredential_throws() { + assertThrows( + NullPointerException.class, + () -> { + DownscopedCredentials.newBuilder() + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .build(); + }, + "Should fail as the source credential is null."); } @Test - public void builder_noCredentialAccessBoundary_throws() throws IOException { - try { - DownscopedCredentials.newBuilder() - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setSourceCredential(getServiceAccountSourceCredentials(/* canRefresh= */ true)) - .build(); - fail("Should fail as no access boundary was provided."); - } catch (NullPointerException e) { - // Expected. - } + void builder_noCredentialAccessBoundary_throws() throws IOException { + assertThrows( + NullPointerException.class, + () -> { + DownscopedCredentials.newBuilder() + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setSourceCredential(getServiceAccountSourceCredentials(/* canRefresh= */ true)) + .build(); + }, + "Should fail as no access boundary was provided."); } @Test - public void builder_noTransport_defaults() throws IOException { + void builder_noTransport_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java index 1416ba964..0ba3efa52 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -53,13 +53,10 @@ import java.util.Locale; import java.util.Map; import javax.annotation.Nullable; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link ExternalAccountCredentials}. */ -@RunWith(JUnit4.class) public class ExternalAccountCredentialsTest { private static final String STS_URL = "https://sts.googleapis.com"; @@ -77,13 +74,13 @@ public HttpTransport create() { private MockExternalAccountCredentialsTransportFactory transportFactory; - @Before - public void setup() { + @BeforeEach + void setup() { transportFactory = new MockExternalAccountCredentialsTransportFactory(); } @Test - public void fromStream_identityPoolCredentials() throws IOException { + void fromStream_identityPoolCredentials() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); ExternalAccountCredentials credential = @@ -93,7 +90,7 @@ public void fromStream_identityPoolCredentials() throws IOException { } @Test - public void fromStream_awsCredentials() throws IOException { + void fromStream_awsCredentials() throws IOException { GenericJson json = buildJsonAwsCredential(); ExternalAccountCredentials credential = @@ -103,56 +100,57 @@ public void fromStream_awsCredentials() throws IOException { } @Test - public void fromStream_invalidStream_throws() throws IOException { + void fromStream_invalidStream_throws() { GenericJson json = buildJsonAwsCredential(); json.put("audience", new HashMap<>()); - try { - ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)); - fail("Should fail."); - } catch (CredentialFormatException e) { - assertEquals("An invalid input stream was provided.", e.getMessage()); - } + CredentialFormatException exception = + assertThrows( + CredentialFormatException.class, + () -> ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)), + "Should fail."); + assertEquals("An invalid input stream was provided.", exception.getMessage()); } @Test - public void fromStream_nullTransport_throws() throws IOException { - try { - ExternalAccountCredentials.fromStream( - new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); - fail("NullPointerException should be thrown."); - } catch (NullPointerException e) { - // Expected. - } + void fromStream_nullTransport_throws() { + assertThrows( + NullPointerException.class, + () -> { + ExternalAccountCredentials.fromStream( + new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); + }, + "NullPointerException should be thrown."); } @Test - public void fromStream_nullStream_throws() throws IOException { - try { - ExternalAccountCredentials.fromStream( - /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); - fail("NullPointerException should be thrown."); - } catch (NullPointerException e) { - // Expected. - } + void fromStream_nullStream_throws() { + assertThrows( + NullPointerException.class, + () -> { + ExternalAccountCredentials.fromStream( + /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); + }, + "NullPointerException should be thrown."); } @Test - public void fromStream_invalidWorkloadAudience_throws() throws IOException { - try { - GenericJson json = buildJsonIdentityPoolWorkforceCredential(); - json.put("audience", "invalidAudience"); - ExternalAccountCredentials credential = - ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)); - fail("CredentialFormatException should be thrown."); - } catch (CredentialFormatException e) { - assertEquals("An invalid input stream was provided.", e.getMessage()); - } + void fromStream_invalidWorkloadAudience_throws() throws IOException { + CredentialFormatException exception = + assertThrows( + CredentialFormatException.class, + () -> { + GenericJson json = buildJsonIdentityPoolWorkforceCredential(); + json.put("audience", "invalidAudience"); + ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)); + }, + "CredentialFormatException should be thrown."); + assertEquals("An invalid input stream was provided.", exception.getMessage()); } @Test - public void fromJson_identityPoolCredentialsWorkload() { + void fromJson_identityPoolCredentialsWorkload() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -168,7 +166,7 @@ public void fromJson_identityPoolCredentialsWorkload() { } @Test - public void fromJson_identityPoolCredentialsWorkforce() { + void fromJson_identityPoolCredentialsWorkforce() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -186,7 +184,7 @@ public void fromJson_identityPoolCredentialsWorkforce() { } @Test - public void fromJson_awsCredentials() throws IOException { + void fromJson_awsCredentials() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonAwsCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -200,43 +198,40 @@ public void fromJson_awsCredentials() throws IOException { } @Test - public void fromJson_nullJson_throws() { - try { - ExternalAccountCredentials.fromJson(/* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); - fail("Exception should be thrown."); - } catch (NullPointerException e) { - // Expected. - } + void fromJson_nullJson_throws() { + assertThrows( + NullPointerException.class, + () -> + ExternalAccountCredentials.fromJson( + /* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY), + "Exception should be thrown."); } @Test - public void fromJson_invalidServiceAccountImpersonationUrl_throws() { + void fromJson_invalidServiceAccountImpersonationUrl_throws() { GenericJson json = buildJsonIdentityPoolCredential(); json.put("service_account_impersonation_url", "https://iamcredentials.googleapis.com"); - try { - ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "Unable to determine target principal from service account impersonation URL.", - e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY), + "Exception should be thrown."); + assertEquals( + "Unable to determine target principal from service account impersonation URL.", + exception.getMessage()); } @Test - public void fromJson_nullTransport_throws() { - try { - ExternalAccountCredentials.fromJson( - new HashMap(), /* transportFactory= */ null); - fail("Exception should be thrown."); - } catch (NullPointerException e) { - // Expected. - } + void fromJson_nullTransport_throws() { + assertThrows( + NullPointerException.class, + () -> ExternalAccountCredentials.fromJson(new HashMap<>(), /* transportFactory= */ null), + "Exception should be thrown."); } @Test - public void fromJson_invalidWorkforceAudiences_throws() { + void fromJson_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "//iam.googleapis.com/locations/global/workloadIdentityPools/pool/providers/provider", @@ -249,65 +244,71 @@ public void fromJson_invalidWorkforceAudiences_throws() { "//iam.googleapis.com/locations/global/workforce/providers"); for (String audience : invalidAudiences) { - try { - GenericJson json = buildJsonIdentityPoolCredential(); - json.put("audience", audience); - json.put("workforce_pool_user_project", "userProject"); - - ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", - e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + GenericJson json = buildJsonIdentityPoolCredential(); + json.put("audience", audience); + json.put("workforce_pool_user_project", "userProject"); + + ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY); + }, + "Exception should be thrown."); + assertEquals( + "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", + exception.getMessage()); } } @Test - public void constructor_invalidTokenUrl() { - try { - new TestExternalAccountCredentials( - transportFactory, - "audience", - "subjectTokenType", - "tokenUrl", - new TestCredentialSource(new HashMap()), - STS_URL, - /* serviceAccountImpersonationUrl= */ null, - "quotaProjectId", - /* clientId= */ null, - /* clientSecret= */ null, - /* scopes= */ null); - fail("Should have failed since an invalid token URL was passed."); - } catch (IllegalArgumentException e) { - assertEquals("The provided token URL is invalid.", e.getMessage()); - } + void constructor_invalidTokenUrl() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + new TestExternalAccountCredentials( + transportFactory, + "audience", + "subjectTokenType", + "tokenUrl", + new TestCredentialSource(new HashMap()), + STS_URL, + /* serviceAccountImpersonationUrl= */ null, + "quotaProjectId", + /* clientId= */ null, + /* clientSecret= */ null, + /* scopes= */ null); + }, + "Should have failed since an invalid token URL was passed."); + assertEquals("The provided token URL is invalid.", exception.getMessage()); } @Test - public void constructor_invalidServiceAccountImpersonationUrl() { - try { - new TestExternalAccountCredentials( - transportFactory, - "audience", - "subjectTokenType", - "tokenUrl", - new TestCredentialSource(new HashMap()), - /* tokenInfoUrl= */ null, - "serviceAccountImpersonationUrl", - "quotaProjectId", - /* clientId= */ null, - /* clientSecret= */ null, - /* scopes= */ null); - fail("Should have failed since an invalid token URL was passed."); - } catch (IllegalArgumentException e) { - assertEquals("The provided token URL is invalid.", e.getMessage()); - } + void constructor_invalidServiceAccountImpersonationUrl() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + new TestExternalAccountCredentials( + transportFactory, + "audience", + "subjectTokenType", + "tokenUrl", + new TestCredentialSource(new HashMap<>()), + /* tokenInfoUrl= */ null, + "serviceAccountImpersonationUrl", + "quotaProjectId", + /* clientId= */ null, + /* clientSecret= */ null, + /* scopes= */ null); + }, + "Should have failed since an invalid token URL was passed."); + assertEquals("The provided token URL is invalid.", exception.getMessage()); } @Test - public void exchangeExternalCredentialForAccessToken() throws IOException { + void exchangeExternalCredentialForAccessToken() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -326,7 +327,7 @@ public void exchangeExternalCredentialForAccessToken() throws IOException { } @Test - public void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { + void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -350,7 +351,7 @@ public void exchangeExternalCredentialForAccessToken_withInternalOptions() throw } @Test - public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() + void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -373,7 +374,7 @@ public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersona } @Test - public void exchangeExternalCredentialForAccessToken_throws() throws IOException { + void exchangeExternalCredentialForAccessToken_throws() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -386,18 +387,18 @@ public void exchangeExternalCredentialForAccessToken_throws() throws IOException StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); - try { - credential.exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest); - fail("Exception should be thrown."); - } catch (OAuthException e) { - assertEquals(errorCode, e.getErrorCode()); - assertEquals(errorDescription, e.getErrorDescription()); - assertEquals(errorUri, e.getErrorUri()); - } + OAuthException exception = + assertThrows( + OAuthException.class, + () -> credential.exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest), + "Exception should be thrown."); + assertEquals(errorCode, exception.getErrorCode()); + assertEquals(errorDescription, exception.getErrorDescription()); + assertEquals(errorUri, exception.getErrorUri()); } @Test - public void getRequestMetadata_withQuotaProjectId() throws IOException { + void getRequestMetadata_withQuotaProjectId() throws IOException { TestExternalAccountCredentials testCredentials = new TestExternalAccountCredentials( transportFactory, @@ -419,7 +420,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException { } @Test - public void validateTokenUrl_validUrls() { + void validateTokenUrl_validUrls() { List validUrls = Arrays.asList( "https://sts.googleapis.com", @@ -438,7 +439,7 @@ public void validateTokenUrl_validUrls() { } @Test - public void validateTokenUrl_invalidUrls() { + void validateTokenUrl_invalidUrls() { List invalidUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -462,17 +463,17 @@ public void validateTokenUrl_invalidUrls() { "https://us-east-1.sts.googleapis.com.evil.com"); for (String url : invalidUrls) { - try { - ExternalAccountCredentials.validateTokenUrl(url); - fail("Should have failed since an invalid URL was passed."); - } catch (IllegalArgumentException e) { - assertEquals("The provided token URL is invalid.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> ExternalAccountCredentials.validateTokenUrl(url), + "Should have failed since an invalid URL was passed."); + assertEquals("The provided token URL is invalid.", exception.getMessage()); } } @Test - public void validateServiceAccountImpersonationUrls_validUrls() { + void validateServiceAccountImpersonationUrls_validUrls() { List validUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -492,7 +493,7 @@ public void validateServiceAccountImpersonationUrls_validUrls() { } @Test - public void validateServiceAccountImpersonationUrls_invalidUrls() { + void validateServiceAccountImpersonationUrls_invalidUrls() { List invalidUrls = Arrays.asList( "https://sts.googleapis.com", @@ -516,12 +517,13 @@ public void validateServiceAccountImpersonationUrls_invalidUrls() { "https://us-east-1.iamcredentials.googleapis.com.evil.com"); for (String url : invalidUrls) { - try { - ExternalAccountCredentials.validateServiceAccountImpersonationInfoUrl(url); - fail("Should have failed since an invalid URL was passed."); - } catch (IllegalArgumentException e) { - assertEquals("The provided service account impersonation URL is invalid.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> ExternalAccountCredentials.validateServiceAccountImpersonationInfoUrl(url), + "Should have failed since an invalid URL was passed."); + assertEquals( + "The provided service account impersonation URL is invalid.", exception.getMessage()); } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java index 36774de58..028f9235e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpTransport; import com.google.api.client.testing.http.MockHttpTransport; @@ -54,12 +54,9 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link GoogleCredentials}. */ -@RunWith(JUnit4.class) public class GoogleCredentialsTest { private static final String SA_CLIENT_EMAIL = @@ -104,39 +101,30 @@ public HttpTransport create() { } @Test - public void getApplicationDefault_nullTransport_throws() throws IOException { - try { - GoogleCredentials.getApplicationDefault(null); - fail(); - } catch (NullPointerException expected) { - // Expected - } + void getApplicationDefault_nullTransport_throws() { + assertThrows(NullPointerException.class, () -> GoogleCredentials.getApplicationDefault(null)); } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() { InputStream stream = new ByteArrayInputStream("foo".getBytes()); - try { - GoogleCredentials.fromStream(stream, null); - fail("Should throw if HttpTransportFactory is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> GoogleCredentials.fromStream(stream, null), + "Should throw if HttpTransportFactory is null"); } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - try { - GoogleCredentials.fromStream(null, transportFactory); - fail("Should throw if InputStream is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> GoogleCredentials.fromStream(null, transportFactory), + "Should throw if InputStream is null"); } @Test - public void fromStream_serviceAccount_providesToken() throws IOException { + void fromStream_serviceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -157,7 +145,7 @@ public void fromStream_serviceAccount_providesToken() throws IOException { } @Test - public void fromStream_serviceAccountNoClientId_throws() throws IOException { + void fromStream_serviceAccountNoClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -166,7 +154,7 @@ public void fromStream_serviceAccountNoClientId_throws() throws IOException { } @Test - public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { + void fromStream_serviceAccountNoClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -175,7 +163,7 @@ public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { } @Test - public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { + void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -184,7 +172,7 @@ public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { } @Test - public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { + void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -193,7 +181,7 @@ public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException } @Test - public void fromStream_user_providesToken() throws IOException { + void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(USER_CLIENT_ID, USER_CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -209,7 +197,7 @@ public void fromStream_user_providesToken() throws IOException { } @Test - public void fromStream_userNoClientId_throws() throws IOException { + void fromStream_userNoClientId_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(null, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -217,7 +205,7 @@ public void fromStream_userNoClientId_throws() throws IOException { } @Test - public void fromStream_userNoClientSecret_throws() throws IOException { + void fromStream_userNoClientSecret_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(USER_CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); @@ -225,7 +213,7 @@ public void fromStream_userNoClientSecret_throws() throws IOException { } @Test - public void fromStream_userNoRefreshToken_throws() throws IOException { + void fromStream_userNoRefreshToken_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, null, QUOTA_PROJECT); @@ -234,7 +222,7 @@ public void fromStream_userNoRefreshToken_throws() throws IOException { } @Test - public void fromStream_identityPoolCredentials_providesToken() throws IOException { + void fromStream_identityPoolCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -253,7 +241,7 @@ public void fromStream_identityPoolCredentials_providesToken() throws IOExceptio } @Test - public void fromStream_awsCredentials_providesToken() throws IOException { + void fromStream_awsCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -273,7 +261,7 @@ public void fromStream_awsCredentials_providesToken() throws IOException { } @Test - public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { + void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -307,7 +295,7 @@ public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOE } @Test - public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { + void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -338,7 +326,7 @@ public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws } @Test - public void createScoped_overloadCallsImplementation() { + void createScoped_overloadCallsImplementation() { final AtomicReference> called = new AtomicReference<>(); final GoogleCredentials expectedScopedCredentials = new GoogleCredentials(); @@ -358,13 +346,12 @@ public GoogleCredentials createScoped(Collection scopes) { } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - try { - GoogleCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY); - fail( - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains(expectedMessageContent)); - } + IOException exception = + assertThrows( + IOException.class, + () -> GoogleCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY), + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + assertTrue(exception.getMessage().contains(expectedMessageContent)); } } From e9dfaf993556e806e886a542ea77d8239857ce3e Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Mon, 11 Oct 2021 21:18:25 +0300 Subject: [PATCH 8/9] chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - third iteration (#756) (#764) --- .../auth/oauth2/IdTokenCredentialsTest.java | 15 +- .../com/google/auth/oauth2/IdTokenTest.java | 25 +- .../oauth2/IdentityPoolCredentialsTest.java | 220 +++++++------- .../oauth2/ImpersonatedCredentialsTest.java | 281 +++++++++--------- 4 files changed, 264 insertions(+), 277 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java index 7dbf770c3..e3dcec4b5 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java @@ -31,19 +31,16 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link IdTokenCredentials}. */ -@RunWith(JUnit4.class) -public class IdTokenCredentialsTest extends BaseSerializationTest { +class IdTokenCredentialsTest extends BaseSerializationTest { @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -69,7 +66,7 @@ public void hashCode_equals() throws IOException { } @Test - public void toString_equals() throws IOException { + void toString_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -95,7 +92,7 @@ public void toString_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java index 14c94995e..ae0f921e0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java @@ -31,19 +31,16 @@ package com.google.auth.oauth2; -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.assertTrue; import java.io.IOException; import java.util.Date; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for AccessToken */ -@RunWith(JUnit4.class) -public class IdTokenTest extends BaseSerializationTest { +class IdTokenTest extends BaseSerializationTest { private static final String TOKEN_1 = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjM0OTRiMWU3ODZjZGFkMDkyZTQyMzc2NmJiZTM3ZjU0ZWQ4N2IyMmQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhdWQiOiJodHRwczovL2Zvby5iYXIiLCJhenAiOiJzdmMtMi00MjlAbWluZXJhbC1taW51dGlhLTgyMC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInN1YiI6IjEwMDE0NzEwNjk5Njc2NDQ3OTA4NSIsImVtYWlsIjoic3ZjLTItNDI5QG1pbmVyYWwtbWludXRpYS04MjAuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaWF0IjoxNTY1Mzg3NTM4LCJleHAiOjE1NjUzOTExMzh9.foo"; @@ -52,14 +49,14 @@ public class IdTokenTest extends BaseSerializationTest { private static final Date EXPIRATION_DATE = new Date((long) 1565391138 * 1000); @Test - public void constructor() throws IOException { + void constructor() throws IOException { IdToken idToken = IdToken.create(TOKEN_1); assertEquals(TOKEN_1, idToken.getTokenValue()); assertEquals(EXPIRATION_DATE, idToken.getExpirationTime()); } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertTrue(accessToken.equals(otherAccessToken)); @@ -67,7 +64,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_token() throws IOException { + void equals_false_token() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_2); assertFalse(accessToken.equals(otherAccessToken)); @@ -75,7 +72,7 @@ public void equals_false_token() throws IOException { } @Test - public void toString_test() throws IOException { + void toString_test() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); String expectedToString = String.format( @@ -85,14 +82,14 @@ public void toString_test() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java index b240e1d16..bde045bff 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java @@ -33,9 +33,9 @@ import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.assertThrows; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -52,13 +52,10 @@ import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link IdentityPoolCredentials}. */ -@RunWith(JUnit4.class) -public class IdentityPoolCredentialsTest { +class IdentityPoolCredentialsTest { private static final String STS_URL = "https://sts.googleapis.com"; @@ -96,7 +93,7 @@ public HttpTransport create() { } @Test - public void createdScoped_clonedCredentialWithAddedScopes() { + void createdScoped_clonedCredentialWithAddedScopes() { IdentityPoolCredentials credentials = (IdentityPoolCredentials) IdentityPoolCredentials.newBuilder(FILE_SOURCED_CREDENTIAL) @@ -125,7 +122,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() { } @Test - public void retrieveSubjectToken_fileSourced() throws IOException { + void retrieveSubjectToken_fileSourced() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -152,7 +149,7 @@ public void retrieveSubjectToken_fileSourced() throws IOException { } @Test - public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { + void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -194,7 +191,7 @@ public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException } @Test - public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { + void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -206,16 +203,16 @@ public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOExc credentialSourceMap.put("file", file.getAbsolutePath()); credentialSourceMap.put("format", formatMap); - try { - new IdentityPoolCredentialSource(credentialSourceMap); - fail("Exception should be thrown due to null format."); - } catch (IllegalArgumentException e) { - assertEquals("Invalid credential source format type: null.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new IdentityPoolCredentialSource(credentialSourceMap), + "Exception should be thrown due to null format."); + assertEquals("Invalid credential source format type: null.", exception.getMessage()); } @Test - public void retrieveSubjectToken_noFile_throws() { + void retrieveSubjectToken_noFile_throws() { Map credentialSourceMap = new HashMap<>(); String path = "badPath"; credentialSourceMap.put("file", path); @@ -228,18 +225,16 @@ public void retrieveSubjectToken_noFile_throws() { .setCredentialSource(credentialSource) .build(); - try { - credentials.retrieveSubjectToken(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals( - String.format("Invalid credential location. The file at %s does not exist.", path), - e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, credentials::retrieveSubjectToken, "Exception should be thrown."); + assertEquals( + String.format("Invalid credential location. The file at %s does not exist.", path), + exception.getMessage()); } @Test - public void retrieveSubjectToken_urlSourced() throws IOException { + void retrieveSubjectToken_urlSourced() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -257,7 +252,7 @@ public void retrieveSubjectToken_urlSourced() throws IOException { } @Test - public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { + void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -283,7 +278,7 @@ public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { } @Test - public void retrieveSubjectToken_urlSourcedCredential_throws() { + void retrieveSubjectToken_urlSourcedCredential_throws() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -298,19 +293,17 @@ public void retrieveSubjectToken_urlSourcedCredential_throws() { buildUrlBasedCredentialSource(transportFactory.transport.getMetadataUrl())) .build(); - try { - credential.retrieveSubjectToken(); - fail("Exception should be thrown."); - } catch (IOException e) { - assertEquals( - String.format( - "Error getting subject token from metadata server: %s", response.getMessage()), - e.getMessage()); - } + IOException exception = + assertThrows( + IOException.class, credential::retrieveSubjectToken, "Exception should be thrown."); + assertEquals( + String.format( + "Error getting subject token from metadata server: %s", response.getMessage()), + exception.getMessage()); } @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -329,7 +322,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc } @Test - public void refreshAccessToken_internalOptionsSet() throws IOException { + void refreshAccessToken_internalOptionsSet() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -363,7 +356,7 @@ public void refreshAccessToken_internalOptionsSet() throws IOException { } @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -386,19 +379,19 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept } @Test - public void identityPoolCredentialSource_invalidSourceType() { - try { - new IdentityPoolCredentialSource(new HashMap()); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "Missing credential source file location or URL. At least one must be specified.", - e.getMessage()); - } + void identityPoolCredentialSource_invalidSourceType() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new IdentityPoolCredentialSource(new HashMap<>()), + "Exception should be thrown."); + assertEquals( + "Missing credential source file location or URL. At least one must be specified.", + exception.getMessage()); } @Test - public void identityPoolCredentialSource_invalidFormatType() { + void identityPoolCredentialSource_invalidFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -406,16 +399,16 @@ public void identityPoolCredentialSource_invalidFormatType() { format.put("type", "unsupportedType"); credentialSourceMap.put("format", format); - try { - new IdentityPoolCredentialSource(credentialSourceMap); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals("Invalid credential source format type: unsupportedType.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new IdentityPoolCredentialSource(credentialSourceMap), + "Exception should be thrown."); + assertEquals("Invalid credential source format type: unsupportedType.", exception.getMessage()); } @Test - public void identityPoolCredentialSource_nullFormatType() { + void identityPoolCredentialSource_nullFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -423,16 +416,16 @@ public void identityPoolCredentialSource_nullFormatType() { format.put("type", null); credentialSourceMap.put("format", format); - try { - new IdentityPoolCredentialSource(credentialSourceMap); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals("Invalid credential source format type: null.", e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new IdentityPoolCredentialSource(credentialSourceMap), + "Exception should be thrown."); + assertEquals("Invalid credential source format type: null.", exception.getMessage()); } @Test - public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { + void identityPoolCredentialSource_subjectTokenFieldNameUnset() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -440,18 +433,18 @@ public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { format.put("type", "json"); credentialSourceMap.put("format", format); - try { - new IdentityPoolCredentialSource(credentialSourceMap); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "When specifying a JSON credential type, the subject_token_field_name must be set.", - e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> new IdentityPoolCredentialSource(credentialSourceMap), + "Exception should be thrown."); + assertEquals( + "When specifying a JSON credential type, the subject_token_field_name must be set.", + exception.getMessage()); } @Test - public void builder() { + void builder() { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -485,7 +478,7 @@ public void builder() { } @Test - public void builder_invalidWorkforceAudiences_throws() { + void builder_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -499,45 +492,50 @@ public void builder_invalidWorkforceAudiences_throws() { "//iam.googleapis.com/locations/global/workforce/providers"); for (String audience : invalidAudiences) { - try { - IdentityPoolCredentials.newBuilder() - .setWorkforcePoolUserProject("workforcePoolUserProject") - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setAudience(audience) - .setSubjectTokenType("subjectTokenType") - .setTokenUrl(STS_URL) - .setTokenInfoUrl("tokenInfoUrl") - .setCredentialSource(FILE_CREDENTIAL_SOURCE) - .setQuotaProjectId("quotaProjectId") - .build(); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", - e.getMessage()); - } + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + IdentityPoolCredentials.newBuilder() + .setWorkforcePoolUserProject("workforcePoolUserProject") + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setAudience(audience) + .setSubjectTokenType("subjectTokenType") + .setTokenUrl(STS_URL) + .setTokenInfoUrl("tokenInfoUrl") + .setCredentialSource(FILE_CREDENTIAL_SOURCE) + .setQuotaProjectId("quotaProjectId") + .build(); + }, + "Exception should be thrown."); + assertEquals( + "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", + exception.getMessage()); } } @Test - public void builder_emptyWorkforceUserProjectWithWorkforceAudience_throws() { - try { - IdentityPoolCredentials.newBuilder() - .setWorkforcePoolUserProject("") - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setAudience("//iam.googleapis.com/locations/global/workforcePools/providers/provider") - .setSubjectTokenType("subjectTokenType") - .setTokenUrl(STS_URL) - .setTokenInfoUrl("tokenInfoUrl") - .setCredentialSource(FILE_CREDENTIAL_SOURCE) - .setQuotaProjectId("quotaProjectId") - .build(); - fail("Exception should be thrown."); - } catch (IllegalArgumentException e) { - assertEquals( - "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", - e.getMessage()); - } + void builder_emptyWorkforceUserProjectWithWorkforceAudience_throws() { + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> { + IdentityPoolCredentials.newBuilder() + .setWorkforcePoolUserProject("") + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setAudience( + "//iam.googleapis.com/locations/global/workforcePools/providers/provider") + .setSubjectTokenType("subjectTokenType") + .setTokenUrl(STS_URL) + .setTokenInfoUrl("tokenInfoUrl") + .setCredentialSource(FILE_CREDENTIAL_SOURCE) + .setQuotaProjectId("quotaProjectId") + .build(); + }, + "Exception should be thrown."); + assertEquals( + "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", + exception.getMessage()); } static InputStream writeIdentityPoolCredentialsStream( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java index 8d834abde..3eeb2d2db 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java @@ -31,14 +31,14 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +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 com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -66,14 +66,11 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Test case for {@link ImpersonatedCredentials}. */ -@RunWith(JUnit4.class) -public class ImpersonatedCredentialsTest extends BaseSerializationTest { +class ImpersonatedCredentialsTest extends BaseSerializationTest { public static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -145,8 +142,8 @@ public HttpTransport create() { private GoogleCredentials sourceCredentials; private MockIAMCredentialsServiceTransportFactory mockTransportFactory; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { sourceCredentials = getSourceCredentials(); mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); } @@ -168,8 +165,8 @@ private GoogleCredentials getSourceCredentials() throws IOException { return sourceCredentials; } - @Test() - public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { + @Test + void fromJson_userAsSource_WithQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_URL, @@ -189,8 +186,8 @@ public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() - public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { + @Test + void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_URL, @@ -210,8 +207,8 @@ public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() - public void fromJson_userAsSource_MissingDelegatesField() throws IOException { + @Test + void fromJson_userAsSource_MissingDelegatesField() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_URL, @@ -232,8 +229,8 @@ public void fromJson_userAsSource_MissingDelegatesField() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() - public void fromJson_ServiceAccountAsSource() throws IOException { + @Test + void fromJson_ServiceAccountAsSource() throws IOException { GenericJson json = buildImpersonationCredentialsJson(IMPERSONATION_URL, DELEGATES, QUOTA_PROJECT_ID); ImpersonatedCredentials credentials = @@ -247,19 +244,19 @@ public void fromJson_ServiceAccountAsSource() throws IOException { assertTrue(sourceCredentials instanceof ServiceAccountCredentials); } - @Test() - public void fromJson_InvalidFormat() throws IOException { + @Test + void fromJson_InvalidFormat() throws IOException { GenericJson json = buildInvalidCredentialsJson(); - try { - ImpersonatedCredentials.fromJson(json, mockTransportFactory); - fail("An exception should be thrown."); - } catch (CredentialFormatException e) { - assertEquals("An invalid input stream was provided.", e.getMessage()); - } + CredentialFormatException exception = + assertThrows( + CredentialFormatException.class, + () -> ImpersonatedCredentials.fromJson(json, mockTransportFactory), + "An exception should be thrown."); + assertEquals("An invalid input stream was provided.", exception.getMessage()); } - @Test() - public void createScopedRequired_True() { + @Test + void createScopedRequired_True() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -271,8 +268,8 @@ public void createScopedRequired_True() { assertTrue(targetCredentials.createScopedRequired()); } - @Test() - public void createScopedRequired_False() { + @Test + void createScopedRequired_False() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -284,8 +281,8 @@ public void createScopedRequired_False() { assertFalse(targetCredentials.createScopedRequired()); } - @Test() - public void createScoped() { + @Test + void createScoped() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -307,8 +304,8 @@ public void createScoped() { assertEquals(Arrays.asList("scope1", "scope2"), scoped_credentials.getScopes()); } - @Test() - public void refreshAccessToken_unauthorized() throws IOException { + @Test + void refreshAccessToken_unauthorized() throws IOException { String expectedMessage = "The caller does not have permission"; mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -326,17 +323,17 @@ public void refreshAccessToken_unauthorized() throws IOException { VALID_LIFETIME, mockTransportFactory); - try { - targetCredentials.refreshAccessToken().getTokenValue(); - fail(String.format("Should throw exception with message containing '%s'", expectedMessage)); - } catch (IOException expected) { - assertEquals("Error requesting access token", expected.getMessage()); - assertTrue(expected.getCause().getMessage().contains(expectedMessage)); - } + IOException exception = + assertThrows( + IOException.class, + () -> targetCredentials.refreshAccessToken().getTokenValue(), + String.format("Should throw exception with message containing '%s'", expectedMessage)); + assertEquals("Error requesting access token", exception.getMessage()); + assertTrue(exception.getCause().getMessage().contains(expectedMessage)); } - @Test() - public void refreshAccessToken_malformedTarget() throws IOException { + @Test + void refreshAccessToken_malformedTarget() throws IOException { String invalidTargetEmail = "foo"; String expectedMessage = "Request contains an invalid argument"; @@ -355,58 +352,60 @@ public void refreshAccessToken_malformedTarget() throws IOException { VALID_LIFETIME, mockTransportFactory); - try { - targetCredentials.refreshAccessToken().getTokenValue(); - fail(String.format("Should throw exception with message containing '%s'", expectedMessage)); - } catch (IOException expected) { - assertEquals("Error requesting access token", expected.getMessage()); - assertTrue(expected.getCause().getMessage().contains(expectedMessage)); - } + IOException exception = + assertThrows( + IOException.class, + () -> targetCredentials.refreshAccessToken().getTokenValue(), + String.format("Should throw exception with message containing '%s'", expectedMessage)); + assertEquals("Error requesting access token", exception.getMessage()); + assertTrue(exception.getCause().getMessage().contains(expectedMessage)); } - @Test() - public void credential_with_zero_lifetime() throws IllegalStateException { + @Test + void credential_with_zero_lifetime() throws IllegalStateException { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, SCOPES, 0); assertEquals(3600, targetCredentials.getLifetime()); } - @Test() - public void credential_with_invalid_lifetime() throws IOException, IllegalStateException { - - try { - ImpersonatedCredentials targetCredentials = - ImpersonatedCredentials.create( - sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, SCOPES, INVALID_LIFETIME); - targetCredentials.refreshAccessToken().getTokenValue(); - fail( - String.format( - "Should throw exception with message containing '%s'", - "lifetime must be less than or equal to 43200")); - } catch (IllegalStateException expected) { - assertTrue(expected.getMessage().contains("lifetime must be less than or equal to 43200")); - } + @Test + void credential_with_invalid_lifetime() throws IOException, IllegalStateException { + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> { + ImpersonatedCredentials targetCredentials = + ImpersonatedCredentials.create( + sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, SCOPES, INVALID_LIFETIME); + targetCredentials.refreshAccessToken().getTokenValue(); + }, + String.format( + "Should throw exception with message containing '%s'", + "lifetime must be less than or equal to 43200")); + assertTrue(exception.getMessage().contains("lifetime must be less than or equal to 43200")); } - @Test() - public void credential_with_invalid_scope() throws IOException, IllegalStateException { - - try { - ImpersonatedCredentials targetCredentials = - ImpersonatedCredentials.create( - sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, null, VALID_LIFETIME); - targetCredentials.refreshAccessToken().getTokenValue(); - fail( - String.format( - "Should throw exception with message containing '%s'", "Scopes cannot be null")); - } catch (IllegalStateException expected) { - assertTrue(expected.getMessage().contains("Scopes cannot be null")); - } + @Test + void credential_with_invalid_scope() throws IOException, IllegalStateException { + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> { + ImpersonatedCredentials targetCredentials = + ImpersonatedCredentials.create( + sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, null, VALID_LIFETIME); + targetCredentials.refreshAccessToken().getTokenValue(); + }, + String.format( + "Should throw exception with message containing '%s'", "Scopes cannot be null")); + assertTrue(exception.getMessage().contains("Scopes cannot be null")); } - @Test() - public void refreshAccessToken_success() throws IOException, IllegalStateException { + @Test + void refreshAccessToken_success() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -423,8 +422,8 @@ public void refreshAccessToken_success() throws IOException, IllegalStateExcepti assertEquals(ACCESS_TOKEN, targetCredentials.refreshAccessToken().getTokenValue()); } - @Test() - public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { + @Test + void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -446,8 +445,8 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalS assertEquals(QUOTA_PROJECT_ID, headerValues.get(0)); } - @Test() - public void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { + @Test + void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -465,8 +464,8 @@ public void getRequestMetadata_withoutQuotaProjectId() throws IOException, Illeg assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test() - public void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { + @Test + void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -484,8 +483,8 @@ public void refreshAccessToken_delegates_success() throws IOException, IllegalSt assertEquals(ACCESS_TOKEN, targetCredentials.refreshAccessToken().getTokenValue()); } - @Test() - public void refreshAccessToken_invalidDate() throws IllegalStateException { + @Test + void refreshAccessToken_invalidDate() throws IllegalStateException { String expectedMessage = "Unparseable date"; mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -500,16 +499,16 @@ public void refreshAccessToken_invalidDate() throws IllegalStateException { VALID_LIFETIME, mockTransportFactory); - try { - targetCredentials.refreshAccessToken().getTokenValue(); - fail(String.format("Should throw exception with message containing '%s'", expectedMessage)); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains(expectedMessage)); - } + IOException exception = + assertThrows( + IOException.class, + () -> targetCredentials.refreshAccessToken().getTokenValue(), + String.format("Should throw exception with message containing '%s'", expectedMessage)); + assertTrue(exception.getMessage().contains(expectedMessage)); } @Test - public void getAccount_sameAs() { + void getAccount_sameAs() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -526,7 +525,7 @@ public void getAccount_sameAs() { } @Test - public void sign_sameAs() { + void sign_sameAs() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -548,7 +547,7 @@ public void sign_sameAs() { } @Test - public void sign_requestIncludesDelegates() throws IOException { + void sign_requestIncludesDelegates() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -579,7 +578,7 @@ public void sign_requestIncludesDelegates() throws IOException { } @Test - public void sign_usesSourceCredentials() { + void sign_usesSourceCredentials() { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date expiry = c.getTime(); @@ -612,7 +611,7 @@ public void sign_usesSourceCredentials() { } @Test - public void sign_accessDenied_throws() { + void sign_accessDenied_throws() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -632,19 +631,19 @@ public void sign_accessDenied_throws() { mockTransportFactory.transport.setErrorResponseCodeAndMessage( HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Sign Error"); - try { - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - targetCredentials.sign(bytes); - fail("Signing should have failed"); - } catch (SigningException e) { - assertEquals("Failed to sign the provided bytes", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("403")); - } + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + SigningException exception = + assertThrows( + SigningException.class, + () -> targetCredentials.sign(bytes), + "Signing should have failed"); + assertEquals("Failed to sign the provided bytes", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("403")); } @Test - public void sign_serverError_throws() { + void sign_serverError_throws() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -664,19 +663,19 @@ public void sign_serverError_throws() { mockTransportFactory.transport.setErrorResponseCodeAndMessage( HttpStatusCodes.STATUS_CODE_SERVER_ERROR, "Sign Error"); - try { - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - targetCredentials.sign(bytes); - fail("Signing should have failed"); - } catch (SigningException e) { - assertEquals("Failed to sign the provided bytes", e.getMessage()); - assertNotNull(e.getCause()); - assertTrue(e.getCause().getMessage().contains("500")); - } + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + SigningException exception = + assertThrows( + SigningException.class, + () -> targetCredentials.sign(bytes), + "Signing should have failed"); + assertEquals("Failed to sign the provided bytes", exception.getMessage()); + assertNotNull(exception.getCause()); + assertTrue(exception.getCause().getMessage().contains("500")); } @Test - public void idTokenWithAudience_sameAs() throws IOException { + void idTokenWithAudience_sameAs() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -707,7 +706,7 @@ public void idTokenWithAudience_sameAs() throws IOException { } @Test - public void idTokenWithAudience_withEmail() throws IOException { + void idTokenWithAudience_withEmail() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -737,7 +736,7 @@ public void idTokenWithAudience_withEmail() throws IOException { } @Test - public void idToken_withServerError() { + void idToken_withServerError() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -761,15 +760,13 @@ public void idToken_withServerError() { .setIdTokenProvider(targetCredentials) .setTargetAudience(targetAudience) .build(); - try { - tokenCredential.refresh(); - } catch (IOException e) { - assertTrue(e.getMessage().contains("Error code 500 trying to getIDToken")); - } + + IOException exception = assertThrows(IOException.class, tokenCredential::refresh); + assertTrue(exception.getMessage().contains("Error code 500 trying to getIDToken")); } @Test - public void idToken_withOtherError() { + void idToken_withOtherError() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -793,15 +790,13 @@ public void idToken_withOtherError() { .setIdTokenProvider(targetCredentials) .setTargetAudience(targetAudience) .build(); - try { - tokenCredential.refresh(); - } catch (IOException e) { - assertTrue(e.getMessage().contains("Unexpected Error code 301 trying to getIDToken")); - } + + IOException exception = assertThrows(IOException.class, tokenCredential::refresh); + assertTrue(exception.getMessage().contains("Unexpected Error code 301 trying to getIDToken")); } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -828,7 +823,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); From 4ae533b321607949f8c9ae65a147468fef6c2b28 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 11 Oct 2021 17:02:03 -0400 Subject: [PATCH 9/9] chore: release 1.2.1 (#757) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> Co-authored-by: Emily Ball --- CHANGELOG.md | 7 +++++++ README.md | 6 +++--- appengine/pom.xml | 2 +- bom/pom.xml | 2 +- credentials/pom.xml | 2 +- oauth2_http/pom.xml | 2 +- pom.xml | 2 +- versions.txt | 12 ++++++------ 8 files changed, 21 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c63168d05..9c479b252 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +### [1.2.1](https://www.github.com/googleapis/google-auth-library-java/compare/v1.2.0...v1.2.1) (2021-10-11) + + +### Bug Fixes + +* disabling self-signed jwt for domain wide delegation ([#754](https://www.github.com/googleapis/google-auth-library-java/issues/754)) ([ac70a27](https://www.github.com/googleapis/google-auth-library-java/commit/ac70a279bdaf681507d7815264a3f5e92fd2aaa6)) + ## [1.2.0](https://www.github.com/googleapis/google-auth-library-java/compare/v1.1.0...v1.2.0) (2021-09-30) diff --git a/README.md b/README.md index 67554f69c..122ed7efd 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ If you are using Maven, add this to your pom.xml file (notice that you can repla com.google.auth google-auth-library-oauth2-http - 1.2.0 + 1.2.1 ``` [//]: # ({x-version-update-end}) @@ -41,7 +41,7 @@ If you are using Gradle, add this to your dependencies [//]: # ({x-version-update-start:google-auth-library-oauth2-http:released}) ```Groovy -compile 'com.google.auth:google-auth-library-oauth2-http:1.2.0' +compile 'com.google.auth:google-auth-library-oauth2-http:1.2.1' ``` [//]: # ({x-version-update-end}) @@ -49,7 +49,7 @@ If you are using SBT, add this to your dependencies [//]: # ({x-version-update-start:google-auth-library-oauth2-http:released}) ```Scala -libraryDependencies += "com.google.auth" % "google-auth-library-oauth2-http" % "1.2.0" +libraryDependencies += "com.google.auth" % "google-auth-library-oauth2-http" % "1.2.1" ``` [//]: # ({x-version-update-end}) diff --git a/appengine/pom.xml b/appengine/pom.xml index 4d4f77010..65c2b233d 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.1-SNAPSHOT + 1.2.1 ../pom.xml diff --git a/bom/pom.xml b/bom/pom.xml index ccdc4161b..2155b45d5 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.auth google-auth-library-bom - 1.2.1-SNAPSHOT + 1.2.1 pom Google Auth Library for Java BOM diff --git a/credentials/pom.xml b/credentials/pom.xml index 9ead18aa2..3b53f1e61 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -4,7 +4,7 @@ com.google.auth google-auth-library-parent - 1.2.1-SNAPSHOT + 1.2.1 ../pom.xml diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index 0e59a9890..f95fcb83c 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.1-SNAPSHOT + 1.2.1 ../pom.xml diff --git a/pom.xml b/pom.xml index aa9f36c67..a90d8da56 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.auth google-auth-library-parent - 1.2.1-SNAPSHOT + 1.2.1 pom Google Auth Library for Java Client libraries providing authentication and diff --git a/versions.txt b/versions.txt index bedd86331..d14e99cd2 100644 --- a/versions.txt +++ b/versions.txt @@ -1,9 +1,9 @@ # Format: # module:released-version:current-version -google-auth-library:1.2.0:1.2.1-SNAPSHOT -google-auth-library-bom:1.2.0:1.2.1-SNAPSHOT -google-auth-library-parent:1.2.0:1.2.1-SNAPSHOT -google-auth-library-appengine:1.2.0:1.2.1-SNAPSHOT -google-auth-library-credentials:1.2.0:1.2.1-SNAPSHOT -google-auth-library-oauth2-http:1.2.0:1.2.1-SNAPSHOT +google-auth-library:1.2.1:1.2.1 +google-auth-library-bom:1.2.1:1.2.1 +google-auth-library-parent:1.2.1:1.2.1 +google-auth-library-appengine:1.2.1:1.2.1 +google-auth-library-credentials:1.2.1:1.2.1 +google-auth-library-oauth2-http:1.2.1:1.2.1