From ec29abc31879cb82d99b61bec107e97d9c2a033a Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 11 Oct 2021 21:06:20 +0000 Subject: [PATCH 1/8] chore: release 1.2.2-SNAPSHOT (#765) :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/clirr-ignored-differences.xml | 11 ----------- oauth2_http/pom.xml | 2 +- pom.xml | 2 +- versions.txt | 12 ++++++------ 7 files changed, 11 insertions(+), 22 deletions(-) delete mode 100644 oauth2_http/clirr-ignored-differences.xml diff --git a/appengine/pom.xml b/appengine/pom.xml index 65c2b233d..3b9953b32 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.1 + 1.2.2-SNAPSHOT ../pom.xml diff --git a/bom/pom.xml b/bom/pom.xml index 2155b45d5..5a80f6e6c 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 + 1.2.2-SNAPSHOT pom Google Auth Library for Java BOM diff --git a/credentials/pom.xml b/credentials/pom.xml index 3b53f1e61..a7da9af04 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -4,7 +4,7 @@ com.google.auth google-auth-library-parent - 1.2.1 + 1.2.2-SNAPSHOT ../pom.xml diff --git a/oauth2_http/clirr-ignored-differences.xml b/oauth2_http/clirr-ignored-differences.xml deleted file mode 100644 index 76b573848..000000000 --- a/oauth2_http/clirr-ignored-differences.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - 7009 - com/google/auth/oauth2/ServiceAccountJwtAccessCredentials - ServiceAccountJwtAccessCredentials(java.lang.String, java.lang.String, java.security.PrivateKey, java.lang.String) - public - private - - diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index f95fcb83c..e03b5d3d4 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 + 1.2.2-SNAPSHOT ../pom.xml diff --git a/pom.xml b/pom.xml index a90d8da56..15ca9a429 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.auth google-auth-library-parent - 1.2.1 + 1.2.2-SNAPSHOT pom Google Auth Library for Java Client libraries providing authentication and diff --git a/versions.txt b/versions.txt index d14e99cd2..f8a5496f2 100644 --- a/versions.txt +++ b/versions.txt @@ -1,9 +1,9 @@ # Format: # module:released-version:current-version -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 +google-auth-library:1.2.1:1.2.2-SNAPSHOT +google-auth-library-bom:1.2.1:1.2.2-SNAPSHOT +google-auth-library-parent:1.2.1:1.2.2-SNAPSHOT +google-auth-library-appengine:1.2.1:1.2.2-SNAPSHOT +google-auth-library-credentials:1.2.1:1.2.2-SNAPSHOT +google-auth-library-oauth2-http:1.2.1:1.2.2-SNAPSHOT From d7edc453d5fc38f89ce9563f919e5201d2fe880f Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Tue, 12 Oct 2021 18:57:38 +0300 Subject: [PATCH 2/8] chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - fourth iteration (#756) (#766) --- .../google/auth/oauth2/ITDownscopingTest.java | 24 ++-- .../ITWorkloadIdentityFederationTest.java | 22 ++-- .../com/google/auth/oauth2/JwtClaimsTest.java | 24 ++-- .../auth/oauth2/JwtCredentialsTest.java | 109 +++++++++--------- 4 files changed, 87 insertions(+), 92 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java index bd00f42c4..875719fbc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -46,7 +46,7 @@ import com.google.auth.Credentials; import com.google.auth.http.HttpCredentialsAdapter; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Integration tests for Downscoping with Credential Access Boundaries via {@link @@ -56,7 +56,7 @@ * GOOGLE_APPLICATION_CREDENTIALS to point to the same service account configured in the setup * script (downscoping-with-cab-setup.sh). */ -public final class ITDownscopingTest { +class ITDownscopingTest { // Output copied from the setup script (downscoping-with-cab-setup.sh). private static final String GCS_BUCKET_NAME = "cab-int-bucket-cbi3qrv5"; @@ -93,7 +93,7 @@ public final class ITDownscopingTest { * in the same bucket. */ @Test - public void downscoping_serviceAccountSourceWithRefresh() throws IOException { + void downscoping_serviceAccountSourceWithRefresh() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -122,12 +122,12 @@ public AccessToken refreshAccessToken() throws IOException { // Attempt to retrieve the object that the downscoped token does not have access to. This should // fail. - try { - retrieveObjectFromGcs(credentials, GCS_OBJECT_NAME_WITHOUT_PERMISSION); - fail("Call to GCS should have failed."); - } catch (HttpResponseException e) { - assertEquals(403, e.getStatusCode()); - } + HttpResponseException exception = + assertThrows( + HttpResponseException.class, + () -> retrieveObjectFromGcs(credentials, GCS_OBJECT_NAME_WITHOUT_PERMISSION), + "Call to GCS should have failed."); + assertEquals(403, exception.getStatusCode()); } private void retrieveObjectFromGcs(Credentials credentials, String objectName) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index cd4448ced..0683b0b5c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java @@ -31,8 +31,8 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -51,8 +51,8 @@ import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Integration tests for Workload Identity Federation. @@ -62,7 +62,7 @@ * (workloadidentityfederation-setup). These tests call GCS to get bucket information. The bucket * name must be provided through the GCS_BUCKET environment variable. */ -public final class ITWorkloadIdentityFederationTest { +class ITWorkloadIdentityFederationTest { // Copy output from workloadidentityfederation-setup. private static final String AUDIENCE_PREFIX = @@ -75,8 +75,8 @@ public final class ITWorkloadIdentityFederationTest { private String clientEmail; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { GenericJson keys = getServiceAccountKeyFileAsJson(); clientEmail = (String) keys.get("client_email"); } @@ -89,7 +89,7 @@ public void setup() throws IOException { * service account key. */ @Test - public void identityPoolCredentials() throws IOException { + void identityPoolCredentials() throws IOException { IdentityPoolCredentials identityPoolCredentials = (IdentityPoolCredentials) ExternalAccountCredentials.fromJson( @@ -108,7 +108,7 @@ public void identityPoolCredentials() throws IOException { * service account key. */ @Test - public void awsCredentials() throws Exception { + void awsCredentials() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -202,9 +202,7 @@ private GenericJson buildAwsCredentialConfig() { private void callGcs(GoogleCredentials credentials) throws IOException { String bucketName = System.getenv("GCS_BUCKET"); - if (bucketName == null) { - fail("GCS bucket name not set through GCS_BUCKET env variable."); - } + assertNotNull(bucketName, "GCS bucket name not set through GCS_BUCKET env variable."); String url = "https://storage.googleapis.com/storage/v1/b/" + bucketName; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java index a54f87e65..69e9684e4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java @@ -31,19 +31,19 @@ package com.google.auth.oauth2; -import static org.junit.Assert.*; +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.assertTrue; import java.util.Collections; 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 JwtClaimsTest { @Test - public void testMergeOverwritesFields() { + void testMergeOverwritesFields() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -64,7 +64,7 @@ public void testMergeOverwritesFields() { } @Test - public void testMergeDefaultValues() { + void testMergeDefaultValues() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -80,7 +80,7 @@ public void testMergeDefaultValues() { } @Test - public void testMergeNull() { + void testMergeNull() { JwtClaims claims1 = JwtClaims.newBuilder().build(); JwtClaims claims2 = JwtClaims.newBuilder().build(); JwtClaims merged = claims1.merge(claims2); @@ -93,7 +93,7 @@ public void testMergeNull() { } @Test - public void testEquals() { + void testEquals() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -111,14 +111,14 @@ public void testEquals() { } @Test - public void testAdditionalClaimsDefaults() { + void testAdditionalClaimsDefaults() { JwtClaims claims = JwtClaims.newBuilder().build(); assertNotNull(claims.getAdditionalClaims()); assertTrue(claims.getAdditionalClaims().isEmpty()); } @Test - public void testMergeAdditionalClaims() { + void testMergeAdditionalClaims() { JwtClaims claims1 = JwtClaims.newBuilder().setAdditionalClaims(Collections.singletonMap("foo", "bar")).build(); JwtClaims claims2 = @@ -138,7 +138,7 @@ public void testMergeAdditionalClaims() { } @Test - public void testIsComplete() { + void testIsComplete() { // Test JwtClaim is complete if audience is not set but scope is provided. JwtClaims claims = JwtClaims.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java index 1c934a8f4..7f65c0035 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.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.assertSame; -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.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; @@ -47,12 +47,9 @@ 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; -@RunWith(JUnit4.class) -public class JwtCredentialsTest extends BaseSerializationTest { +class JwtCredentialsTest extends BaseSerializationTest { private static final String PRIVATE_KEY_ID = "d84a4fefcf50791d4a90f2d7af17469d6282df9d"; private static final String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" @@ -80,7 +77,7 @@ static PrivateKey getPrivateKey() { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -102,51 +99,51 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void builder_requiresPrivateKey() { - try { - JwtClaims claims = - JwtClaims.newBuilder() - .setAudience("some-audience") - .setIssuer("some-issuer") - .setSubject("some-subject") - .build(); - JwtCredentials.newBuilder().setJwtClaims(claims).setPrivateKeyId(PRIVATE_KEY_ID).build(); - fail("Should throw exception"); - } catch (NullPointerException ex) { - // expected - } + void builder_requiresPrivateKey() { + assertThrows( + NullPointerException.class, + () -> { + JwtClaims claims = + JwtClaims.newBuilder() + .setAudience("some-audience") + .setIssuer("some-issuer") + .setSubject("some-subject") + .build(); + JwtCredentials.newBuilder().setJwtClaims(claims).setPrivateKeyId(PRIVATE_KEY_ID).build(); + }, + "Should throw exception"); } @Test - public void builder_requiresClaims() { - try { - JwtCredentials.newBuilder() - .setPrivateKeyId(PRIVATE_KEY_ID) - .setPrivateKey(getPrivateKey()) - .build(); - fail("Should throw exception"); - } catch (NullPointerException ex) { - // expected - } + void builder_requiresClaims() { + assertThrows( + NullPointerException.class, + () -> { + JwtCredentials.newBuilder() + .setPrivateKeyId(PRIVATE_KEY_ID) + .setPrivateKey(getPrivateKey()) + .build(); + }, + "Should throw exception"); } @Test - public void builder_requiresCompleteClaims() { - try { - JwtClaims claims = JwtClaims.newBuilder().build(); - JwtCredentials.newBuilder() - .setJwtClaims(claims) - .setPrivateKeyId(PRIVATE_KEY_ID) - .setPrivateKey(getPrivateKey()) - .build(); - fail("Should throw exception"); - } catch (IllegalStateException ex) { - // expected - } + void builder_requiresCompleteClaims() { + assertThrows( + IllegalStateException.class, + () -> { + JwtClaims claims = JwtClaims.newBuilder().build(); + JwtCredentials.newBuilder() + .setJwtClaims(claims) + .setPrivateKeyId(PRIVATE_KEY_ID) + .setPrivateKey(getPrivateKey()) + .build(); + }, + "Should throw exception"); } @Test - public void jwtWithClaims_overwritesClaims() throws IOException { + void jwtWithClaims_overwritesClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -171,7 +168,7 @@ public void jwtWithClaims_overwritesClaims() throws IOException { } @Test - public void jwtWithClaims_defaultsClaims() throws IOException { + void jwtWithClaims_defaultsClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -191,7 +188,7 @@ public void jwtWithClaims_defaultsClaims() throws IOException { } @Test - public void getRequestMetadata_hasJwtAccess() throws IOException { + void getRequestMetadata_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -210,7 +207,7 @@ public void getRequestMetadata_hasJwtAccess() throws IOException { } @Test - public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { + void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -236,7 +233,7 @@ public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOExce } @Test - public void privateKeyIdNull() throws IOException { + void privateKeyIdNull() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -255,7 +252,7 @@ public void privateKeyIdNull() throws IOException { } @Test - public void privateKeyIdNotSpecified() throws IOException { + void privateKeyIdNotSpecified() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -282,7 +279,7 @@ private void verifyJwtAccess( expectedIssuer, expectedSubject, expectedKeyId, - Collections.emptyMap()); + Collections.emptyMap()); } private void verifyJwtAccess( @@ -295,15 +292,15 @@ private void verifyJwtAccess( throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull("Authorization headers not found", authorizations); + assertNotNull(authorizations, "Authorization headers not found"); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull("Multiple bearer assertions found", assertion); + assertNull(assertion, "Multiple bearer assertions found"); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull("Bearer assertion not found", assertion); + assertNotNull(assertion, "Bearer assertion not found"); JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion); assertEquals(expectedIssuer, signature.getPayload().getIssuer()); assertEquals(expectedSubject, signature.getPayload().getSubject()); From 59dfb35a9c3d6d90790c7afbd83991b67a6535ed Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Wed, 13 Oct 2021 17:13:12 +0300 Subject: [PATCH 3/8] chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - fifth iteration (#756) (#767) --- .../com/google/auth/oauth2/MockExecutor.java | 4 +- .../oauth2/MockMetadataServerTransport.java | 2 +- .../auth/oauth2/MockTokenServerTransport.java | 10 +- .../auth/oauth2/OAuth2CredentialsTest.java | 131 ++++---- .../OAuth2CredentialsWithRefreshTest.java | 47 ++- .../auth/oauth2/OAuthExceptionTest.java | 17 +- .../oauth2/ServiceAccountCredentialsTest.java | 282 +++++++++--------- 7 files changed, 226 insertions(+), 267 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java index ce36548e2..3c425e345 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java @@ -36,7 +36,7 @@ /** Mock thread-less executor. */ public final class MockExecutor implements Executor { - private LinkedList tasks = new LinkedList(); + private LinkedList tasks = new LinkedList<>(); @Override public void execute(Runnable task) { @@ -45,7 +45,7 @@ public void execute(Runnable task) { int runTasks() { LinkedList savedTasks = tasks; - tasks = new LinkedList(); + tasks = new LinkedList<>(); for (Runnable task : savedTasks) { task.run(); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java index 07c5b0fb5..b3dd9ca89 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java @@ -166,7 +166,7 @@ public LowLevelHttpResponse execute() throws IOException { } // https://cloud.google.com/compute/docs/instances/verifying-instance-identity#token_format - Map queryPairs = new HashMap(); + Map queryPairs = new HashMap<>(); String query = (new URL(url)).getQuery(); String[] pairs = query.split("&"); for (String pair : pairs) { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java index b07b58f9d..7eea7d462 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java @@ -60,10 +60,10 @@ public class MockTokenServerTransport extends MockHttpTransport { static final String EXPECTED_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; static final JsonFactory JSON_FACTORY = new GsonFactory(); int buildRequestCount; - final Map clients = new HashMap(); - final Map refreshTokens = new HashMap(); - final Map serviceAccounts = new HashMap(); - final Map codes = new HashMap(); + final Map clients = new HashMap<>(); + final Map refreshTokens = new HashMap<>(); + final Map serviceAccounts = new HashMap<>(); + final Map codes = new HashMap<>(); URI tokenServerUri = OAuth2Utils.TOKEN_SERVER_URI; private IOException error; private final Queue> responseSequence = new ArrayDeque<>(); @@ -106,7 +106,7 @@ public void setError(IOException error) { public void addResponseErrorSequence(IOException... errors) { for (IOException error : errors) { - responseSequence.add(Futures.immediateFailedFuture(error)); + responseSequence.add(Futures.immediateFailedFuture(error)); } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java index dcfc77f04..34add0b0c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java @@ -32,14 +32,13 @@ package com.google.auth.oauth2; import static java.util.concurrent.TimeUnit.HOURS; -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.assertThrows; -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.util.Clock; import com.google.auth.TestClock; @@ -69,16 +68,12 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.function.ThrowingRunnable; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Test case for {@link OAuth2Credentials}. */ -@RunWith(JUnit4.class) -public class OAuth2CredentialsTest extends BaseSerializationTest { +class OAuth2CredentialsTest extends BaseSerializationTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -88,25 +83,25 @@ public class OAuth2CredentialsTest extends BaseSerializationTest { private ExecutorService realExecutor; - @Before - public void setUp() { + @BeforeEach + void setUp() { realExecutor = Executors.newCachedThreadPool(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { realExecutor.shutdown(); } @Test - public void constructor_storesAccessToken() { + void constructor_storesAccessToken() { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); - assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); + assertEquals(ACCESS_TOKEN, credentials.getAccessToken().getTokenValue()); } @Test - public void constructor_overrideMargin() throws Throwable { + void constructor_overrideMargin() throws Throwable { Duration staleMargin = Duration.ofMinutes(3); Duration expirationMargin = Duration.ofMinutes(2); @@ -187,18 +182,18 @@ public AccessToken refreshAccessToken() throws IOException { } @Test - public void getAuthenticationType_returnsOAuth2() { + void getAuthenticationType_returnsOAuth2() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .build(); - assertEquals(credentials.getAuthenticationType(), "OAuth2"); + assertEquals("OAuth2", credentials.getAuthenticationType()); } @Test - public void hasRequestMetadata_returnsTrue() { + void hasRequestMetadata_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -209,7 +204,7 @@ public void hasRequestMetadata_returnsTrue() { } @Test - public void hasRequestMetadataOnly_returnsTrue() { + void hasRequestMetadataOnly_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -220,7 +215,7 @@ public void hasRequestMetadataOnly_returnsTrue() { } @Test - public void addChangeListener_notifiesOnRefresh() throws IOException { + void addChangeListener_notifiesOnRefresh() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -258,7 +253,7 @@ public void addChangeListener_notifiesOnRefresh() throws IOException { } @Test - public void removeChangeListener_unregisters_observer() throws IOException { + void removeChangeListener_unregisters_observer() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -295,7 +290,7 @@ public void removeChangeListener_unregisters_observer() throws IOException { } @Test - public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { + void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -333,13 +328,11 @@ public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException clock.addToCurrentTime(60 * 60 * 1000); assertEquals(0, transportFactory.transport.buildRequestCount); - try { - credentials.getRequestMetadata(CALL_URI); - fail("Should throw"); - } catch (IOException e) { - assertSame(error, e); - assertEquals(1, transportFactory.transport.buildRequestCount--); - } + IOException exception = + assertThrows( + IOException.class, () -> credentials.getRequestMetadata(CALL_URI), "Should throw"); + assertSame(error, exception); + assertEquals(1, transportFactory.transport.buildRequestCount--); // Reset the error and try again transportFactory.transport.setError(null); @@ -349,7 +342,7 @@ public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException } @Test - public void getRequestMetadata_async() throws IOException { + void getRequestMetadata_async() { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -419,8 +412,7 @@ public void getRequestMetadata_async() throws IOException { } @Test - public void getRequestMetadata_async_refreshRace() - throws ExecutionException, InterruptedException { + void getRequestMetadata_async_refreshRace() throws ExecutionException, InterruptedException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -478,7 +470,7 @@ public Map> call() throws Exception { } @Test - public void getRequestMetadata_temporaryToken_hasToken() throws IOException { + void getRequestMetadata_temporaryToken_hasToken() throws IOException { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); @@ -488,7 +480,7 @@ public void getRequestMetadata_temporaryToken_hasToken() throws IOException { } @Test - public void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { + void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); @@ -558,7 +550,7 @@ public AccessToken refreshAccessToken() { } @Test - public void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { + void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -627,7 +619,7 @@ public AccessToken refreshAccessToken() { } @Test - public void getRequestMetadata_singleFlightErrorSharing() { + void getRequestMetadata_singleFlightErrorSharing() { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -671,32 +663,17 @@ public Map> call() throws Exception { // Get the error that getRequestMetadata(uri) created Throwable actualBlockingError = - assertThrows( - ExecutionException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - blockingCall.get(); - } - }) - .getCause(); + assertThrows(ExecutionException.class, blockingCall::get).getCause(); assertEquals(error, actualBlockingError); RuntimeException actualAsyncError = - assertThrows( - RuntimeException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - callback1.awaitResult(); - } - }); + assertThrows(RuntimeException.class, callback1::awaitResult); assertEquals(error, actualAsyncError); } @Test - public void getRequestMetadata_syncErrorsIncludeCallingStackframe() { + void getRequestMetadata_syncErrorsIncludeCallingStackframe() { final OAuth2Credentials creds = new OAuth2Credentials() { @Override @@ -726,7 +703,7 @@ public AccessToken refreshAccessToken() { } @Test - public void refresh_refreshesToken() throws IOException { + void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -762,7 +739,7 @@ public void refresh_refreshesToken() throws IOException { } @Test - public void refreshIfExpired_refreshesToken() throws IOException { + void refreshIfExpired_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -805,15 +782,21 @@ public void refreshIfExpired_refreshesToken() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test(expected = IllegalStateException.class) - public void refresh_temporaryToken_throws() throws IOException { - OAuth2Credentials credentials = - OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); - credentials.refresh(); + @Test + void refresh_temporaryToken_throws() { + assertThrows( + IllegalStateException.class, + () -> { + OAuth2Credentials credentials = + OAuth2Credentials.newBuilder() + .setAccessToken(new AccessToken(ACCESS_TOKEN, null)) + .build(); + credentials.refresh(); + }); } @Test - public void equals_true() throws IOException { + void equals_true() { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken1, null)).build(); @@ -824,7 +807,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_accessToken() throws IOException { + void equals_false_accessToken() { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = @@ -836,7 +819,7 @@ public void equals_false_accessToken() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() { AccessToken accessToken = new AccessToken("1/MkSJoj1xsli0AccessToken_NKPY2", null); OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); @@ -851,7 +834,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -861,7 +844,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java index 2acd41ed9..f9a41eec9 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -31,23 +31,20 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; 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; /** Tests for {@link OAuth2CredentialsWithRefresh}. */ -@RunWith(JUnit4.class) -public class OAuth2CredentialsWithRefreshTest { +class OAuth2CredentialsWithRefreshTest { private static final AccessToken ACCESS_TOKEN = new AccessToken("accessToken", new Date()); @Test - public void builder() { + void builder() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -66,7 +63,7 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_noAccessToken() { + void builder_noAccessToken() { OAuth2CredentialsWithRefresh.newBuilder() .setRefreshHandler( new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @@ -79,29 +76,27 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_noRefreshHandler_throws() { - try { - OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(); - fail("Should fail as a refresh handler must be provided."); - } catch (NullPointerException e) { - // Expected. - } + void builder_noRefreshHandler_throws() { + assertThrows( + NullPointerException.class, + () -> OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(), + "Should fail as a refresh handler must be provided."); } @Test - public void builder_noExpirationTimeInAccessToken_throws() { - try { - OAuth2CredentialsWithRefresh.newBuilder() - .setAccessToken(new AccessToken("accessToken", null)) - .build(); - fail("Should fail as a refresh handler must be provided."); - } catch (IllegalArgumentException e) { - // Expected. - } + void builder_noExpirationTimeInAccessToken_throws() { + assertThrows( + IllegalArgumentException.class, + () -> { + OAuth2CredentialsWithRefresh.newBuilder() + .setAccessToken(new AccessToken("accessToken", null)) + .build(); + }, + "Should fail as a refresh handler must be provided."); } @Test - public void refreshAccessToken_delegateToRefreshHandler() throws IOException { + void refreshAccessToken_delegateToRefreshHandler() throws IOException { final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = OAuth2CredentialsWithRefresh.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java index f864f4791..67f3ba82b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java @@ -31,23 +31,20 @@ 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 org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link OAuthException}. */ -@RunWith(JUnit4.class) -public final class OAuthExceptionTest { +class OAuthExceptionTest { private static final String FULL_MESSAGE_FORMAT = "Error code %s: %s - %s"; private static final String ERROR_DESCRIPTION_FORMAT = "Error code %s: %s"; private static final String BASE_MESSAGE_FORMAT = "Error code %s"; @Test - public void getMessage_fullFormat() { + void getMessage_fullFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", "errorUri"); assertEquals("errorCode", e.getErrorCode()); @@ -60,7 +57,7 @@ public void getMessage_fullFormat() { } @Test - public void getMessage_descriptionFormat() { + void getMessage_descriptionFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", /* errorUri= */ null); assertEquals("errorCode", e.getErrorCode()); @@ -73,7 +70,7 @@ public void getMessage_descriptionFormat() { } @Test - public void getMessage_baseFormat() { + void getMessage_baseFormat() { OAuthException e = new OAuthException("errorCode", /* errorDescription= */ null, /* errorUri= */ null); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 1e0be6b3f..476bfbd5a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -31,15 +31,17 @@ 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.assertNotEquals; -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.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -49,7 +51,6 @@ import com.google.api.client.testing.http.FixedClock; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Clock; -import com.google.api.client.util.Joiner; import com.google.auth.RequestMetadataCallback; import com.google.auth.TestUtils; import com.google.auth.http.AuthHttpConstants; @@ -72,13 +73,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ -@RunWith(JUnit4.class) -public class ServiceAccountCredentialsTest extends BaseSerializationTest { +class ServiceAccountCredentialsTest extends BaseSerializationTest { private static final String CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -133,7 +131,7 @@ private ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcept } @Test - public void setLifetime() throws IOException { + void setLifetime() throws IOException { ServiceAccountCredentials.Builder builder = createDefaultBuilder(); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.getLifetime()); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); @@ -147,27 +145,27 @@ public void setLifetime() throws IOException { } @Test - public void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { - try { - createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(); - 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")); - } + void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(), + 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 createWithCustomLifetime() throws IOException { + void createWithCustomLifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); credentials = credentials.createWithCustomLifetime(4000); assertEquals(4000, credentials.getLifetime()); } @Test - public void createdScoped_clones() throws IOException { + void createdScoped_clones() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -197,7 +195,7 @@ public void createdScoped_clones() throws IOException { } @Test - public void createdDelegated_clones() throws IOException { + void createdDelegated_clones() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -228,7 +226,7 @@ public void createdDelegated_clones() throws IOException { } @Test - public void createAssertion_correct() throws IOException { + void createAssertion_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = @@ -253,11 +251,11 @@ public void createAssertion_correct() throws IOException { assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(USER, payload.getSubject()); - assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); + assertEquals(String.join(" ", scopes), payload.get("scope")); } @Test - public void createAssertion_defaultScopes_correct() throws IOException { + void createAssertion_defaultScopes_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = @@ -283,11 +281,11 @@ public void createAssertion_defaultScopes_correct() throws IOException { assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(USER, payload.getSubject()); - assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); + assertEquals(String.join(" ", scopes), payload.get("scope")); } @Test - public void createAssertion_custom_lifetime() throws IOException { + void createAssertion_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -300,7 +298,7 @@ public void createAssertion_custom_lifetime() throws IOException { } @Test - public void createAssertionForIdToken_correct() throws IOException { + void createAssertionForIdToken_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = @@ -329,7 +327,7 @@ public void createAssertionForIdToken_correct() throws IOException { } @Test - public void createAssertionForIdToken_custom_lifetime() throws IOException { + void createAssertionForIdToken_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); @@ -345,7 +343,7 @@ public void createAssertionForIdToken_custom_lifetime() throws IOException { } @Test - public void createAssertionForIdToken_incorrect() throws IOException { + void createAssertionForIdToken_incorrect() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = @@ -375,7 +373,7 @@ public void createAssertionForIdToken_incorrect() throws IOException { } @Test - public void createAssertion_withTokenUri_correct() throws IOException { + void createAssertion_withTokenUri_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = @@ -401,11 +399,11 @@ public void createAssertion_withTokenUri_correct() throws IOException { assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(USER, payload.getSubject()); - assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); + assertEquals(String.join(" ", scopes), payload.get("scope")); } @Test - public void createdScoped_enablesAccessTokens() throws IOException { + void createdScoped_enablesAccessTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GoogleCredentials credentials = @@ -418,14 +416,13 @@ public void createdScoped_enablesAccessTokens() throws IOException { transportFactory, null); - try { - credentials.getRequestMetadata(null); - fail("Should not be able to get token without scopes"); - } catch (IOException e) { - assertTrue( - "expected to fail with exception", - e.getMessage().contains("Scopes and uri are not configured for service account")); - } + IOException exception = + assertThrows( + IOException.class, + () -> credentials.getRequestMetadata(null), + "Should not be able to get token without scopes"); + assertTrue( + exception.getMessage().contains("Scopes and uri are not configured for service account")); GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); Map> metadata = scopedCredentials.getRequestMetadata(CALL_URI); @@ -433,7 +430,7 @@ public void createdScoped_enablesAccessTokens() throws IOException { } @Test - public void createdScoped_defaultScopes() throws IOException { + void createdScoped_defaultScopes() throws IOException { final URI TOKEN_SERVER = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -474,7 +471,7 @@ public void createdScoped_defaultScopes() throws IOException { } @Test - public void createScopedRequired_emptyScopes() throws IOException { + void createScopedRequired_emptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, EMPTY_SCOPES); @@ -483,7 +480,7 @@ public void createScopedRequired_emptyScopes() throws IOException { } @Test - public void createScopedRequired_nonEmptyScopes() throws IOException { + void createScopedRequired_nonEmptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, SCOPES); @@ -492,7 +489,7 @@ public void createScopedRequired_nonEmptyScopes() throws IOException { } @Test - public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { + void createScopedRequired_nonEmptyDefaultScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null, SCOPES); @@ -501,7 +498,7 @@ public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { } @Test - public void fromJSON_getProjectId() throws IOException { + void fromJSON_getProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -514,7 +511,7 @@ public void fromJSON_getProjectId() throws IOException { } @Test - public void fromJSON_getProjectIdNull() throws IOException { + void fromJSON_getProjectIdNull() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -527,7 +524,7 @@ public void fromJSON_getProjectIdNull() throws IOException { } @Test - public void fromJSON_hasAccessToken() throws IOException { + void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -542,7 +539,7 @@ public void fromJSON_hasAccessToken() throws IOException { } @Test - public void fromJSON_tokenServerUri() throws IOException { + void fromJSON_tokenServerUri() throws IOException { final String tokenServerUri = "https://foo.com/bar"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -556,7 +553,7 @@ public void fromJSON_tokenServerUri() throws IOException { } @Test - public void fromJson_hasQuotaProjectId() throws IOException { + void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -573,7 +570,7 @@ public void fromJson_hasQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + void getRequestMetadata_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); OAuth2Credentials credentials = @@ -592,7 +589,7 @@ public void getRequestMetadata_hasAccessToken() throws IOException { } @Test - public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { final URI TOKEN_SERVER = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -613,7 +610,7 @@ public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOExcep } @Test - public void refreshAccessToken_refreshesToken() throws IOException { + void refreshAccessToken_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -637,7 +634,7 @@ public void refreshAccessToken_refreshesToken() throws IOException { } @Test - public void refreshAccessToken_tokenExpiry() throws IOException { + void refreshAccessToken_tokenExpiry() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -665,7 +662,7 @@ public void refreshAccessToken_tokenExpiry() throws IOException { } @Test - public void refreshAccessToken_retriesIOException() throws IOException { + void refreshAccessToken_retriesIOException() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -690,7 +687,7 @@ public void refreshAccessToken_retriesIOException() throws IOException { } @Test - public void refreshAccessToken_retriesForbiddenError() throws IOException { + void refreshAccessToken_retriesForbiddenError() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -715,7 +712,7 @@ public void refreshAccessToken_retriesForbiddenError() throws IOException { } @Test - public void refreshAccessToken_retriesServerError() throws IOException { + void refreshAccessToken_retriesServerError() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -740,7 +737,7 @@ public void refreshAccessToken_retriesServerError() throws IOException { } @Test - public void refreshAccessToken_failsNotFoundError() throws IOException { + void refreshAccessToken_failsNotFoundError() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -758,18 +755,18 @@ public void refreshAccessToken_failsNotFoundError() throws IOException { transport.addServiceAccount(CLIENT_EMAIL, accessToken1); TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken1); - try { - transport.addResponseSequence(new MockLowLevelHttpResponse().setStatusCode(404)); - transport.addServiceAccount(CLIENT_EMAIL, accessToken2); - credentials.refresh(); - fail("Should not retry on Not Found"); - } catch (IOException expected) { - // Expected - } + assertThrows( + IOException.class, + () -> { + transport.addResponseSequence(new MockLowLevelHttpResponse().setStatusCode(404)); + transport.addServiceAccount(CLIENT_EMAIL, accessToken2); + credentials.refresh(); + }, + "Should not retry on Not Found"); } @Test - public void idTokenWithAudience_correct() throws IOException { + void idTokenWithAudience_correct() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -801,7 +798,7 @@ public void idTokenWithAudience_correct() throws IOException { } @Test - public void idTokenWithAudience_incorrect() throws IOException { + void idTokenWithAudience_incorrect() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -831,7 +828,7 @@ public void idTokenWithAudience_incorrect() throws IOException { } @Test - public void getScopes_nullReturnsEmpty() throws IOException { + void getScopes_nullReturnsEmpty() throws IOException { ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null); @@ -843,7 +840,7 @@ public void getScopes_nullReturnsEmpty() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null); @@ -851,7 +848,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void sign_sameAs() + void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] toSign = {0xD, 0xE, 0xA, 0xD}; ServiceAccountCredentials credentials = @@ -865,7 +862,7 @@ public void sign_sameAs() } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -891,7 +888,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_clientId() throws IOException { + void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -917,7 +914,7 @@ public void equals_false_clientId() throws IOException { } @Test - public void equals_false_email() throws IOException { + void equals_false_email() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -943,7 +940,7 @@ public void equals_false_email() throws IOException { } @Test - public void equals_false_keyId() throws IOException { + void equals_false_keyId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -969,7 +966,7 @@ public void equals_false_keyId() throws IOException { } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -987,7 +984,7 @@ public void equals_false_scopes() throws IOException { CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, - ImmutableSet.of(), + ImmutableSet.of(), serverTransportFactory, tokenServer1); assertFalse(credentials.equals(otherCredentials)); @@ -995,7 +992,7 @@ public void equals_false_scopes() throws IOException { } @Test - public void equals_false_transportFactory() throws IOException { + void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1022,7 +1019,7 @@ public void equals_false_transportFactory() throws IOException { } @Test - public void equals_false_tokenServer() throws IOException { + void equals_false_tokenServer() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); final URI tokenServer2 = URI.create("https://foo2.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1049,7 +1046,7 @@ public void equals_false_tokenServer() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1083,7 +1080,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1108,7 +1105,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -1131,29 +1128,25 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); - try { - ServiceAccountCredentials.fromStream(stream, null); - fail("Should throw if HttpTransportFactory is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> ServiceAccountCredentials.fromStream(stream, null), + "Should throw if HttpTransportFactory is null"); } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - try { - ServiceAccountCredentials.fromStream(null, transportFactory); - fail("Should throw if InputStream is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> ServiceAccountCredentials.fromStream(null, transportFactory), + "Should throw if InputStream is null"); } @Test - public void fromStream_providesToken() throws IOException { + void fromStream_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -1169,7 +1162,7 @@ public void fromStream_providesToken() throws IOException { } @Test - public void fromStream_noClientId_throws() throws IOException { + void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(null, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); @@ -1177,7 +1170,7 @@ public void fromStream_noClientId_throws() throws IOException { } @Test - public void fromStream_noClientEmail_throws() throws IOException { + void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, null, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); @@ -1185,7 +1178,7 @@ public void fromStream_noClientEmail_throws() throws IOException { } @Test - public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { + void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.setError(new IOException("Invalid grant: Account not found")); @@ -1208,15 +1201,12 @@ public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOExcep String expectedErrorMessage = String.format("iss: %s", CLIENT_EMAIL); - try { - tokenCredential.refresh(); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains(expectedErrorMessage)); - } + IOException exception = assertThrows(IOException.class, tokenCredential::refresh); + assertTrue(exception.getMessage().contains(expectedErrorMessage)); } @Test - public void fromStream_noPrivateKey_throws() throws IOException { + void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, null, PRIVATE_KEY_ID); @@ -1224,7 +1214,7 @@ public void fromStream_noPrivateKey_throws() throws IOException { } @Test - public void fromStream_noPrivateKeyId_throws() throws IOException { + void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, null); @@ -1232,7 +1222,7 @@ public void fromStream_noPrivateKeyId_throws() throws IOException { } @Test - public void getUriForSelfSignedJWT() { + void getUriForSelfSignedJWT() { assertNull(ServiceAccountCredentials.getUriForSelfSignedJWT(null)); URI uri = URI.create("https://compute.googleapis.com/compute/v1/projects/"); @@ -1241,21 +1231,21 @@ public void getUriForSelfSignedJWT() { } @Test - public void getUriForSelfSignedJWT_noHost() { + void getUriForSelfSignedJWT_noHost() { URI uri = URI.create("file:foo"); URI expected = URI.create("file:foo"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } @Test - public void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { + void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { URI uri = URI.create("compute.googleapis.com"); URI expected = URI.create("compute.googleapis.com"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1282,7 +1272,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1305,7 +1295,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataWithCallback() throws IOException { + void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1342,11 +1332,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { + void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1365,7 +1355,7 @@ public void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { } @Test - public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { + void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1388,12 +1378,10 @@ public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() thr 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 - } + assertThrows( + Exception.class, + () -> verifyJwtAccess(metadata, "dummy.scope"), + "jwt access should fail with ServiceAccountUser"); transport.addServiceAccount(CLIENT_EMAIL, accessToken2); credentials.refresh(); @@ -1401,7 +1389,7 @@ public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() thr } @Test - public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { + void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1418,7 +1406,7 @@ public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { } @Test - public void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOException { + void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1437,7 +1425,7 @@ public void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOExcept } @Test - public void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { + void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1459,11 +1447,8 @@ public void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { new RequestMetadataCallback() { @Override public void onSuccess(Map> metadata) { - try { - verifyJwtAccess(metadata, "dummy.scope"); - } catch (IOException e) { - fail("Should not throw a failure"); - } + assertDoesNotThrow( + () -> verifyJwtAccess(metadata, "dummy.scope"), "Should not throw a failure"); success.set(true); } @@ -1473,22 +1458,22 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } private void verifyJwtAccess(Map> metadata, String expectedScopeClaim) throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull("Authorization headers not found", authorizations); + assertNotNull(authorizations, "Authorization headers not found"); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull("Multiple bearer assertions found", assertion); + assertNull(assertion, "Multiple bearer assertions found"); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull("Bearer assertion not found", assertion); + assertNotNull(assertion, "Bearer assertion not found"); JsonWebSignature signature = JsonWebSignature.parse(GsonFactory.getDefaultInstance(), assertion); assertEquals(CLIENT_EMAIL, signature.getPayload().getIssuer()); @@ -1542,13 +1527,12 @@ static InputStream writeServiceAccountStream( } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - try { - ServiceAccountCredentials.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, + () -> ServiceAccountCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY), + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + assertTrue(exception.getMessage().contains(expectedMessageContent)); } } From 928dd04fc72eb8ae5617da2d73ce771a01883f3a Mon Sep 17 00:00:00 2001 From: Andrei Arlou Date: Wed, 13 Oct 2021 23:16:18 +0300 Subject: [PATCH 4/8] chore: migrate tests in oauth2_http module from JUnit4 to JUnit5 - sixth iteration (#756) (#769) --- .../javatests/com/google/auth/TestUtils.java | 28 +-- ...ckExternalAccountCredentialsTransport.java | 6 +- .../google/auth/oauth2/MockStsTransport.java | 4 +- ...erviceAccountJwtAccessCredentialsTest.java | 212 +++++++++--------- .../auth/oauth2/StsRequestHandlerTest.java | 76 ++----- .../google/auth/oauth2/TokenVerifierTest.java | 99 ++++---- .../auth/oauth2/UserAuthorizerTest.java | 90 ++++---- .../auth/oauth2/UserCredentialsTest.java | 154 ++++++------- oauth2_http/pom.xml | 5 - pom.xml | 7 - 10 files changed, 303 insertions(+), 378 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/TestUtils.java b/oauth2_http/javatests/com/google/auth/TestUtils.java index b9c2b6d75..d2218092e 100644 --- a/oauth2_http/javatests/com/google/auth/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/TestUtils.java @@ -31,8 +31,9 @@ package com.google.auth; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponseException; @@ -45,8 +46,8 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @@ -63,40 +64,31 @@ public class TestUtils { public static void assertContainsBearerToken(Map> metadata, String token) { assertNotNull(metadata); assertNotNull(token); - assertTrue("Bearer token not found", hasBearerToken(metadata, token)); + assertTrue(hasBearerToken(metadata, token), "Bearer token not found"); } public static void assertNotContainsBearerToken( Map> metadata, String token) { assertNotNull(metadata); assertNotNull(token); - assertTrue("Bearer token found", !hasBearerToken(metadata, token)); + assertFalse(hasBearerToken(metadata, token), "Bearer token found"); } private static boolean hasBearerToken(Map> metadata, String token) { String expectedValue = AuthHttpConstants.BEARER + " " + token; List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull("Authorization headers not found", authorizations); - for (String authorization : authorizations) { - if (expectedValue.equals(authorization)) { - return true; - } - } - return false; + assertNotNull(authorizations, "Authorization headers not found"); + return authorizations.contains(expectedValue); } public static InputStream jsonToInputStream(GenericJson json) throws IOException { json.setFactory(JSON_FACTORY); String text = json.toPrettyString(); - return new ByteArrayInputStream(text.getBytes("UTF-8")); + return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); } public static InputStream stringToInputStream(String text) { - try { - return new ByteArrayInputStream(text.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Unexpected encoding exception", e); - } + return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); } public static Map parseQuery(String query) throws IOException { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java index 108900705..7e07146cc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.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.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java index 1695c8450..527532170 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java @@ -31,8 +31,8 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.LowLevelHttpRequest; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index 5020317f2..3a0249142 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -31,15 +31,16 @@ 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.assertNotEquals; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; @@ -63,13 +64,10 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ -@RunWith(JUnit4.class) -public class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { +class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { private static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -96,7 +94,7 @@ public class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTes private static final String QUOTA_PROJECT = "sample-quota-project-id"; @Test - public void constructor_allParameters_constructs() throws IOException { + void constructor_allParameters_constructs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -115,7 +113,7 @@ public void constructor_allParameters_constructs() throws IOException { } @Test - public void constructor_noClientId_constructs() throws IOException { + void constructor_noClientId_constructs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) @@ -125,7 +123,7 @@ public void constructor_noClientId_constructs() throws IOException { } @Test - public void constructor_noPrivateKeyId_constructs() throws IOException { + void constructor_noPrivateKeyId_constructs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -135,36 +133,36 @@ public void constructor_noPrivateKeyId_constructs() throws IOException { } @Test - public void constructor_noEmail_throws() throws IOException { + void constructor_noEmail_throws() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); - try { - ServiceAccountJwtAccessCredentials.newBuilder() - .setClientId(SA_CLIENT_ID) - .setPrivateKey(privateKey) - .setPrivateKeyId(SA_PRIVATE_KEY_ID) - .build(); - fail("exception expected"); - } catch (NullPointerException e) { - // Expected - } - } - - @Test - public void constructor_noPrivateKey_throws() { - try { - ServiceAccountJwtAccessCredentials.newBuilder() - .setClientId(SA_CLIENT_ID) - .setClientEmail(SA_CLIENT_EMAIL) - .setPrivateKeyId(SA_PRIVATE_KEY_ID) - .build(); - fail("exception expected"); - } catch (NullPointerException e) { - // Expected - } - } - - @Test - public void getAuthenticationType_returnsJwtAccess() throws IOException { + assertThrows( + NullPointerException.class, + () -> { + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .build(); + }, + "exception expected"); + } + + @Test + void constructor_noPrivateKey_throws() { + assertThrows( + NullPointerException.class, + () -> { + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .build(); + }, + "exception expected"); + } + + @Test + void getAuthenticationType_returnsJwtAccess() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -172,7 +170,7 @@ public void getAuthenticationType_returnsJwtAccess() throws IOException { } @Test - public void hasRequestMetadata_returnsTrue() throws IOException { + void hasRequestMetadata_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -180,7 +178,7 @@ public void hasRequestMetadata_returnsTrue() throws IOException { } @Test - public void hasRequestMetadataOnly_returnsTrue() throws IOException { + void hasRequestMetadataOnly_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -188,7 +186,7 @@ public void hasRequestMetadataOnly_returnsTrue() throws IOException { } @Test - public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { + void getRequestMetadata_blocking_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -204,7 +202,7 @@ public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { } @Test - public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { + void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -221,7 +219,7 @@ public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOExcep } @Test - public void getRequestMetadata_blocking_noURI_throws() throws IOException { + void getRequestMetadata_blocking_noURI_throws() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -231,16 +229,11 @@ public void getRequestMetadata_blocking_noURI_throws() throws IOException { .setPrivateKeyId(SA_PRIVATE_KEY_ID) .build(); - try { - credentials.getRequestMetadata(); - fail("exception expected"); - } catch (IOException e) { - // Expected - } + assertThrows(IOException.class, credentials::getRequestMetadata, "exception expected"); } @Test - public void getRequestMetadata_blocking_cached() throws IOException { + void getRequestMetadata_blocking_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -265,7 +258,7 @@ public void getRequestMetadata_blocking_cached() throws IOException { } @Test - public void getRequestMetadata_blocking_cache_expired() throws IOException { + void getRequestMetadata_blocking_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -290,7 +283,7 @@ public void getRequestMetadata_blocking_cache_expired() throws IOException { } @Test - public void getRequestMetadata_async_hasJwtAccess() throws IOException { + void getRequestMetadata_async_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -309,7 +302,7 @@ public void getRequestMetadata_async_hasJwtAccess() throws IOException { } @Test - public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { + void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -329,7 +322,7 @@ public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOExceptio } @Test - public void getRequestMetadata_async_noURI_exception() throws IOException { + void getRequestMetadata_async_noURI_exception() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -347,7 +340,7 @@ public void getRequestMetadata_async_noURI_exception() throws IOException { } @Test - public void getRequestMetadata_async_cache_expired() throws IOException { + void getRequestMetadata_async_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -375,7 +368,7 @@ public void getRequestMetadata_async_cache_expired() throws IOException { } @Test - public void getRequestMetadata_async_cached() throws IOException { + void getRequestMetadata_async_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -403,7 +396,7 @@ public void getRequestMetadata_async_cached() throws IOException { } @Test - public void getRequestMetadata_contains_quotaProjectId() throws IOException { + void getRequestMetadata_contains_quotaProjectId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -423,7 +416,7 @@ public void getRequestMetadata_contains_quotaProjectId() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -436,7 +429,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void sign_sameAs() + void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); byte[] toSign = {0xD, 0xE, 0xA, 0xD}; @@ -455,7 +448,7 @@ public void sign_sameAs() } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -478,7 +471,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_clientId() throws IOException { + void equals_false_clientId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -501,7 +494,7 @@ public void equals_false_clientId() throws IOException { } @Test - public void equals_false_email() throws IOException { + void equals_false_email() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -524,7 +517,7 @@ public void equals_false_email() throws IOException { } @Test - public void equals_false_keyId() throws IOException { + void equals_false_keyId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -547,7 +540,7 @@ public void equals_false_keyId() throws IOException { } @Test - public void equals_false_callUri() throws IOException { + void equals_false_callUri() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); final URI otherCallUri = URI.create("https://foo.com/bar"); ServiceAccountJwtAccessCredentials credentials = @@ -571,7 +564,7 @@ public void equals_false_callUri() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -591,7 +584,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -613,7 +606,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -634,18 +627,16 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - try { - ServiceAccountCredentials.fromStream(null, transportFactory); - fail("Should throw if InputStream is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> ServiceAccountCredentials.fromStream(null, transportFactory), + "Should throw if InputStream is null"); } @Test - public void fromStream_hasJwtAccess() throws IOException { + void fromStream_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -658,7 +649,7 @@ public void fromStream_hasJwtAccess() throws IOException { } @Test - public void fromStream_defaultURI_hasJwtAccess() throws IOException { + void fromStream_defaultURI_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -672,7 +663,7 @@ public void fromStream_defaultURI_hasJwtAccess() throws IOException { } @Test - public void fromStream_noClientId_throws() throws IOException { + void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -681,7 +672,7 @@ public void fromStream_noClientId_throws() throws IOException { } @Test - public void fromStream_noClientEmail_throws() throws IOException { + void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -690,7 +681,7 @@ public void fromStream_noClientEmail_throws() throws IOException { } @Test - public void fromStream_noPrivateKey_throws() throws IOException { + void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -699,7 +690,7 @@ public void fromStream_noPrivateKey_throws() throws IOException { } @Test - public void fromStream_noPrivateKeyId_throws() throws IOException { + void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -708,7 +699,7 @@ public void fromStream_noPrivateKeyId_throws() throws IOException { } @Test - public void jwtWithClaims_overrideAudience() throws IOException { + void jwtWithClaims_overrideAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -726,7 +717,7 @@ public void jwtWithClaims_overrideAudience() throws IOException { } @Test - public void jwtWithClaims_noAudience() throws IOException { + void jwtWithClaims_noAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -735,16 +726,14 @@ public void jwtWithClaims_noAudience() throws IOException { .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .build(); - try { - credentials.jwtWithClaims(JwtClaims.newBuilder().build()); - fail("Expected to throw exception for missing audience"); - } catch (IllegalStateException ex) { - // expected exception - } + assertThrows( + IllegalStateException.class, + () -> credentials.jwtWithClaims(JwtClaims.newBuilder().build()), + "Expected to throw exception for missing audience"); } @Test - public void jwtWithClaims_defaultAudience() throws IOException { + void jwtWithClaims_defaultAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -761,7 +750,7 @@ public void jwtWithClaims_defaultAudience() throws IOException { } @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + void getRequestMetadataSetsQuotaProjectId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -781,7 +770,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + void getRequestMetadataNoQuotaProjectId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -797,7 +786,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataWithCallback() throws IOException { + void getRequestMetadataWithCallback() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -827,7 +816,7 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } private void verifyJwtAccess( @@ -838,15 +827,15 @@ private void verifyJwtAccess( throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull("Authorization headers not found", authorizations); + assertNotNull(authorizations, "Authorization headers not found"); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull("Multiple bearer assertions found", assertion); + assertNull(assertion, "Multiple bearer assertions found"); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull("Bearer assertion not found", assertion); + assertNotNull(assertion, "Bearer assertion not found"); JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion); assertEquals(expectedEmail, signature.getPayload().getIssuer()); assertEquals(expectedEmail, signature.getPayload().getSubject()); @@ -855,13 +844,12 @@ private void verifyJwtAccess( } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - try { - ServiceAccountJwtAccessCredentials.fromStream(stream, CALL_URI); - fail( - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains(expectedMessageContent)); - } + IOException exception = + assertThrows( + IOException.class, + () -> ServiceAccountJwtAccessCredentials.fromStream(stream, CALL_URI), + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + assertTrue(exception.getMessage().contains(expectedMessageContent)); } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java index dd0cc7ce9..324eede9f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +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.http.HttpHeaders; import com.google.api.client.testing.http.MockLowLevelHttpRequest; @@ -44,15 +44,11 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.function.ThrowingRunnable; -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 StsRequestHandler}. */ -@RunWith(JUnit4.class) -public final class StsRequestHandlerTest { +class StsRequestHandlerTest { private static final String TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; @@ -64,13 +60,13 @@ public final class StsRequestHandlerTest { private MockStsTransport transport; - @Before + @BeforeEach public void setup() { transport = new MockStsTransport(); } @Test - public void exchangeToken() throws IOException { + void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType") .setScopes(Arrays.asList(CLOUD_PLATFORM_SCOPE)) @@ -104,7 +100,7 @@ public void exchangeToken() throws IOException { } @Test - public void exchangeToken_withOptionalParams() throws IOException { + void exchangeToken_withOptionalParams() throws IOException { // Return optional params scope and the refresh_token. transport.addScopeSequence(Arrays.asList("scope1", "scope2", "scope3")); transport.addRefreshTokenSequence("refreshToken"); @@ -168,7 +164,7 @@ public void exchangeToken_withOptionalParams() throws IOException { } @Test - public void exchangeToken_throwsException() throws IOException { + void exchangeToken_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -181,23 +177,15 @@ public void exchangeToken_throwsException() throws IOException { TestUtils.buildHttpResponseException( "invalidRequest", /* errorDescription= */ null, /* errorUri= */ null)); - OAuthException e = - assertThrows( - OAuthException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); - - assertEquals("invalidRequest", e.getErrorCode()); - assertNull(e.getErrorDescription()); - assertNull(e.getErrorUri()); + OAuthException exception = assertThrows(OAuthException.class, requestHandler::exchangeToken); + + assertEquals("invalidRequest", exception.getErrorCode()); + assertNull(exception.getErrorDescription()); + assertNull(exception.getErrorUri()); } @Test - public void exchangeToken_withOptionalParams_throwsException() throws IOException { + void exchangeToken_withOptionalParams_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -209,23 +197,15 @@ public void exchangeToken_withOptionalParams_throwsException() throws IOExceptio transport.addResponseErrorSequence( TestUtils.buildHttpResponseException("invalidRequest", "errorDescription", "errorUri")); - OAuthException e = - assertThrows( - OAuthException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); - - assertEquals("invalidRequest", e.getErrorCode()); - assertEquals("errorDescription", e.getErrorDescription()); - assertEquals("errorUri", e.getErrorUri()); + OAuthException exception = assertThrows(OAuthException.class, requestHandler::exchangeToken); + + assertEquals("invalidRequest", exception.getErrorCode()); + assertEquals("errorDescription", exception.getErrorDescription()); + assertEquals("errorUri", exception.getErrorUri()); } @Test - public void exchangeToken_ioException() { + void exchangeToken_ioException() { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -237,20 +217,12 @@ public void exchangeToken_ioException() { IOException e = new IOException(); transport.addResponseErrorSequence(e); - IOException thrownException = - assertThrows( - IOException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + IOException thrownException = assertThrows(IOException.class, requestHandler::exchangeToken); assertEquals(e, thrownException); } @Test - public void exchangeToken_noExpiresInReturned() throws IOException { + void exchangeToken_noExpiresInReturned() throws IOException { // Don't return expires in. This happens in the CAB flow when the subject token does not belong // to a service account. transport.setReturnExpiresIn(/* returnExpiresIn= */ false); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index e779828ff..6c6373267 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java @@ -30,10 +30,10 @@ */ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -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.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.http.LowLevelHttpRequest; @@ -50,12 +50,9 @@ import java.io.Reader; import java.util.Arrays; import java.util.List; -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 TokenVerifierTest { +class TokenVerifierTest { private static final String ES256_TOKEN = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im1wZjBEQSJ9.eyJhdWQiOiIvcHJvamVjdHMvNjUyNTYyNzc2Nzk4L2FwcHMvY2xvdWQtc2FtcGxlcy10ZXN0cy1waHAtaWFwIiwiZW1haWwiOiJjaGluZ29yQGdvb2dsZS5jb20iLCJleHAiOjE1ODQwNDc2MTcsImdvb2dsZSI6eyJhY2Nlc3NfbGV2ZWxzIjpbImFjY2Vzc1BvbGljaWVzLzUxODU1MTI4MDkyNC9hY2Nlc3NMZXZlbHMvcmVjZW50U2VjdXJlQ29ubmVjdERhdGEiLCJhY2Nlc3NQb2xpY2llcy81MTg1NTEyODA5MjQvYWNjZXNzTGV2ZWxzL3Rlc3ROb09wIiwiYWNjZXNzUG9saWNpZXMvNTE4NTUxMjgwOTI0L2FjY2Vzc0xldmVscy9ldmFwb3JhdGlvblFhRGF0YUZ1bGx5VHJ1c3RlZCJdfSwiaGQiOiJnb29nbGUuY29tIiwiaWF0IjoxNTg0MDQ3MDE3LCJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwic3ViIjoiYWNjb3VudHMuZ29vZ2xlLmNvbToxMTIxODE3MTI3NzEyMDE5NzI4OTEifQ.yKNtdFY5EKkRboYNexBdfugzLhC3VuGyFcuFYA8kgpxMqfyxa41zkML68hYKrWu2kOBTUW95UnbGpsIi_u1fiA"; @@ -73,56 +70,50 @@ public class TokenVerifierTest { Arrays.asList(ES256_TOKEN, FEDERATED_SIGNON_RS256_TOKEN, SERVICE_ACCOUNT_RS256_TOKEN); // Fixed to 2020-02-26 08:00:00 to allow expiration tests to pass - private static final Clock FIXED_CLOCK = - new Clock() { - @Override - public long currentTimeMillis() { - return 1582704000000L; - } - }; + private static final Clock FIXED_CLOCK = () -> 1582704000000L; @Test - public void verifyExpiredToken() { + void verifyExpiredToken() { for (String token : ALL_TOKENS) { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build(); - try { - tokenVerifier.verify(token); - fail("Should have thrown a VerificationException"); - } catch (TokenVerifier.VerificationException e) { - assertTrue(e.getMessage().contains("expired")); - } + TokenVerifier.VerificationException exception = + assertThrows( + TokenVerifier.VerificationException.class, + () -> tokenVerifier.verify(token), + "Should have thrown a VerificationException"); + assertTrue(exception.getMessage().contains("expired")); } } @Test - public void verifyExpectedAudience() { + void verifyExpectedAudience() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setAudience("expected audience").build(); for (String token : ALL_TOKENS) { - try { - tokenVerifier.verify(token); - fail("Should have thrown a VerificationException"); - } catch (TokenVerifier.VerificationException e) { - assertTrue(e.getMessage().contains("audience does not match")); - } + TokenVerifier.VerificationException exception = + assertThrows( + TokenVerifier.VerificationException.class, + () -> tokenVerifier.verify(token), + "Should have thrown a VerificationException"); + assertTrue(exception.getMessage().contains("audience does not match")); } } @Test - public void verifyExpectedIssuer() { + void verifyExpectedIssuer() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build(); for (String token : ALL_TOKENS) { - try { - tokenVerifier.verify(token); - fail("Should have thrown a VerificationException"); - } catch (TokenVerifier.VerificationException e) { - assertTrue(e.getMessage().contains("issuer does not match")); - } + TokenVerifier.VerificationException exception = + assertThrows( + TokenVerifier.VerificationException.class, + () -> tokenVerifier.verify(token), + "Should have thrown a VerificationException"); + assertTrue(exception.getMessage().contains("issuer does not match")); } } @Test - public void verifyEs256Token404CertificateUrl() { + void verifyEs256Token404CertificateUrl() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -151,15 +142,14 @@ public LowLevelHttpResponse execute() throws IOException { .setClock(FIXED_CLOCK) .setHttpTransportFactory(httpTransportFactory) .build(); - try { - tokenVerifier.verify(ES256_TOKEN); - } catch (TokenVerifier.VerificationException e) { - assertTrue(e.getMessage().contains("Could not find PublicKey")); - } + TokenVerifier.VerificationException exception = + assertThrows( + TokenVerifier.VerificationException.class, () -> tokenVerifier.verify(ES256_TOKEN)); + assertTrue(exception.getMessage().contains("Could not find PublicKey")); } @Test - public void verifyEs256TokenPublicKeyMismatch() { + void verifyEs256TokenPublicKeyMismatch() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -188,16 +178,16 @@ public LowLevelHttpResponse execute() throws IOException { .setClock(FIXED_CLOCK) .setHttpTransportFactory(httpTransportFactory) .build(); - try { - tokenVerifier.verify(ES256_TOKEN); - fail("Should have failed verification"); - } catch (TokenVerifier.VerificationException e) { - assertTrue(e.getMessage().contains("Error fetching PublicKey")); - } + TokenVerifier.VerificationException exception = + assertThrows( + TokenVerifier.VerificationException.class, + () -> tokenVerifier.verify(ES256_TOKEN), + "Should have failed verification"); + assertTrue(exception.getMessage().contains("Error fetching PublicKey")); } @Test - public void verifyEs256Token() throws TokenVerifier.VerificationException, IOException { + void verifyEs256Token() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.gstatic.com/iap/verify/public_key-jwk", @@ -211,7 +201,7 @@ public void verifyEs256Token() throws TokenVerifier.VerificationException, IOExc } @Test - public void verifyRs256Token() throws TokenVerifier.VerificationException, IOException { + void verifyRs256Token() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.googleapis.com/oauth2/v3/certs", @@ -225,7 +215,7 @@ public void verifyRs256Token() throws TokenVerifier.VerificationException, IOExc } @Test - public void verifyRs256TokenWithLegacyCertificateUrlFormat() + void verifyRs256TokenWithLegacyCertificateUrlFormat() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( @@ -240,8 +230,7 @@ public void verifyRs256TokenWithLegacyCertificateUrlFormat() } @Test - public void verifyServiceAccountRs256Token() - throws TokenVerifier.VerificationException, IOException { + void verifyServiceAccountRs256Token() throws TokenVerifier.VerificationException, IOException { TokenVerifier tokenVerifier = TokenVerifier.newBuilder() .setClock(FIXED_CLOCK) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java index 345c2b9c3..16cc0ec1d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.auth.TestUtils; import com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory; @@ -46,13 +46,10 @@ import java.util.Collections; 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; /** Unit Tests for UserAuthorizer */ -@RunWith(JUnit4.class) -public class UserAuthorizerTest { +class UserAuthorizerTest { private static final String CLIENT_ID_VALUE = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @@ -69,7 +66,7 @@ public class UserAuthorizerTest { private static final URI BASE_URI = URI.create("http://example.com/foo"); @Test - public void constructorMinimum() { + void constructorMinimum() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -86,7 +83,7 @@ public void constructorMinimum() { } @Test - public void constructorCommon() { + void constructorCommon() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -103,18 +100,22 @@ public void constructorCommon() { assertEquals(CALLBACK_URI, authorizer.getCallbackUri()); } - @Test(expected = NullPointerException.class) - public void constructorCommon_nullClientId_throws() { - UserAuthorizer.newBuilder().setScopes(SCOPES).setCallbackUri(CALLBACK_URI).build(); + @Test + void constructorCommon_nullClientId_throws() { + assertThrows( + NullPointerException.class, + () -> UserAuthorizer.newBuilder().setScopes(SCOPES).setCallbackUri(CALLBACK_URI).build()); } - @Test(expected = NullPointerException.class) - public void constructorCommon_nullScopes_throws() { - UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build(); + @Test + void constructorCommon_nullScopes_throws() { + assertThrows( + NullPointerException.class, + () -> UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build()); } @Test - public void getCallbackUri_relativeToBase() { + void getCallbackUri_relativeToBase() { final URI callbackURI = URI.create("/bar"); final URI expectedCallbackURI = URI.create("http://example.com/bar"); UserAuthorizer authorizer = @@ -130,7 +131,7 @@ public void getCallbackUri_relativeToBase() { } @Test - public void getAuthorizationUrl() throws IOException { + void getAuthorizationUrl() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -162,7 +163,7 @@ public void getAuthorizationUrl() throws IOException { } @Test - public void getCredentials_noCredentials_returnsNull() throws IOException { + void getCredentials_noCredentials_returnsNull() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -176,7 +177,7 @@ public void getCredentials_noCredentials_returnsNull() throws IOException { } @Test - public void getCredentials_storedCredentials_returnsStored() throws IOException { + void getCredentials_storedCredentials_returnsStored() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserCredentials initialCredentials = @@ -202,8 +203,8 @@ public void getCredentials_storedCredentials_returnsStored() throws IOException assertEquals(EXPIRATION_TIME, credentials.getAccessToken().getExpirationTimeMillis()); } - @Test(expected = NullPointerException.class) - public void getCredentials_nullUserId_throws() throws IOException { + @Test + void getCredentials_nullUserId_throws() { TokenStore tokenStore = new MemoryTokensStorage(); UserAuthorizer authorizer = UserAuthorizer.newBuilder() @@ -212,11 +213,11 @@ public void getCredentials_nullUserId_throws() throws IOException { .setTokenStore(tokenStore) .build(); - authorizer.getCredentials(null); + assertThrows(NullPointerException.class, () -> authorizer.getCredentials(null)); } @Test - public void getCredentials_refreshedToken_stored() throws IOException { + void getCredentials_refreshedToken_stored() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; AccessToken accessToken1 = new AccessToken(accessTokenValue1, new Date(EXPIRATION_TIME)); @@ -262,7 +263,7 @@ public void getCredentials_refreshedToken_stored() throws IOException { } @Test - public void getCredentialsFromCode_conevertsCodeToTokens() throws IOException { + void getCredentialsFromCode_conevertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode(CODE, REFRESH_TOKEN, ACCESS_TOKEN_VALUE); @@ -281,8 +282,8 @@ public void getCredentialsFromCode_conevertsCodeToTokens() throws IOException { assertEquals(ACCESS_TOKEN_VALUE, credentials.getAccessToken().getTokenValue()); } - @Test(expected = NullPointerException.class) - public void getCredentialsFromCode_nullCode_throws() throws IOException { + @Test + void getCredentialsFromCode_nullCode_throws() { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -290,11 +291,12 @@ public void getCredentialsFromCode_nullCode_throws() throws IOException { .setTokenStore(new MemoryTokensStorage()) .build(); - authorizer.getCredentialsFromCode(null, BASE_URI); + assertThrows( + NullPointerException.class, () -> authorizer.getCredentialsFromCode(null, BASE_URI)); } @Test - public void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { + void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -329,8 +331,8 @@ public void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOEx assertEquals(accessTokenValue2, credentials2.getAccessToken().getTokenValue()); } - @Test(expected = NullPointerException.class) - public void getAndStoreCredentialsFromCode_nullCode_throws() throws IOException { + @Test + void getAndStoreCredentialsFromCode_nullCode_throws() { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -338,11 +340,13 @@ public void getAndStoreCredentialsFromCode_nullCode_throws() throws IOException .setTokenStore(new MemoryTokensStorage()) .build(); - authorizer.getAndStoreCredentialsFromCode(USER_ID, null, BASE_URI); + assertThrows( + NullPointerException.class, + () -> authorizer.getAndStoreCredentialsFromCode(USER_ID, null, BASE_URI)); } - @Test(expected = NullPointerException.class) - public void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOException { + @Test + void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -350,11 +354,13 @@ public void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOExceptio .setTokenStore(new MemoryTokensStorage()) .build(); - authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI); + assertThrows( + NullPointerException.class, + () -> authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI)); } @Test - public void revokeAuthorization_revokesAndClears() throws IOException { + void revokeAuthorization_revokesAndClears() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -385,12 +391,8 @@ public void revokeAuthorization_revokesAndClears() throws IOException { authorizer.revokeAuthorization(USER_ID); - try { - credentials1.refresh(); - fail("Credentials should not refresh after revoke."); - } catch (IOException expected) { - // Expected - } + assertThrows( + IOException.class, credentials1::refresh, "Credentials should not refresh after revoke."); UserCredentials credentials2 = authorizer.getCredentials(USER_ID); assertNull(credentials2); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index d28e6011f..33457a36c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -31,13 +31,14 @@ 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 static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Clock; @@ -59,13 +60,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link UserCredentials}. */ -@RunWith(JUnit4.class) -public class UserCredentialsTest extends BaseSerializationTest { +class UserCredentialsTest extends BaseSerializationTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -81,13 +79,19 @@ public class UserCredentialsTest extends BaseSerializationTest { + "aXNzIjoiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAyMTAxNTUwODM0MjAwNzA4NTY4In0" + ".redacted"; - @Test(expected = IllegalStateException.class) - public void constructor_accessAndRefreshTokenNull_throws() { - UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); + @Test + void constructor_accessAndRefreshTokenNull_throws() { + assertThrows( + IllegalStateException.class, + () -> + UserCredentials.newBuilder() + .setClientId(CLIENT_ID) + .setClientSecret(CLIENT_SECRET) + .build()); } @Test - public void constructor() { + void constructor() { UserCredentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -102,7 +106,7 @@ public void constructor() { } @Test - public void createScoped_same() { + void createScoped_same() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -113,7 +117,7 @@ public void createScoped_same() { } @Test - public void createScopedRequired_false() { + void createScopedRequired_false() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -124,7 +128,7 @@ public void createScopedRequired_false() { } @Test - public void fromJson_hasAccessToken() throws IOException { + void fromJson_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -137,7 +141,7 @@ public void fromJson_hasAccessToken() throws IOException { } @Test - public void fromJson_hasQuotaProjectId() throws IOException { + void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -153,7 +157,7 @@ public void fromJson_hasQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_initialToken_hasAccessToken() throws IOException { + void getRequestMetadata_initialToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -171,7 +175,7 @@ public void getRequestMetadata_initialToken_hasAccessToken() throws IOException } @Test - public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { + void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -183,16 +187,14 @@ public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException .setHttpTransportFactory(transportFactory) .build(); - try { - userCredentials.refresh(); - fail("Should not be able to refresh without refresh token."); - } catch (IllegalStateException expected) { - // Expected - } + assertThrows( + IllegalStateException.class, + userCredentials::refresh, + "Should not be able to refresh without refresh token."); } @Test - public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { + void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -210,7 +212,7 @@ public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOExcept } @Test - public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { final URI TOKEN_SERVER = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -231,7 +233,7 @@ public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOExcep } @Test - public void equals_true() throws IOException { + void equals_true() { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -260,7 +262,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_clientId() throws IOException { + void equals_false_clientId() { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -287,7 +289,7 @@ public void equals_false_clientId() throws IOException { } @Test - public void equals_false_clientSecret() throws IOException { + void equals_false_clientSecret() { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -314,7 +316,7 @@ public void equals_false_clientSecret() throws IOException { } @Test - public void equals_false_refreshToken() throws IOException { + void equals_false_refreshToken() { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -341,7 +343,7 @@ public void equals_false_refreshToken() throws IOException { } @Test - public void equals_false_accessToken() throws IOException { + void equals_false_accessToken() { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); AccessToken otherAccessToken = new AccessToken("otherAccessToken", null); @@ -369,7 +371,7 @@ public void equals_false_accessToken() throws IOException { } @Test - public void equals_false_transportFactory() throws IOException { + void equals_false_transportFactory() { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -397,7 +399,7 @@ public void equals_false_transportFactory() throws IOException { } @Test - public void equals_false_tokenServer() throws IOException { + void equals_false_tokenServer() { final URI tokenServer1 = URI.create("https://foo1.com/bar"); final URI tokenServer2 = URI.create("https://foo2.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -425,7 +427,7 @@ public void equals_false_tokenServer() throws IOException { } @Test - public void equals_false_quotaProjectId() throws IOException { + void equals_false_quotaProjectId() { final String quotaProject1 = "sample-id-1"; final String quotaProject2 = "sample-id-2"; AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -453,7 +455,7 @@ public void equals_false_quotaProjectId() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -485,7 +487,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -513,7 +515,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -534,29 +536,25 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); - try { - UserCredentials.fromStream(stream, null); - fail("Should throw if HttpTransportFactory is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> UserCredentials.fromStream(stream, null), + "Should throw if HttpTransportFactory is null"); } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - try { - UserCredentials.fromStream(null, transportFactory); - fail("Should throw if InputStream is null"); - } catch (NullPointerException expected) { - // Expected - } + assertThrows( + NullPointerException.class, + () -> UserCredentials.fromStream(null, transportFactory), + "Should throw if InputStream is null"); } @Test - public void fromStream_user_providesToken() throws IOException { + void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -571,28 +569,28 @@ public void fromStream_user_providesToken() throws IOException { } @Test - public void fromStream_userNoClientId_throws() throws IOException { + void fromStream_userNoClientId_throws() throws IOException { InputStream userStream = writeUserStream(null, CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_id"); } @Test - public void fromStream_userNoClientSecret_throws() throws IOException { + void fromStream_userNoClientSecret_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_secret"); } @Test - public void fromStream_userNoRefreshToken_throws() throws IOException { + void fromStream_userNoRefreshToken_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, CLIENT_SECRET, null, QUOTA_PROJECT); testFromStreamException(userStream, "refresh_token"); } @Test - public void saveUserCredentials_saved_throws() throws IOException { + void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -607,7 +605,7 @@ public void saveUserCredentials_saved_throws() throws IOException { } @Test - public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { + void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -632,7 +630,7 @@ public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOExcep } @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -654,7 +652,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -672,7 +670,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataWithCallback() throws IOException { + void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -703,11 +701,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void IdTokenCredentials_WithUserEmailScope_success() throws IOException { + void IdTokenCredentials_WithUserEmailScope_success() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -734,7 +732,7 @@ public void IdTokenCredentials_WithUserEmailScope_success() throws IOException { } @Test - public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -752,11 +750,8 @@ public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + " login'. The latter form would not work for Cloud Run, but would still generate an" + " id token."; - try { - tokenCredential.refresh(); - } catch (IOException expected) { - assertTrue(expected.getMessage().equals(expectedMessageContent)); - } + IOException exception = assertThrows(IOException.class, tokenCredential::refresh); + assertTrue(exception.getMessage().equals(expectedMessageContent)); } static GenericJson writeUserJson( @@ -786,13 +781,12 @@ static InputStream writeUserStream( } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - try { - UserCredentials.fromStream(stream); - fail( - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - } catch (IOException expected) { - assertTrue(expected.getMessage().contains(expectedMessageContent)); - } + IOException exception = + assertThrows( + IOException.class, + () -> UserCredentials.fromStream(stream), + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + assertTrue(exception.getMessage().contains(expectedMessageContent)); } } diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index e03b5d3d4..5ea87d674 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -130,11 +130,6 @@ com.google.guava guava - - junit - junit - test - org.junit.jupiter junit-jupiter-api diff --git a/pom.xml b/pom.xml index 15ca9a429..71e872942 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,6 @@ UTF-8 1.40.1 - 4.13.2 5.8.1 31.0.1-android 1.9.91 @@ -121,12 +120,6 @@ auto-value-annotations ${auto-value-annotation.version} - - junit - junit - ${project.junit.version} - test - com.google.appengine appengine From 5557148208c2f3eb7b495ee9473543663a4b8cb5 Mon Sep 17 00:00:00 2001 From: Emily Ball Date: Thu, 14 Oct 2021 08:38:12 -0700 Subject: [PATCH 5/8] chore: update doclet version (#768) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 71e872942..75863f81a 100644 --- a/pom.xml +++ b/pom.xml @@ -497,7 +497,7 @@ com.microsoft.doclet.DocFxDoclet false - ${env.KOKORO_GFILE_DIR}/java-docfx-doclet-1.2.1.jar + ${env.KOKORO_GFILE_DIR}/java-docfx-doclet-1.3.0.jar -outputpath ${project.build.directory}/docfx-yml -projectname ${artifactId} none protected From 39712445949d536ea4b6ba9ef5f186111defdac1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 18 Oct 2021 16:54:30 +0000 Subject: [PATCH 6/8] build(java): Introduce Native Image testing build script changes (#771) --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/build.sh | 5 +++++ .kokoro/presubmit/graalvm-native.cfg | 33 ++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 .kokoro/presubmit/graalvm-native.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 284c8b69d..a600ac229 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/repo-automation-bots/owlbot-java:latest - digest: sha256:13b7387edb404234610d30473ac48210ae7fe42a136335ee2b2f8a07c4c7f6a5 + digest: sha256:d4b2141d65566523dfd523f63c6e6899ab1281463bce182a9f600e74b0511875 diff --git a/.kokoro/build.sh b/.kokoro/build.sh index 7970adcb1..30e14cf64 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -69,6 +69,11 @@ integration) verify RETURN_CODE=$? ;; +graalvm) + # Run Unit and Integration Tests with Native Image + mvn test -Pnative -Penable-integration-tests + RETURN_CODE=$? + ;; samples) SAMPLES_DIR=samples # only run ITs in snapshot/ on presubmit PRs. run ITs in all 3 samples/ subdirectories otherwise. diff --git a/.kokoro/presubmit/graalvm-native.cfg b/.kokoro/presubmit/graalvm-native.cfg new file mode 100644 index 000000000..4c7225ec9 --- /dev/null +++ b/.kokoro/presubmit/graalvm-native.cfg @@ -0,0 +1,33 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/graalvm" +} + +env_vars: { + key: "JOB_TYPE" + value: "graalvm" +} + +# TODO: remove this after we've migrated all tests and scripts +env_vars: { + key: "GCLOUD_PROJECT" + value: "gcloud-devel" +} + +env_vars: { + key: "GOOGLE_CLOUD_PROJECT" + value: "gcloud-devel" +} + +env_vars: { + key: "GOOGLE_APPLICATION_CREDENTIALS" + value: "secret_manager/java-it-service-account" +} + +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "java-it-service-account" +} From c8c3073790ca2f660eabd2c410b0e295f693040b Mon Sep 17 00:00:00 2001 From: Leo <39062083+lsirac@users.noreply.github.com> Date: Wed, 20 Oct 2021 15:59:58 -0700 Subject: [PATCH 7/8] fix: environment variable is "AWS_SESSION_TOKEN" and not "Token" (#772) --- oauth2_http/java/com/google/auth/oauth2/AwsCredentials.java | 2 +- .../javatests/com/google/auth/oauth2/AwsCredentialsTest.java | 4 ++-- .../com/google/auth/oauth2/AwsRequestSignerTest.java | 4 ++-- .../google/auth/oauth2/ITWorkloadIdentityFederationTest.java | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/oauth2_http/java/com/google/auth/oauth2/AwsCredentials.java b/oauth2_http/java/com/google/auth/oauth2/AwsCredentials.java index 4f00517bc..25d67660d 100644 --- a/oauth2_http/java/com/google/auth/oauth2/AwsCredentials.java +++ b/oauth2_http/java/com/google/auth/oauth2/AwsCredentials.java @@ -273,7 +273,7 @@ AwsSecurityCredentials getAwsSecurityCredentials() throws IOException { // Check environment variables for credentials first. String accessKeyId = getEnvironmentProvider().getEnv("AWS_ACCESS_KEY_ID"); String secretAccessKey = getEnvironmentProvider().getEnv("AWS_SECRET_ACCESS_KEY"); - String token = getEnvironmentProvider().getEnv("Token"); + String token = getEnvironmentProvider().getEnv("AWS_SESSION_TOKEN"); if (accessKeyId != null && secretAccessKey != null) { return new AwsSecurityCredentials(accessKeyId, secretAccessKey, token); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java index 16fcb61f9..c36bdf3bc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -276,7 +276,7 @@ void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOExce environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") .setEnv("AWS_SECRET_ACCESS_KEY", "awsSecretAccessKey") - .setEnv("Token", "token"); + .setEnv("AWS_SESSION_TOKEN", "awsSessionToken"); AwsCredentials testAwsCredentials = (AwsCredentials) @@ -288,7 +288,7 @@ void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOExce assertEquals("awsAccessKeyId", credentials.getAccessKeyId()); assertEquals("awsSecretAccessKey", credentials.getSecretAccessKey()); - assertEquals("token", credentials.getToken()); + assertEquals("awsSessionToken", credentials.getToken()); } @Test diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java index f7bdfb084..e43bb1dd9 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java @@ -535,9 +535,9 @@ public AwsSecurityCredentials retrieveAwsSecurityCredentials() throws IOExceptio GenericJson json = parser.parseAndClose(stream, StandardCharsets.UTF_8, GenericJson.class); - String awsToken = (String) json.get("Token"); - String secretAccessKey = (String) json.get("SecretAccessKey"); String accessKeyId = (String) json.get("AccessKeyId"); + String secretAccessKey = (String) json.get("SecretAccessKey"); + String awsToken = (String) json.get("Token"); return new AwsSecurityCredentials(accessKeyId, secretAccessKey, awsToken); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index 0683b0b5c..5ce78fcd2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java @@ -138,7 +138,7 @@ void awsCredentials() throws Exception { testEnvironmentProvider .setEnv("AWS_ACCESS_KEY_ID", awsAccessKeyId) .setEnv("AWS_SECRET_ACCESS_KEY", awsSecretAccessKey) - .setEnv("Token", awsSessionToken) + .setEnv("AWS_SESSION_TOKEN", awsSessionToken) .setEnv("AWS_REGION", "us-east-2"); AwsCredentials awsCredential = From 88386e4568386f60d824935892e2e22c74c2572e Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 21 Oct 2021 17:48:42 +0000 Subject: [PATCH 8/8] chore: release 1.2.2 (#774) :robot: I have created a release \*beep\* \*boop\* --- ### [1.2.2](https://www.github.com/googleapis/google-auth-library-java/compare/v1.2.1...v1.2.2) (2021-10-20) ### Bug Fixes * environment variable is "AWS_SESSION_TOKEN" and not "Token" ([#772](https://www.github.com/googleapis/google-auth-library-java/issues/772)) ([c8c3073](https://www.github.com/googleapis/google-auth-library-java/commit/c8c3073790ca2f660eabd2c410b0e295f693040b)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- 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 9c479b252..e7e31c7a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +### [1.2.2](https://www.github.com/googleapis/google-auth-library-java/compare/v1.2.1...v1.2.2) (2021-10-20) + + +### Bug Fixes + +* environment variable is "AWS_SESSION_TOKEN" and not "Token" ([#772](https://www.github.com/googleapis/google-auth-library-java/issues/772)) ([c8c3073](https://www.github.com/googleapis/google-auth-library-java/commit/c8c3073790ca2f660eabd2c410b0e295f693040b)) + ### [1.2.1](https://www.github.com/googleapis/google-auth-library-java/compare/v1.2.0...v1.2.1) (2021-10-11) diff --git a/README.md b/README.md index 122ed7efd..7d629f110 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.1 + 1.2.2 ``` [//]: # ({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.1' +compile 'com.google.auth:google-auth-library-oauth2-http:1.2.2' ``` [//]: # ({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.1" +libraryDependencies += "com.google.auth" % "google-auth-library-oauth2-http" % "1.2.2" ``` [//]: # ({x-version-update-end}) diff --git a/appengine/pom.xml b/appengine/pom.xml index 3b9953b32..ac06cbe5a 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.2-SNAPSHOT + 1.2.2 ../pom.xml diff --git a/bom/pom.xml b/bom/pom.xml index 5a80f6e6c..43e880985 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.2-SNAPSHOT + 1.2.2 pom Google Auth Library for Java BOM diff --git a/credentials/pom.xml b/credentials/pom.xml index a7da9af04..00b0c5b01 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -4,7 +4,7 @@ com.google.auth google-auth-library-parent - 1.2.2-SNAPSHOT + 1.2.2 ../pom.xml diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index 5ea87d674..147f7dae3 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -5,7 +5,7 @@ com.google.auth google-auth-library-parent - 1.2.2-SNAPSHOT + 1.2.2 ../pom.xml diff --git a/pom.xml b/pom.xml index 75863f81a..0f85fd36b 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.google.auth google-auth-library-parent - 1.2.2-SNAPSHOT + 1.2.2 pom Google Auth Library for Java Client libraries providing authentication and diff --git a/versions.txt b/versions.txt index f8a5496f2..5c93c58c8 100644 --- a/versions.txt +++ b/versions.txt @@ -1,9 +1,9 @@ # Format: # module:released-version:current-version -google-auth-library:1.2.1:1.2.2-SNAPSHOT -google-auth-library-bom:1.2.1:1.2.2-SNAPSHOT -google-auth-library-parent:1.2.1:1.2.2-SNAPSHOT -google-auth-library-appengine:1.2.1:1.2.2-SNAPSHOT -google-auth-library-credentials:1.2.1:1.2.2-SNAPSHOT -google-auth-library-oauth2-http:1.2.1:1.2.2-SNAPSHOT +google-auth-library:1.2.2:1.2.2 +google-auth-library-bom:1.2.2:1.2.2 +google-auth-library-parent:1.2.2:1.2.2 +google-auth-library-appengine:1.2.2:1.2.2 +google-auth-library-credentials:1.2.2:1.2.2 +google-auth-library-oauth2-http:1.2.2:1.2.2