From 904f78098363fe6c77f7ee1c3284ff149320a5f3 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Thu, 1 Jan 2026 19:36:22 -0500 Subject: [PATCH 01/19] chore: migrate tests from JUnit 4 to JUnit 5 --- .../appengine/AppEngineCredentialsTest.java | 48 ++- .../appengine/MockAppIdentityService.java | 2 +- appengine/pom.xml | 4 +- ...deCredentialAccessBoundaryFactoryTest.java | 111 +++---- ...lientSideCredentialAccessBoundaryTest.java | 16 +- cab-token-generator/pom.xml | 4 +- .../google/auth/ApiKeyCredentialsTest.java | 25 +- .../com/google/auth/SigningExceptionTest.java | 25 +- credentials/pom.xml | 4 +- .../javatests/com/google/auth/TestClock.java | 2 +- .../javatests/com/google/auth/TestUtils.java | 15 +- .../auth/http/HttpCredentialsAdapterTest.java | 26 +- .../auth/mtls/SecureConnectProviderTest.java | 36 +-- .../WorkloadCertificateConfigurationTest.java | 37 +-- .../google/auth/mtls/X509ProviderTest.java | 35 +-- .../google/auth/oauth2/AccessTokenTest.java | 38 +-- .../auth/oauth2/AppEngineCredentialsTest.java | 58 ++-- .../auth/oauth2/AwsCredentialsTest.java | 134 +++----- .../auth/oauth2/AwsRequestSignerTest.java | 56 ++-- .../auth/oauth2/BaseSerializationTest.java | 2 +- ...eIdentityPoolSubjectTokenSupplierTest.java | 113 +++---- .../com/google/auth/oauth2/ClientIdTest.java | 72 ++--- .../oauth2/CloudShellCredentialsTest.java | 40 +-- .../oauth2/ComputeEngineCredentialsTest.java | 213 +++++-------- .../oauth2/CredentialAccessBoundaryTest.java | 68 ++-- .../DefaultCredentialsProviderTest.java | 141 +++------ .../auth/oauth2/DefaultPKCEProviderTest.java | 20 +- .../oauth2/DownscopedCredentialsTest.java | 46 +-- .../auth/oauth2/ExecutableResponseTest.java | 56 ++-- ...lAccountAuthorizedUserCredentialsTest.java | 204 +++++------- .../ExternalAccountCredentialsTest.java | 181 ++++------- .../ExternalAccountSupplierContextTest.java | 15 +- .../auth/oauth2/GdchCredentialsTest.java | 121 +++----- .../auth/oauth2/GdchCredentialsTestUtil.java | 4 +- .../auth/oauth2/GoogleAuthUtilsTest.java | 14 +- .../auth/oauth2/GoogleCredentialsTest.java | 173 ++++------- .../google/auth/oauth2/ITDownscopingTest.java | 16 +- .../ITWorkloadIdentityFederationTest.java | 34 +- .../com/google/auth/oauth2/IamUtilsTest.java | 39 +-- .../auth/oauth2/IdTokenCredentialsTest.java | 22 +- .../com/google/auth/oauth2/IdTokenTest.java | 38 +-- .../IdentityPoolCredentialsSourceTest.java | 35 +-- .../oauth2/IdentityPoolCredentialsTest.java | 148 ++++----- .../oauth2/ImpersonatedCredentialsTest.java | 177 ++++------- ...nalAwsSecurityCredentialsSupplierTest.java | 32 +- .../com/google/auth/oauth2/JwtClaimsTest.java | 39 +-- .../auth/oauth2/JwtCredentialsTest.java | 56 ++-- .../com/google/auth/oauth2/LoggingTest.java | 42 +-- .../google/auth/oauth2/LoggingUtilsTest.java | 22 +- .../google/auth/oauth2/MetricsUtilsTest.java | 21 +- .../com/google/auth/oauth2/MockExecutor.java | 2 +- ...ckExternalAccountCredentialsTransport.java | 9 +- .../auth/oauth2/MockHttpTransportFactory.java | 2 +- .../MockIAMCredentialsServiceTransport.java | 2 +- ...IAMCredentialsServiceTransportFactory.java | 2 +- .../oauth2/MockMetadataServerTransport.java | 2 +- .../oauth2/MockRequestMetadataCallback.java | 2 +- .../google/auth/oauth2/MockStsTransport.java | 7 +- .../oauth2/MockTokenCheckingTransport.java | 2 +- .../auth/oauth2/MockTokenServerTransport.java | 2 +- .../MockTokenServerTransportFactory.java | 2 +- .../auth/oauth2/OAuth2CredentialsTest.java | 129 +++----- .../OAuth2CredentialsWithRefreshTest.java | 41 +-- .../google/auth/oauth2/OAuth2UtilsTest.java | 25 +- .../auth/oauth2/OAuthExceptionTest.java | 33 +- .../oauth2/PluggableAuthCredentialsTest.java | 65 ++-- .../oauth2/PluggableAuthExceptionTest.java | 32 +- .../auth/oauth2/PluggableAuthHandlerTest.java | 82 ++--- .../oauth2/SecureSessionAgentConfigTest.java | 21 +- .../auth/oauth2/SecureSessionAgentTest.java | 30 +- .../oauth2/ServiceAccountCredentialsTest.java | 292 +++++++----------- ...erviceAccountJwtAccessCredentialsTest.java | 180 ++++------- .../auth/oauth2/Slf4jUtilsLogbackTest.java | 40 +-- .../google/auth/oauth2/Slf4jUtilsTest.java | 32 +- .../auth/oauth2/StsRequestHandlerTest.java | 66 ++-- .../com/google/auth/oauth2/TestAppender.java | 4 +- .../auth/oauth2/TestEnvironmentProvider.java | 2 +- .../com/google/auth/oauth2/TestUtils.java | 9 +- .../google/auth/oauth2/TokenVerifierTest.java | 50 ++- .../auth/oauth2/UserAuthorizerTest.java | 191 ++++++------ .../auth/oauth2/UserCredentialsTest.java | 156 ++++------ .../FTComputeEngineCredentialsTest.java | 27 +- .../oauth2/functional/FTQuotaProjectId.java | 13 +- .../FTServiceAccountCredentialsTest.java | 53 ++-- oauth2_http/pom.xml | 17 +- pom.xml | 25 +- samples/snippets/pom.xml | 6 + .../snippets/src/test/java/SnippetsIT.java | 46 +-- 88 files changed, 1764 insertions(+), 2817 deletions(-) diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index e1c3d5201..7fa155fe7 100644 --- a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java +++ b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java @@ -31,14 +31,13 @@ package com.google.auth.appengine; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.BaseSerializationTest; @@ -51,13 +50,10 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for AppEngineCredentials */ -@RunWith(JUnit4.class) -public class AppEngineCredentialsTest extends BaseSerializationTest { +class AppEngineCredentialsTest extends BaseSerializationTest { private static Collection SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope1", "scope2")); @@ -65,7 +61,7 @@ public class AppEngineCredentialsTest extends BaseSerializationTest { private static final String EXPECTED_ACCOUNT = "serviceAccount"; @Test - public void constructor_usesAppIdentityService() throws IOException { + void constructor_usesAppIdentityService() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -83,7 +79,7 @@ public void constructor_usesAppIdentityService() throws IOException { } @Test - public void refreshAccessToken_sameAs() throws IOException { + void refreshAccessToken_sameAs() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -100,7 +96,7 @@ public void refreshAccessToken_sameAs() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setServiceAccountName(EXPECTED_ACCOUNT); AppEngineCredentials credentials = @@ -112,7 +108,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() throws IOException { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setSignature(expectedSignature); @@ -125,7 +121,7 @@ public void sign_sameAs() throws IOException { } @Test - public void createScoped_clonesWithScopes() throws IOException { + void createScoped_clonesWithScopes() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; Collection emptyScopes = Collections.emptyList(); @@ -155,7 +151,7 @@ public void createScoped_clonesWithScopes() throws IOException { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -175,7 +171,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() throws IOException { Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -195,7 +191,7 @@ public void equals_false_scopes() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { String expectedToString = String.format( "AppEngineCredentials{scopes=[%s], scopesRequired=%b, appIdentityServiceClassName=%s}", @@ -213,7 +209,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -230,7 +226,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -249,7 +245,7 @@ private static void assertContainsBearerToken(Map> metadata assertNotNull(token); String expectedValue = "Bearer " + token; List authorizations = metadata.get("Authorization"); - assertNotNull("Authorization headers not found", authorizations); - assertTrue("Bearer token not found", authorizations.contains(expectedValue)); + assertNotNull(authorizations, "Authorization headers not found"); + assertTrue(authorizations.contains(expectedValue), "Bearer token not found"); } -} +} \ No newline at end of file diff --git a/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java b/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java index c0befa4c7..a7fa4eb40 100644 --- a/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java +++ b/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java @@ -120,4 +120,4 @@ public ParsedAppId parseFullAppId(String fullAppId) { public String getDefaultGcsBucketName() { return null; } -} +} \ No newline at end of file diff --git a/appengine/pom.xml b/appengine/pom.xml index fde9650c8..8199e0676 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -64,8 +64,8 @@ guava - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java index 3f353db37..d44252324 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java @@ -31,11 +31,12 @@ package com.google.auth.credentialaccessboundary; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; + import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -69,17 +70,15 @@ import java.util.Base64; import java.util.Map; import java.util.concurrent.CountDownLatch; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link * com.google.auth.credentialaccessboundary.ClientSideCredentialAccessBoundaryFactory}. */ -@RunWith(JUnit4.class) -public class ClientSideCredentialAccessBoundaryFactoryTest { + +class ClientSideCredentialAccessBoundaryFactoryTest { private static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n" + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALX0PQoe1igW12i" @@ -106,8 +105,7 @@ public HttpTransport create() { } } - @Before - public void setUp() { + @BeforeEach void setUp() { mockStsTransportFactory = new MockStsTransportFactory(); mockStsTransportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -116,8 +114,7 @@ public void setUp() { "service-account@google.com", "accessToken"); } - @Test - public void fetchIntermediateCredentials() throws Exception { + @Test void fetchIntermediateCredentials() throws Exception { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -145,8 +142,7 @@ public void fetchIntermediateCredentials() throws Exception { intermediateCredentials.getIntermediateAccessToken().getTokenValue()); } - @Test - public void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { + @Test void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { String universeDomain = "foobar"; GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() @@ -167,8 +163,7 @@ public void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOExc assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain)); } - @Test - public void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() + @Test void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() throws Exception { // Simulate error when refreshing the source credential. mockTokenServerTransportFactory.transport.setError(new IOException()); @@ -186,8 +181,7 @@ public void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOE assertEquals("Unable to refresh the provided source credential.", thrown.getMessage()); } - @Test - public void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() + @Test void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() throws Exception { // Simulate STS not returning expires_in. mockStsTransportFactory.transport.setReturnExpiresIn(false); @@ -215,8 +209,7 @@ public void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpirat sourceAccessToken.getExpirationTime(), intermediateAccessToken.getExpirationTime()); } - @Test - public void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() + @Test void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -235,8 +228,7 @@ public void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentia assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); } - @Test - public void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { + @Test void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.NONE); @@ -251,8 +243,7 @@ public void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); } - @Test - public void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { + @Test void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -273,8 +264,7 @@ public void refreshCredentialsIfRequired_blockingSingleThread() throws IOExcepti assertEquals(1 + numRefresh, mockStsTransportFactory.transport.getRequestCount()); } - @Test - public void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { + @Test void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -308,8 +298,7 @@ public void refreshCredentialsIfRequired_asyncSingleThread() throws IOException assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } - @Test - public void refreshCredentialsIfRequired_blockingMultiThread() + @Test void refreshCredentialsIfRequired_blockingMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -329,8 +318,7 @@ public void refreshCredentialsIfRequired_blockingMultiThread() assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } - @Test - public void refreshCredentialsIfRequired_asyncMultiThread() + @Test void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -357,8 +345,7 @@ public void refreshCredentialsIfRequired_asyncMultiThread() assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } - @Test - public void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOException() + @Test void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOException() throws Exception { // Simulate error when refreshing the source credential. mockTokenServerTransportFactory.transport.setError(new IOException()); @@ -377,8 +364,7 @@ public void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOE } // Tests related to the builder methods. - @Test - public void builder_noSourceCredential_throws() { + @Test void builder_noSourceCredential_throws() { NullPointerException exception = assertThrows( NullPointerException.class, @@ -389,8 +375,7 @@ public void builder_noSourceCredential_throws() { assertEquals("Source credential must not be null.", exception.getMessage()); } - @Test - public void builder_minimumTokenLifetime_negative_throws() throws IOException { + @Test void builder_minimumTokenLifetime_negative_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -404,8 +389,7 @@ public void builder_minimumTokenLifetime_negative_throws() throws IOException { assertEquals("Minimum token lifetime must be greater than zero.", exception.getMessage()); } - @Test - public void builder_minimumTokenLifetime_zero_throws() throws IOException { + @Test void builder_minimumTokenLifetime_zero_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -419,8 +403,7 @@ public void builder_minimumTokenLifetime_zero_throws() throws IOException { assertEquals("Minimum token lifetime must be greater than zero.", exception.getMessage()); } - @Test - public void builder_refreshMargin_negative_throws() throws IOException { + @Test void builder_refreshMargin_negative_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -434,8 +417,7 @@ public void builder_refreshMargin_negative_throws() throws IOException { assertEquals("Refresh margin must be greater than zero.", exception.getMessage()); } - @Test - public void builder_refreshMargin_zero_throws() throws IOException { + @Test void builder_refreshMargin_zero_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -449,8 +431,7 @@ public void builder_refreshMargin_zero_throws() throws IOException { assertEquals("Refresh margin must be greater than zero.", exception.getMessage()); } - @Test - public void builder_setsCorrectDefaultValues() throws IOException { + @Test void builder_setsCorrectDefaultValues() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); ClientSideCredentialAccessBoundaryFactory factory = @@ -464,8 +445,7 @@ public void builder_setsCorrectDefaultValues() throws IOException { factory.getTokenExchangeEndpoint()); } - @Test - public void builder_universeDomainMismatch_throws() throws IOException { + @Test void builder_universeDomainMismatch_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -482,8 +462,7 @@ public void builder_universeDomainMismatch_throws() throws IOException { exception.getMessage()); } - @Test - public void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { + @Test void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -502,8 +481,7 @@ public void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws exception.getMessage()); } - @Test - public void builder_invalidRefreshMargin_throws() throws IOException { + @Test void builder_invalidRefreshMargin_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -521,8 +499,7 @@ public void builder_invalidRefreshMargin_throws() throws IOException { exception.getMessage()); } - @Test - public void builder_invalidMinimumTokenLifetime_throws() throws IOException { + @Test void builder_invalidMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -540,8 +517,7 @@ public void builder_invalidMinimumTokenLifetime_throws() throws IOException { exception.getMessage()); } - @Test - public void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException { + @Test void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -556,8 +532,7 @@ public void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException factory.getMinimumTokenLifetime()); } - @Test - public void builder_refreshMarginNotSet_usesDefault() throws IOException { + @Test void builder_refreshMarginNotSet_usesDefault() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -709,8 +684,7 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S return ClientSideAccessBoundary.parseFrom(rawRestrictions); } - @Test - public void generateToken_withAvailablityCondition_success() throws Exception { + @Test void generateToken_withAvailablityCondition_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -769,8 +743,7 @@ public void generateToken_withAvailablityCondition_success() throws Exception { assertEquals("b", expr.getCallExpr().getArgs(1).getIdentExpr().getName()); } - @Test - public void generateToken_withoutAvailabilityCondition_success() throws Exception { + @Test void generateToken_withoutAvailabilityCondition_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -821,8 +794,7 @@ public void generateToken_withoutAvailabilityCondition_success() throws Exceptio assertFalse(rule.hasCompiledAvailabilityCondition()); } - @Test - public void generateToken_withMultipleRules_success() throws Exception { + @Test void generateToken_withMultipleRules_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -885,8 +857,7 @@ public void generateToken_withMultipleRules_success() throws Exception { assertFalse(rule2.hasCompiledAvailabilityCondition()); } - @Test - public void generateToken_withInvalidAvailabilityCondition_failure() throws Exception { + @Test void generateToken_withInvalidAvailabilityCondition_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -922,8 +893,7 @@ public void generateToken_withInvalidAvailabilityCondition_failure() throws Exce assertThrows(CelValidationException.class, () -> factory.generateToken(accessBoundary)); } - @Test - public void generateToken_withSessionKeyNotBase64Encoded_failure() throws Exception { + @Test void generateToken_withSessionKeyNotBase64Encoded_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); transportFactory.transport.setAccessBoundarySessionKey("invalid_key"); @@ -959,8 +929,7 @@ public void generateToken_withSessionKeyNotBase64Encoded_failure() throws Except assertThrows(IllegalStateException.class, () -> factory.generateToken(accessBoundary)); } - @Test - public void generateToken_withMalformSessionKey_failure() throws Exception { + @Test void generateToken_withMalformSessionKey_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); transportFactory.transport.setAccessBoundarySessionKey("aW52YWxpZF9rZXk="); @@ -995,4 +964,4 @@ public void generateToken_withMalformSessionKey_failure() throws Exception { assertThrows(GeneralSecurityException.class, () -> factory.generateToken(accessBoundary)); } -} +} \ No newline at end of file diff --git a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java index 5ef5bfb68..786eaff18 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java @@ -31,10 +31,9 @@ package com.google.auth.credentialaccessboundary; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - +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; import com.google.api.client.http.HttpRequestFactory; @@ -52,7 +51,7 @@ import dev.cel.common.CelValidationException; import java.io.IOException; import java.security.GeneralSecurityException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Integration tests for {@link ClientSideCredentialAccessBoundaryFactory}. * @@ -61,7 +60,7 @@ * GOOGLE_APPLICATION_CREDENTIALS to point to the same service account configured in the setup * script (downscoping-with-cab-setup.sh). */ -public final class ITClientSideCredentialAccessBoundaryTest { +final class ITClientSideCredentialAccessBoundaryTest { // Output copied from the setup script (downscoping-with-cab-setup.sh). private static final String GCS_BUCKET_NAME = "cab-int-bucket-cbi3qrv5"; @@ -97,8 +96,7 @@ public final class ITClientSideCredentialAccessBoundaryTest { * downscoped token. 2. Validating that we do not have permission to retrieve a different object * in the same bucket. */ - @Test - public void clientSideCredentialAccessBoundary_serviceAccountSource() throws IOException { + @Test void clientSideCredentialAccessBoundary_serviceAccountSource() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = () -> { ServiceAccountCredentials sourceCredentials = @@ -150,4 +148,4 @@ private void retrieveObjectFromGcs(Credentials credentials, String objectName) HttpResponse response = request.execute(); assertTrue(response.isSuccessStatusCode()); } -} +} \ No newline at end of file diff --git a/cab-token-generator/pom.xml b/cab-token-generator/pom.xml index 9fa12ab2e..e3a31c722 100644 --- a/cab-token-generator/pom.xml +++ b/cab-token-generator/pom.xml @@ -58,8 +58,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/credentials/javatests/com/google/auth/ApiKeyCredentialsTest.java b/credentials/javatests/com/google/auth/ApiKeyCredentialsTest.java index 661d06c18..1de45daa9 100644 --- a/credentials/javatests/com/google/auth/ApiKeyCredentialsTest.java +++ b/credentials/javatests/com/google/auth/ApiKeyCredentialsTest.java @@ -30,33 +30,30 @@ */ package com.google.auth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +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 java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link ApiKeyCredentials}. */ -@RunWith(JUnit4.class) -public class ApiKeyCredentialsTest { +class ApiKeyCredentialsTest { private static final String TEST_API_KEY = "testApiKey"; @Test - public void testGetAuthenticationType() { + void testGetAuthenticationType() { ApiKeyCredentials credentials = ApiKeyCredentials.create(TEST_API_KEY); assertEquals("API-Key", credentials.getAuthenticationType()); } @Test - public void testGetRequestMetadata() throws IOException, URISyntaxException { + void testGetRequestMetadata() throws IOException, URISyntaxException { ApiKeyCredentials credentials = ApiKeyCredentials.create(TEST_API_KEY); Map> metadata = credentials.getRequestMetadata(new URI("http://test.com")); assertEquals(1, metadata.size()); @@ -66,24 +63,24 @@ public void testGetRequestMetadata() throws IOException, URISyntaxException { } @Test - public void testHasRequestMetadata() { + void testHasRequestMetadata() { ApiKeyCredentials credentials = ApiKeyCredentials.create(TEST_API_KEY); assertTrue(credentials.hasRequestMetadata()); } @Test - public void testHasRequestMetadataOnly() { + void testHasRequestMetadataOnly() { ApiKeyCredentials credentials = ApiKeyCredentials.create(TEST_API_KEY); assertTrue(credentials.hasRequestMetadataOnly()); } @Test - public void testNullApiKey_ThrowsException() { + void testNullApiKey_ThrowsException() { assertThrows(IllegalArgumentException.class, () -> ApiKeyCredentials.create(null)); } @Test - public void testBlankApiKey_ThrowsException() { + void testBlankApiKey_ThrowsException() { assertThrows(IllegalArgumentException.class, () -> ApiKeyCredentials.create("")); } } diff --git a/credentials/javatests/com/google/auth/SigningExceptionTest.java b/credentials/javatests/com/google/auth/SigningExceptionTest.java index 0d7aa48c5..8787c71a0 100644 --- a/credentials/javatests/com/google/auth/SigningExceptionTest.java +++ b/credentials/javatests/com/google/auth/SigningExceptionTest.java @@ -31,29 +31,28 @@ package com.google.auth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.auth.ServiceAccountSigner.SigningException; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SigningExceptionTest { +class SigningExceptionTest { private static final String EXPECTED_MESSAGE = "message"; private static final RuntimeException EXPECTED_CAUSE = new RuntimeException(); @Test - public void constructor() { + void constructor() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertEquals(EXPECTED_MESSAGE, signingException.getMessage()); assertSame(EXPECTED_CAUSE, signingException.getCause()); } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertTrue(signingException.equals(otherSigningException)); @@ -61,7 +60,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_message() throws IOException { + void equals_false_message() throws IOException { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException("otherMessage", EXPECTED_CAUSE); assertFalse(signingException.equals(otherSigningException)); @@ -69,7 +68,7 @@ public void equals_false_message() throws IOException { } @Test - public void equals_false_cause() throws IOException { + void equals_false_cause() throws IOException { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException("otherMessage", new RuntimeException()); @@ -78,9 +77,9 @@ public void equals_false_cause() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertEquals(signingException.hashCode(), otherSigningException.hashCode()); } -} +} \ No newline at end of file diff --git a/credentials/pom.xml b/credentials/pom.xml index da1fc3e4f..3bb116ac0 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -46,8 +46,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/oauth2_http/javatests/com/google/auth/TestClock.java b/oauth2_http/javatests/com/google/auth/TestClock.java index fa3dd027f..364d66321 100644 --- a/oauth2_http/javatests/com/google/auth/TestClock.java +++ b/oauth2_http/javatests/com/google/auth/TestClock.java @@ -50,4 +50,4 @@ public void addToCurrentTime(long milliseconds) { public void setCurrentTime(long currentTime) { this.currentTime = currentTime; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/TestUtils.java b/oauth2_http/javatests/com/google/auth/TestUtils.java index 99d601da8..52d8f726d 100644 --- a/oauth2_http/javatests/com/google/auth/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/TestUtils.java @@ -31,10 +31,9 @@ package com.google.auth; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.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; import com.google.api.client.json.GenericJson; @@ -70,20 +69,20 @@ 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); - assertFalse("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); + assertNotNull(authorizations, "Authorization headers not found"); return authorizations.contains(expectedValue); } @@ -151,4 +150,4 @@ public static String getDefaultExpireTime() { } private TestUtils() {} -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index bdbcd2c91..a2e1ebe4b 100644 --- a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java +++ b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java @@ -31,9 +31,9 @@ package com.google.auth.http; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; @@ -47,20 +47,17 @@ import com.google.auth.oauth2.OAuth2Credentials; import com.google.auth.oauth2.UserCredentials; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link HttpCredentialsAdapter}. */ -@RunWith(JUnit4.class) -public class HttpCredentialsAdapterTest { + +class HttpCredentialsAdapterTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; - @Test - public void initialize_populatesOAuth2Credentials() throws IOException { + @Test void initialize_populatesOAuth2Credentials() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -86,8 +83,7 @@ public void initialize_populatesOAuth2Credentials() throws IOException { assertEquals(authorizationHeader, expectedAuthorization); } - @Test - public void initialize_populatesOAuth2Credentials_handle401() throws IOException { + @Test void initialize_populatesOAuth2Credentials_handle401() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; @@ -124,8 +120,7 @@ public void initialize_populatesOAuth2Credentials_handle401() throws IOException assertEquals(MockTokenCheckingTransport.SUCCESS_CONTENT, response.parseAsString()); } - @Test - public void initialize_noURI() throws IOException { + @Test void initialize_noURI() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory tokenServerTransportFactory = @@ -153,8 +148,7 @@ public void initialize_noURI() throws IOException { assertEquals(authorizationHeader, expectedAuthorization); } - @Test - public void getCredentials() { + @Test void getCredentials() { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory(); @@ -173,4 +167,4 @@ public void getCredentials() { Credentials returnedCredentials = adapter.getCredentials(); assertThat(returnedCredentials, instanceOf(Credentials.class)); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java index 9592a52d6..498ae5072 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java @@ -31,18 +31,17 @@ package com.google.auth.mtls; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - +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 java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SecureConnectProviderTest { +class SecureConnectProviderTest { private static class TestCertProviderCommandProcess extends Process { @@ -100,8 +99,7 @@ public Process createProcess(InputStream metadata) throws IOException { } } - @Test - public void testGetKeyStoreNonZeroExitCode() + @Test void testGetKeyStoreNonZeroExitCode() throws IOException, InterruptedException, GeneralSecurityException { InputStream metadata = this.getClass() @@ -112,14 +110,13 @@ public void testGetKeyStoreNonZeroExitCode() IOException.class, () -> SecureConnectProvider.getKeyStore(metadata, new TestProcessProvider(1))); assertTrue( - "expected to fail with nonzero exit code", actual .getMessage() - .contains("SecureConnect: Cert provider command failed with exit code: 1")); + .contains("SecureConnect: Cert provider command failed with exit code: 1"), + "expected to fail with nonzero exit code"); } - @Test - public void testExtractCertificateProviderCommand() throws IOException { + @Test void testExtractCertificateProviderCommand() throws IOException { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mtls_context_aware_metadata.json"); List command = SecureConnectProvider.extractCertificateProviderCommand(inputStream); @@ -128,27 +125,22 @@ public void testExtractCertificateProviderCommand() throws IOException { assertEquals("some_argument", command.get(1)); } - @Test - public void testRunCertificateProviderCommandSuccess() throws IOException, InterruptedException { + @Test void testRunCertificateProviderCommandSuccess() throws IOException, InterruptedException { Process certCommandProcess = new TestCertProviderCommandProcess(0, false); int exitValue = SecureConnectProvider.runCertificateProviderCommand(certCommandProcess, 100); assertEquals(0, exitValue); } - @Test - public void testRunCertificateProviderCommandTimeout() throws InterruptedException { + @Test void testRunCertificateProviderCommandTimeout() throws InterruptedException { Process certCommandProcess = new TestCertProviderCommandProcess(0, true); IOException actual = assertThrows( IOException.class, () -> SecureConnectProvider.runCertificateProviderCommand(certCommandProcess, 100)); - assertTrue( - "expected to fail with timeout", - actual.getMessage().contains("SecureConnect: Cert provider command timed out")); + assertTrue(actual.getMessage().contains("SecureConnect: Cert provider command timed out"), "expected to fail with timeout"); } - @Test - public void testGetKeyStore_FileNotFoundException() + @Test void testGetKeyStore_FileNotFoundException() throws IOException, GeneralSecurityException, InterruptedException { SecureConnectProvider provider = new SecureConnectProvider(new TestProcessProvider(0), "/invalid/metadata/path.json"); @@ -158,4 +150,4 @@ public void testGetKeyStore_FileNotFoundException() assertEquals("SecureConnect metadata does not exist.", exception.getMessage()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java index 70bb4294e..c09802012 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java @@ -31,20 +31,19 @@ package com.google.auth.mtls; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - +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.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; import java.io.InputStream; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class WorkloadCertificateConfigurationTest { +class WorkloadCertificateConfigurationTest { - @Test - public void workloadCertificateConfig_fromStream_Succeeds() throws IOException { + @Test void workloadCertificateConfig_fromStream_Succeeds() throws IOException { String certPath = "cert.crt"; String privateKeyPath = "key.crt"; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); @@ -54,14 +53,13 @@ public void workloadCertificateConfig_fromStream_Succeeds() throws IOException { assertNotNull(config); } - @Test - public void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws IOException { + @Test void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws IOException { String certPath = ""; String privateKeyPath = "key.crt"; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); IllegalArgumentException exception = - Assert.assertThrows( + assertThrows( IllegalArgumentException.class, () -> WorkloadCertificateConfiguration.fromCertificateConfigurationStream(configStream)); @@ -72,14 +70,13 @@ public void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws I "The cert_path field must be provided in the workload certificate configuration.")); } - @Test - public void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() throws IOException { + @Test void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() throws IOException { String certPath = "cert.crt"; String privateKeyPath = ""; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); IllegalArgumentException exception = - Assert.assertThrows( + assertThrows( IllegalArgumentException.class, () -> WorkloadCertificateConfiguration.fromCertificateConfigurationStream(configStream)); @@ -90,14 +87,13 @@ public void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() th "The key_path field must be provided in the workload certificate configuration.")); } - @Test - public void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws IOException { + @Test void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws IOException { GenericJson json = new GenericJson(); json.put("cert_configs", new GenericJson()); InputStream configStream = TestUtils.jsonToInputStream(json); CertificateSourceUnavailableException exception = - Assert.assertThrows( + assertThrows( CertificateSourceUnavailableException.class, () -> WorkloadCertificateConfiguration.fromCertificateConfigurationStream(configStream)); @@ -108,13 +104,12 @@ public void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws I "A workload certificate configuration must be provided in the cert_configs object.")); } - @Test - public void workloadCertificateConfig_fromStreamMissingCertConfig_Fails() throws IOException { + @Test void workloadCertificateConfig_fromStreamMissingCertConfig_Fails() throws IOException { GenericJson json = new GenericJson(); InputStream configStream = TestUtils.jsonToInputStream(json); IllegalArgumentException exception = - Assert.assertThrows( + assertThrows( IllegalArgumentException.class, () -> WorkloadCertificateConfiguration.fromCertificateConfigurationStream(configStream)); @@ -147,4 +142,4 @@ private static GenericJson writeWorkloadCertificateConfigJson( json.put("cert_configs", certConfigs); return json; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java index de016cf55..7d62c4170 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java @@ -31,10 +31,10 @@ package com.google.auth.mtls; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; @@ -47,10 +47,10 @@ import java.security.cert.CertificateFactory; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class X509ProviderTest { +class X509ProviderTest { private static final String TEST_CERT = "-----BEGIN CERTIFICATE-----\n" @@ -86,19 +86,17 @@ public class X509ProviderTest { + "VUV6b25kqrcu\n" + "-----END PRIVATE KEY-----"; - @Test - public void x509Provider_fileDoesntExist_throws() { + @Test void x509Provider_fileDoesntExist_throws() { String certConfigPath = "badfile.txt"; X509Provider testProvider = new TestX509Provider(certConfigPath); String expectedErrorMessage = "File does not exist."; CertificateSourceUnavailableException exception = - Assert.assertThrows(CertificateSourceUnavailableException.class, testProvider::getKeyStore); + assertThrows(CertificateSourceUnavailableException.class, testProvider::getKeyStore); assertTrue(exception.getMessage().contains(expectedErrorMessage)); } - @Test - public void x509Provider_emptyFile_throws() { + @Test void x509Provider_emptyFile_throws() { String certConfigPath = "certConfig.txt"; InputStream certConfigStream = new ByteArrayInputStream("".getBytes()); TestX509Provider testProvider = new TestX509Provider(certConfigPath); @@ -106,12 +104,11 @@ public void x509Provider_emptyFile_throws() { String expectedErrorMessage = "no JSON input found"; IllegalArgumentException exception = - Assert.assertThrows(IllegalArgumentException.class, testProvider::getKeyStore); + assertThrows(IllegalArgumentException.class, testProvider::getKeyStore); assertTrue(exception.getMessage().contains(expectedErrorMessage)); } - @Test - public void x509Provider_succeeds() throws IOException, KeyStoreException, CertificateException { + @Test void x509Provider_succeeds() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; String keyPath = "key.crt"; @@ -134,8 +131,7 @@ public void x509Provider_succeeds() throws IOException, KeyStoreException, Certi assertNotNull(store.getCertificateAlias(expectedCert)); } - @Test - public void x509Provider_succeeds_withEnvVariable() + @Test void x509Provider_succeeds_withEnvVariable() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; @@ -160,8 +156,7 @@ public void x509Provider_succeeds_withEnvVariable() assertNotNull(store.getCertificateAlias(expectedCert)); } - @Test - public void x509Provider_succeeds_withWellKnownPath() + @Test void x509Provider_succeeds_withWellKnownPath() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; @@ -235,4 +230,4 @@ InputStream createInputStream(File file) throws FileNotFoundException { return stream; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java index f32fe231b..4bf342da2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java @@ -31,24 +31,20 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for AccessToken */ -@RunWith(JUnit4.class) -public class AccessTokenTest extends BaseSerializationTest { +class AccessTokenTest extends BaseSerializationTest { private static final String TOKEN = "AccessToken"; private static final Date EXPIRATION_DATE = new Date(); @@ -56,7 +52,7 @@ public class AccessTokenTest extends BaseSerializationTest { private static final String SCOPES_STRING = "scope1 scope2"; @Test - public void constructor() { + void constructor() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(TOKEN, accessToken.getTokenValue()); assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); @@ -65,7 +61,7 @@ public void constructor() { } @Test - public void builder() { + void builder() { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -108,7 +104,7 @@ public void builder() { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -129,7 +125,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() throws IOException { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -149,7 +145,7 @@ public void equals_false_scopes() throws IOException { } @Test - public void equals_false_token() throws IOException { + void equals_false_token() throws IOException { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -169,7 +165,7 @@ public void equals_false_token() throws IOException { } @Test - public void equals_false_expirationDate() throws IOException { + void equals_false_expirationDate() throws IOException { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -189,7 +185,7 @@ public void equals_false_expirationDate() throws IOException { } @Test - public void toString_containsFields() { + void toString_containsFields() { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -204,7 +200,7 @@ public void toString_containsFields() { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -223,7 +219,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { AccessToken emptyScopes = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -249,4 +245,4 @@ public void serialize() throws IOException, ClassNotFoundException { assertEquals(accessToken.hashCode(), deserializedAccessToken.hashCode()); assertEquals(accessToken.toString(), deserializedAccessToken.toString()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index 82b76d879..e5582a3d7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -31,13 +31,12 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.util.ArrayList; @@ -47,12 +46,9 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class AppEngineCredentialsTest extends BaseSerializationTest { +class AppEngineCredentialsTest extends BaseSerializationTest { private static final String EXPECTED_ACCESS_TOKEN = "ExpectedAccessToken"; private static final Date EXPECTED_EXPIRATION_DATE = @@ -65,8 +61,7 @@ public class AppEngineCredentialsTest extends BaseSerializationTest { private static final Collection DEFAULT_SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope3")); - @Test - public void constructor_usesAppIdentityService() throws IOException { + @Test void constructor_usesAppIdentityService() throws IOException { Collection scopes = Collections.singleton("SomeScope"); TestAppEngineCredentials credentials = new TestAppEngineCredentials(scopes); List forNameArgs = credentials.getForNameArgs(); @@ -77,8 +72,7 @@ public void constructor_usesAppIdentityService() throws IOException { assertEquals(AppEngineCredentials.SIGNING_RESULT_CLASS, forNameArgs.get(3)); } - @Test - public void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { + @Test void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { try { new TestAppEngineCredentialsNoSdk(); fail("Credential expected to fail to load if credential class not present."); @@ -93,28 +87,24 @@ public void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOExc } } - @Test - public void refreshAccessToken_sameAs() throws IOException { + @Test void refreshAccessToken_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); } - @Test - public void getAccount_sameAs() throws IOException { + @Test void getAccount_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(EXPECTED_ACCOUNT, credentials.getAccount()); } - @Test - public void sign_sameAs() throws IOException { + @Test void sign_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertArrayEquals(EXPECTED_SIGNATURE, credentials.sign("Bytes to sign".getBytes())); } - @Test - public void createScoped_clonesWithScopes() throws IOException { + @Test void createScoped_clonesWithScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); try { @@ -132,8 +122,7 @@ public void createScoped_clonesWithScopes() throws IOException { assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); } - @Test - public void createScoped_defaultScopes() throws IOException { + @Test void createScoped_defaultScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); @@ -151,8 +140,7 @@ public void createScoped_defaultScopes() throws IOException { assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { GoogleCredentials credentials = new TestAppEngineCredentials(SCOPES); GoogleCredentials otherCredentials = new TestAppEngineCredentials(SCOPES); assertTrue(credentials.equals(credentials)); @@ -160,8 +148,7 @@ public void equals_true() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_scopes() throws IOException { + @Test void equals_false_scopes() throws IOException { final Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(emptyScopes); @@ -170,8 +157,7 @@ public void equals_false_scopes() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { String expectedToString = String.format( "TestAppEngineCredentials{scopes=[%s], scopesRequired=%b}", "SomeScope", false); @@ -180,14 +166,12 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { AppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(credentials.hashCode(), credentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(scopes); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); @@ -306,4 +290,4 @@ Class forName(String className) throws ClassNotFoundException { throw new ClassNotFoundException(className); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java index e8b401063..a6e793150 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonParser; @@ -56,13 +56,11 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link AwsCredentials}. */ -@RunWith(JUnit4.class) -public class AwsCredentialsTest extends BaseSerializationTest { + +class AwsCredentialsTest extends BaseSerializationTest { private static final String STS_URL = "https://sts.googleapis.com/v1/token"; private static final String AWS_CREDENTIALS_URL = "https://169.254.169.254"; @@ -111,8 +109,7 @@ public class AwsCredentialsTest extends BaseSerializationTest { private static final ExternalAccountSupplierContext emptyContext = ExternalAccountSupplierContext.newBuilder().setAudience("").setSubjectTokenType("").build(); - @Test - public void test_awsCredentialSource() { + @Test void test_awsCredentialSource() { String keys[] = {"region_url", "url", "imdsv2_session_token_url"}; for (String key : keys) { Map credentialSourceWithInvalidUrl = buildAwsIpv6CredentialSourceMap(); @@ -123,8 +120,7 @@ public void test_awsCredentialSource() { } } - @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -145,8 +141,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc ExternalAccountCredentialsTest.validateMetricsHeader(headers, "aws", false, false); } - @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -175,8 +170,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept ExternalAccountCredentialsTest.validateMetricsHeader(headers, "aws", true, false); } - @Test - public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + @Test void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -215,8 +209,7 @@ public void refreshAccessToken_withServiceAccountImpersonationOptions() throws I ExternalAccountCredentialsTest.validateMetricsHeader(headers, "aws", true, true); } - @Test - public void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() + @Test void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -243,8 +236,7 @@ public void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersona ExternalAccountCredentialsTest.validateMetricsHeader(headers, "programmatic", false, false); } - @Test - public void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() + @Test void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -278,7 +270,7 @@ public void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonatio @Test @SuppressWarnings("unchecked") - public void retrieveSubjectToken() throws IOException { + void retrieveSubjectToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -322,7 +314,7 @@ public void retrieveSubjectToken() throws IOException { @Test @SuppressWarnings("unchecked") - public void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { + void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -385,8 +377,7 @@ public void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(4), AWS_CREDENTIALS_URL_WITH_ROLE, sessionTokenHeader); } - @Test - public void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() + @Test void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -431,8 +422,7 @@ public void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() assertEquals(0, requests.size()); } - @Test - public void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() + @Test void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -477,8 +467,7 @@ public void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() assertEquals(0, requests.size()); } - @Test - public void retrieveSubjectToken_noRegion_expectThrows() { + @Test void retrieveSubjectToken_noRegion_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -505,8 +494,7 @@ public void retrieveSubjectToken_noRegion_expectThrows() { ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS); } - @Test - public void retrieveSubjectToken_noRole_expectThrows() { + @Test void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -537,8 +525,7 @@ public void retrieveSubjectToken_noRole_expectThrows() { ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL, EMPTY_STRING_HEADERS); } - @Test - public void retrieveSubjectToken_noCredentials_expectThrows() { + @Test void retrieveSubjectToken_noCredentials_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -572,8 +559,7 @@ public void retrieveSubjectToken_noCredentials_expectThrows() { ValidateRequest(requests.get(2), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS); } - @Test - public void retrieveSubjectToken_noRegionUrlProvided() { + @Test void retrieveSubjectToken_noRegionUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -602,8 +588,7 @@ public void retrieveSubjectToken_noRegionUrlProvided() { assertTrue(requests.isEmpty()); } - @Test - public void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { + @Test void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -641,8 +626,7 @@ public void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { assertNotNull(headers.get("Authorization")); } - @Test - public void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IOException { + @Test void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -684,8 +668,7 @@ public void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IO assertNotNull(headers.get("Authorization")); } - @Test - public void retrieveSubjectToken_passesContext() throws IOException { + @Test void retrieveSubjectToken_passesContext() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -714,8 +697,7 @@ public void retrieveSubjectToken_passesContext() throws IOException { awsCredential.retrieveSubjectToken(); } - @Test - public void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOException { + @Test void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -741,8 +723,7 @@ public void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOE } } - @Test - public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { + @Test void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -761,8 +742,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws I assertNull(credentials.getSessionToken()); } - @Test - public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { + @Test void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -794,8 +774,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws assertEquals("awsSessionToken", credentials.getSessionToken()); } - @Test - public void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerCall() + @Test void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerCall() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider @@ -816,8 +795,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerC assertEquals("awsSessionToken", credentials.getSessionToken()); } - @Test - public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { + @Test void getAwsSecurityCredentials_fromMetadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -844,8 +822,7 @@ public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS); } - @Test - public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { + @Test void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -873,8 +850,7 @@ public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { assertTrue(requests.isEmpty()); } - @Test - public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { + @Test void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_REGION", "region"); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -899,8 +875,7 @@ public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { assertTrue(requests.isEmpty()); } - @Test - public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { + @Test void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -924,8 +899,7 @@ public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOExceptio assertTrue(requests.isEmpty()); } - @Test - public void getAwsRegion_metadataServer() throws IOException { + @Test void getAwsRegion_metadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredentials = @@ -951,8 +925,7 @@ public void getAwsRegion_metadataServer() throws IOException { ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS); } - @Test - public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + @Test void createdScoped_clonedCredentialWithAddedScopes() throws IOException { AwsCredentials credentials = AwsCredentials.newBuilder(AWS_CREDENTIAL) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -982,8 +955,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { assertEquals("universeDomain", newCredentials.getUniverseDomain()); } - @Test - public void credentialSource_invalidAwsEnvironmentId() { + @Test void credentialSource_invalidAwsEnvironmentId() { Map credentialSource = new HashMap<>(); credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "azure1"); @@ -996,8 +968,7 @@ public void credentialSource_invalidAwsEnvironmentId() { } } - @Test - public void credentialSource_invalidAwsEnvironmentVersion() { + @Test void credentialSource_invalidAwsEnvironmentVersion() { Map credentialSource = new HashMap<>(); int environmentVersion = 2; credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); @@ -1014,8 +985,7 @@ public void credentialSource_invalidAwsEnvironmentVersion() { } } - @Test - public void credentialSource_missingRegionalCredVerificationUrl() { + @Test void credentialSource_missingRegionalCredVerificationUrl() { try { new AwsCredentialSource(new HashMap()); fail("Exception should be thrown."); @@ -1026,8 +996,7 @@ public void credentialSource_missingRegionalCredVerificationUrl() { } } - @Test - public void builder_allFields() throws IOException { + @Test void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1062,8 +1031,7 @@ public void builder_allFields() throws IOException { assertEquals("universeDomain", credentials.getUniverseDomain()); } - @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + @Test void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1099,8 +1067,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void newBuilder_allFields() throws IOException { + @Test void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1137,8 +1104,7 @@ public void newBuilder_allFields() throws IOException { assertEquals(credentials.getUniverseDomain(), newBuilderCreds.getUniverseDomain()); } - @Test - public void newBuilder_noUniverseDomain_defaults() throws IOException { + @Test void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1174,8 +1140,7 @@ public void newBuilder_noUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, newBuilderCreds.getUniverseDomain()); } - @Test - public void builder_defaultRegionalCredentialVerificationUrlOverride() throws IOException { + @Test void builder_defaultRegionalCredentialVerificationUrlOverride() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsSecurityCredentialsSupplier supplier = @@ -1202,8 +1167,7 @@ public void builder_defaultRegionalCredentialVerificationUrlOverride() throws IO credentials.getRegionalCredentialVerificationUrl()); } - @Test - public void builder_supplierAndCredSourceThrows() throws IOException { + @Test void builder_supplierAndCredSourceThrows() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsSecurityCredentialsSupplier supplier = @@ -1233,8 +1197,7 @@ public void builder_supplierAndCredSourceThrows() throws IOException { } } - @Test - public void builder_noSupplieOrCredSourceThrows() throws IOException { + @Test void builder_noSupplieOrCredSourceThrows() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); Supplier testSupplier = () -> null; @@ -1262,8 +1225,7 @@ public void builder_noSupplieOrCredSourceThrows() throws IOException { } } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials testCredentials = @@ -1399,4 +1361,4 @@ public AwsSecurityCredentials getCredentials(ExternalAccountSupplierContext cont return credentials; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java index 3bac05214..dacd30014 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java @@ -31,8 +31,7 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; - +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; @@ -43,8 +42,8 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link AwsRequestSigner}. @@ -52,7 +51,7 @@ *

Examples of sigv4 signed requests: * https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html */ -public class AwsRequestSignerTest { +class AwsRequestSignerTest { private static final String DATE = "Mon, 09 Sep 2011 23:36:00 GMT"; private static final String X_AMZ_DATE = "20200811T065522Z"; @@ -63,8 +62,7 @@ public class AwsRequestSignerTest { private AwsSecurityCredentials awsSecurityCredentials; - @Before - public void setUp() throws IOException { + @BeforeEach void setUp() throws IOException { // Required for date parsing when run in different Locales Locale.setDefault(Locale.US); awsSecurityCredentials = retrieveAwsSecurityCredentials(); @@ -72,8 +70,7 @@ public void setUp() throws IOException { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.sreq - @Test - public void sign_getHost() { + @Test void sign_getHost() { String url = "https://host.foo.com"; Map headers = new HashMap<>(); @@ -103,8 +100,7 @@ public void sign_getHost() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.sreq - @Test - public void sign_getHostRelativePath() { + @Test void sign_getHostRelativePath() { String url = "https://host.foo.com/foo/bar/../.."; Map headers = new HashMap<>(); @@ -134,8 +130,7 @@ public void sign_getHostRelativePath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.sreq - @Test - public void sign_getHostInvalidPath() { + @Test void sign_getHostInvalidPath() { String url = "https://host.foo.com/./"; Map headers = new HashMap<>(); @@ -165,8 +160,7 @@ public void sign_getHostInvalidPath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.sreq - @Test - public void sign_getHostDotPath() { + @Test void sign_getHostDotPath() { String url = "https://host.foo.com/./foo"; Map headers = new HashMap<>(); @@ -196,8 +190,7 @@ public void sign_getHostDotPath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.sreq - @Test - public void sign_getHostUtf8Path() { + @Test void sign_getHostUtf8Path() { String url = "https://host.foo.com/%E1%88%B4"; Map headers = new HashMap<>(); @@ -227,8 +220,7 @@ public void sign_getHostUtf8Path() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.sreq - @Test - public void sign_getHostDuplicateQueryParam() { + @Test void sign_getHostDuplicateQueryParam() { String url = "https://host.foo.com/?foo=Zoo&foo=aha"; Map headers = new HashMap<>(); @@ -258,8 +250,7 @@ public void sign_getHostDuplicateQueryParam() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.sreq - @Test - public void sign_postWithUpperCaseHeaderKey() { + @Test void sign_postWithUpperCaseHeaderKey() { String url = "https://host.foo.com/"; String headerKey = "ZOO"; String headerValue = "zoobar"; @@ -293,8 +284,7 @@ public void sign_postWithUpperCaseHeaderKey() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.sreq - @Test - public void sign_postWithUpperCaseHeaderValue() { + @Test void sign_postWithUpperCaseHeaderValue() { String url = "https://host.foo.com/"; String headerKey = "zoo"; String headerValue = "ZOOBAR"; @@ -328,8 +318,7 @@ public void sign_postWithUpperCaseHeaderValue() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.sreq - @Test - public void sign_postWithHeader() { + @Test void sign_postWithHeader() { String url = "https://host.foo.com/"; String headerKey = "p"; String headerValue = "phfft"; @@ -363,8 +352,7 @@ public void sign_postWithHeader() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.sreq - @Test - public void sign_postWithBodyNoCustomHeaders() { + @Test void sign_postWithBodyNoCustomHeaders() { String url = "https://host.foo.com/"; String headerKey = "Content-Type"; String headerValue = "application/x-www-form-urlencoded"; @@ -399,8 +387,7 @@ public void sign_postWithBodyNoCustomHeaders() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.sreq - @Test - public void sign_postWithQueryString() { + @Test void sign_postWithQueryString() { String url = "https://host.foo.com/?foo=bar"; Map headers = new HashMap<>(); @@ -428,8 +415,7 @@ public void sign_postWithQueryString() { assertEquals(URI.create(url).normalize().toString(), signature.getUrl()); } - @Test - public void sign_getDescribeRegions() { + @Test void sign_getDescribeRegions() { String url = "https://ec2.us-east-2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15"; Map additionalHeaders = new HashMap<>(); @@ -459,8 +445,7 @@ public void sign_getDescribeRegions() { assertEquals(URI.create(url).normalize().toString(), signature.getUrl()); } - @Test - public void sign_postGetCallerIdentity() { + @Test void sign_postGetCallerIdentity() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; Map additionalHeaders = new HashMap<>(); @@ -490,8 +475,7 @@ public void sign_postGetCallerIdentity() { assertEquals(URI.create(url).normalize().toString(), signature.getUrl()); } - @Test - public void sign_postGetCallerIdentityNoToken() { + @Test void sign_postGetCallerIdentityNoToken() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; AwsSecurityCredentials awsSecurityCredentialsWithoutToken = @@ -544,4 +528,4 @@ public AwsSecurityCredentials retrieveAwsSecurityCredentials() throws IOExceptio return new AwsSecurityCredentials(accessKeyId, secretAccessKey, awsToken); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java index f9fbac134..23fd21b6b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java @@ -51,4 +51,4 @@ public T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundExc return (T) input.readObject(); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java index bfc7c59cb..c8e2c28ea 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java @@ -31,10 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import com.google.auth.oauth2.IdentityPoolCredentialSource.CertificateConfig; @@ -53,20 +54,16 @@ import java.security.cert.X509Certificate; import java.util.Base64; import java.util.List; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link CertificateIdentityPoolSubjectTokenSupplier}. */ -@RunWith(JUnit4.class) -public class CertificateIdentityPoolSubjectTokenSupplierTest { - - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); +@ExtendWith(MockitoExtension.class) +class CertificateIdentityPoolSubjectTokenSupplierTest { @Mock private IdentityPoolCredentialSource mockCredentialSource; @Mock private CertificateConfig mockCertificateConfig; @@ -86,37 +83,34 @@ public class CertificateIdentityPoolSubjectTokenSupplierTest { private byte[] testCertBytesFromFile; private byte[] intermediateCertBytesFromFile; - @Before - public void setUp() throws IOException, URISyntaxException { + @BeforeEach void setUp() throws IOException, URISyntaxException { ClassLoader classLoader = getClass().getClassLoader(); URL leafCertUrl = classLoader.getResource("x509_leaf_certificate.pem"); - assertNotNull("Test leaf certificate file not found!", leafCertUrl); + assertNotNull(leafCertUrl, "Test leaf certificate file not found!"); File testCertFile = new File(leafCertUrl.getFile()); URL intermediateCertUrl = classLoader.getResource("x509_intermediate_certificate.pem"); - assertNotNull("Test intermediate certificate file not found!", intermediateCertUrl); + assertNotNull(intermediateCertUrl, "Test intermediate certificate file not found!"); - when(mockCertificateConfig.useDefaultCertificateConfig()).thenReturn(false); - when(mockCertificateConfig.getCertificateConfigLocation()) + lenient().when(mockCertificateConfig.useDefaultCertificateConfig()).thenReturn(false); + lenient().when(mockCertificateConfig.getCertificateConfigLocation()) .thenReturn(testCertFile.getAbsolutePath()); - when(mockCredentialSource.getCertificateConfig()).thenReturn(mockCertificateConfig); - when(mockCredentialSource.getCredentialLocation()).thenReturn(testCertFile.getAbsolutePath()); + lenient().when(mockCredentialSource.getCertificateConfig()).thenReturn(mockCertificateConfig); + lenient().when(mockCredentialSource.getCredentialLocation()).thenReturn(testCertFile.getAbsolutePath()); supplier = new CertificateIdentityPoolSubjectTokenSupplier(mockCredentialSource); testCertBytesFromFile = Files.readAllBytes(Paths.get(leafCertUrl.toURI())); intermediateCertBytesFromFile = Files.readAllBytes(Paths.get(intermediateCertUrl.toURI())); } - @Test - public void parseCertificate_validData_returnsCertificate() throws Exception { + @Test void parseCertificate_validData_returnsCertificate() throws Exception { X509Certificate cert = CertificateIdentityPoolSubjectTokenSupplier.parseCertificate(testCertBytesFromFile); assertNotNull(cert); } - @Test - public void parseCertificate_emptyData_throwsIllegalArgumentException() { + @Test void parseCertificate_emptyData_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -125,8 +119,7 @@ public void parseCertificate_emptyData_throwsIllegalArgumentException() { "Invalid certificate data: Certificate file is empty or null.", exception.getMessage()); } - @Test - public void parseCertificate_nullData_throwsIllegalArgumentException() { + @Test void parseCertificate_nullData_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -135,8 +128,7 @@ public void parseCertificate_nullData_throwsIllegalArgumentException() { "Invalid certificate data: Certificate file is empty or null.", exception.getMessage()); } - @Test - public void parseCertificate_invalidData_throwsCertificateException() { + @Test void parseCertificate_invalidData_throwsCertificateException() { CertificateException exception = assertThrows( CertificateException.class, @@ -144,8 +136,7 @@ public void parseCertificate_invalidData_throwsCertificateException() { assertEquals("Failed to parse X.509 certificate data.", exception.getMessage()); } - @Test - public void getSubjectToken_withoutTrustChain_success() throws Exception { + @Test void getSubjectToken_withoutTrustChain_success() throws Exception { // Calculate expected result based on the file content. CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate expectedCert = @@ -161,12 +152,11 @@ public void getSubjectToken_withoutTrustChain_success() throws Exception { assertEquals(expectedSubjectToken, actualSubjectToken); } - @Test - public void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { + @Test void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { // Configure mock to return the path to the trust chain file with leaf. ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("trust_chain_with_leaf.pem"); - assertNotNull("Test trust chain file not found!", trustChainUrl); + assertNotNull(trustChainUrl, "Test trust chain file not found!"); when(mockCertificateConfig.getTrustChainPath()) .thenReturn(new File(trustChainUrl.getFile()).getAbsolutePath()); @@ -195,12 +185,11 @@ public void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { assertEquals(expectedSubjectToken, actualSubjectToken); } - @Test - public void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { + @Test void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { // Configure mock to return the path to the trust chain file WITHOUT leaf. ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("trust_chain_without_leaf.pem"); - assertNotNull("Test trust chain file (without leaf) not found!", trustChainUrl); + assertNotNull(trustChainUrl, "Test trust chain file (without leaf) not found!"); when(mockCertificateConfig.getTrustChainPath()) .thenReturn(new File(trustChainUrl.getFile()).getAbsolutePath()); @@ -234,11 +223,10 @@ public void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { // when the trust chain file is provided and contains the leaf certificate, // but the leaf certificate is not the *first* certificate in that file. // For example, an intermediate certificate appears before the leaf certificate. - @Test - public void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException() { + @Test void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException() { ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("trust_chain_wrong_order.pem"); - assertNotNull("Test trust chain file (wrong order) not found!", trustChainUrl); + assertNotNull(trustChainUrl, "Test trust chain file (wrong order) not found!"); String trustChainPath = new File(trustChainUrl.getFile()).getAbsolutePath(); when(mockCertificateConfig.getTrustChainPath()).thenReturn(trustChainPath); @@ -254,22 +242,17 @@ public void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException( assertEquals(expectedOuterExceptionMessage, exception.getMessage()); Throwable cause = exception.getCause(); - assertNotNull("Exception cause should not be null", cause); - assertTrue( - "Exception cause should be an IllegalArgumentException", - cause instanceof IllegalArgumentException); + assertNotNull(cause, "Exception cause should not be null"); + assertTrue(cause instanceof IllegalArgumentException, "Exception cause should be an IllegalArgumentException"); assertEquals(expectedRootErrorMessage, cause.getMessage()); } - @Test - public void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { + @Test void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { // Configure mock to use the leaf certificate file itself as the trust chain file, // simulating a scenario where the trust chain file contains only the leaf. ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("x509_leaf_certificate.pem"); - assertNotNull( - "Test resource 'x509_leaf_certificate.pem' (used as trust chain) not found!", - trustChainUrl); + assertNotNull(trustChainUrl, "Test resource 'x509_leaf_certificate.pem' (used as trust chain) not found!"); when(mockCertificateConfig.getTrustChainPath()) .thenReturn(new File(trustChainUrl.getFile()).getAbsolutePath()); @@ -291,8 +274,7 @@ public void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { assertEquals(expectedSubjectToken, actualSubjectToken); } - @Test - public void getSubjectToken_trustChainFileNotFound_throwsIOException() { + @Test void getSubjectToken_trustChainFileNotFound_throwsIOException() { // Configure mock to return a non-existent path for the trust chain. String nonExistentPath = "/path/to/non/existent/trust_chain.pem"; when(mockCertificateConfig.getTrustChainPath()).thenReturn(nonExistentPath); @@ -308,8 +290,7 @@ public void getSubjectToken_trustChainFileNotFound_throwsIOException() { assertEquals("Trust chain file not found: " + nonExistentPath, exception.getMessage()); } - @Test - public void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws Exception { + @Test void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws Exception { // Create a temporary file with invalid cert data for the trust chain. File invalidTrustChainFile = File.createTempFile("invalid_trust_chain", ".pem"); invalidTrustChainFile.deleteOnExit(); @@ -341,8 +322,7 @@ public void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws E "Error loading PEM certificates from the trust chain file: " + invalidPath)); } - @Test - public void getSubjectToken_leafCertFileNotFound_throwsIOException() { + @Test void getSubjectToken_leafCertFileNotFound_throwsIOException() { // Configure mock to return a non-existent path for the leaf certificate. String nonExistentPath = "/path/to/non/existent/leaf.pem"; when(mockCredentialSource.getCredentialLocation()).thenReturn(nonExistentPath); @@ -357,9 +337,8 @@ public void getSubjectToken_leafCertFileNotFound_throwsIOException() { assertEquals("Leaf certificate file not found: " + nonExistentPath, exception.getMessage()); // Check that the cause is the original NoSuchFileException. - assertNotNull("Exception should have a cause", exception.getCause()); - assertTrue( - "Cause should be NoSuchFileException", exception.getCause() instanceof NoSuchFileException); + assertNotNull(exception.getCause(), "Exception should have a cause"); + assertTrue(exception.getCause() instanceof NoSuchFileException, "Cause should be NoSuchFileException"); // Check the message of the cause (which is the path) in a platform-agnostic way. Path expectedCausePath = Paths.get(nonExistentPath); @@ -367,8 +346,7 @@ public void getSubjectToken_leafCertFileNotFound_throwsIOException() { assertEquals(expectedCausePath, actualCausePath); } - @Test - public void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exception { + @Test void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exception { // Create a temporary file with invalid cert data. File invalidLeafFile = File.createTempFile("invalid_leaf", ".pem"); invalidLeafFile.deleteOnExit(); @@ -395,8 +373,7 @@ public void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exc exception.getMessage()); } - @Test - public void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertificateException() + @Test void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertificateException() throws IOException { // Create a temporary file with content that does not match PEM certificate blocks. File trustChainFile = File.createTempFile("non_pem_content_trust_chain", ".txt"); @@ -417,15 +394,13 @@ public void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertif assertEquals(expectedMessage, exception.getMessage()); } - @Test - public void readTrustChain_nullPath_returnsEmptyList() throws Exception { + @Test void readTrustChain_nullPath_returnsEmptyList() throws Exception { List certs = CertificateIdentityPoolSubjectTokenSupplier.readTrustChain(null); assertNotNull(certs); assertTrue(certs.isEmpty()); } - @Test - public void readTrustChain_emptyFile_returnsEmptyList() throws IOException, CertificateException { + @Test void readTrustChain_emptyFile_returnsEmptyList() throws IOException, CertificateException { // Create an empty temporary file. File emptyFile = File.createTempFile("empty_trust_chain", ".pem"); emptyFile.deleteOnExit(); @@ -436,4 +411,4 @@ public void readTrustChain_emptyFile_returnsEmptyList() throws IOException, Cert assertNotNull(certs); assertTrue(certs.isEmpty()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java index d7a5ca015..c3da45974 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java @@ -31,25 +31,22 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for ClientId */ -@RunWith(JUnit4.class) -public class ClientIdTest { + +class ClientIdTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; - @Test - public void constructor() { + @Test void constructor() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); @@ -57,20 +54,19 @@ public void constructor() { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test(expected = NullPointerException.class) - public void constructor_nullClientId_throws() { - ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build(); + @Test + void constructor_nullClientId_throws() { + assertThrows( + NullPointerException.class, () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); } - @Test - public void constructor_nullClientSecret() { + @Test void constructor_nullClientSecret() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).build(); assertEquals(CLIENT_ID, clientId.getClientId()); assertNull(clientId.getClientSecret()); } - @Test - public void fromJson_web() throws IOException { + @Test void fromJson_web() throws IOException { GenericJson json = writeClientIdJson("web", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -79,8 +75,7 @@ public void fromJson_web() throws IOException { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test - public void fromJson_installed() throws IOException { + @Test void fromJson_installed() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -89,8 +84,7 @@ public void fromJson_installed() throws IOException { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test - public void fromJson_installedNoSecret() throws IOException { + @Test void fromJson_installedNoSecret() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, null); ClientId clientId = ClientId.fromJson(json); @@ -99,42 +93,41 @@ public void fromJson_installedNoSecret() throws IOException { assertNull(clientId.getClientSecret()); } - @Test(expected = IOException.class) - public void fromJson_invalidType_throws() throws IOException { + @Test + void fromJson_invalidType_throws() throws IOException { GenericJson json = writeClientIdJson("invalid", CLIENT_ID, null); - ClientId.fromJson(json); + assertThrows(IOException.class, () -> ClientId.fromJson(json)); } - @Test(expected = IOException.class) - public void fromJson_noClientId_throws() throws IOException { + @Test + void fromJson_noClientId_throws() throws IOException { GenericJson json = writeClientIdJson("web", null, null); - ClientId.fromJson(json); + assertThrows(IOException.class, () -> ClientId.fromJson(json)); } - @Test(expected = IOException.class) - public void fromJson_zeroLengthClientId_throws() throws IOException { + @Test + void fromJson_zeroLengthClientId_throws() throws IOException { GenericJson json = writeClientIdJson("web", "", null); - ClientId.fromJson(json); + assertThrows(IOException.class, () -> ClientId.fromJson(json)); } - @Test - public void fromResource() throws IOException { + @Test void fromResource() throws IOException { ClientId clientId = ClientId.fromResource(ClientIdTest.class, "/client_secret.json"); assertEquals(CLIENT_ID, clientId.getClientId()); assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test(expected = NullPointerException.class) - public void fromResource_badResource() throws IOException { - ClientId.fromResource(ClientIdTest.class, "invalid.json"); + @Test + void fromResource_badResource() throws IOException { + assertThrows( + NullPointerException.class, () -> ClientId.fromResource(ClientIdTest.class, "invalid.json")); } - @Test - public void fromStream() throws IOException { + @Test void fromStream() throws IOException { String text = "{" + "\"web\": {" @@ -154,8 +147,7 @@ public void fromStream() throws IOException { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test - public void fromStream_invalidJson_doesNotThrow() throws IOException { + @Test void fromStream_invalidJson_doesNotThrow() throws IOException { String invalidJson = "{" + "\"web\": {" @@ -183,4 +175,4 @@ private GenericJson writeClientIdJson(String type, String clientId, String clien json.put(type, details); return json; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java index e316df4d8..5ec50d8a2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java @@ -31,11 +31,10 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.util.Clock; import java.io.BufferedReader; import java.io.IOException; @@ -43,16 +42,13 @@ import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for CloudShellCredentials */ -@RunWith(JUnit4.class) -public class CloudShellCredentialsTest extends BaseSerializationTest { - @Test - public void refreshAccessToken() throws IOException { +class CloudShellCredentialsTest extends BaseSerializationTest { + + @Test void refreshAccessToken() throws IOException { final ServerSocket authSocket = new ServerSocket(0); try { Runnable serverTask = @@ -85,38 +81,33 @@ public void run() { } } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertTrue(credentials.equals(otherCredentials)); assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_authPort() throws IOException { + @Test void equals_false_authPort() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(43).build(); assertFalse(credentials.equals(otherCredentials)); assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { String expectedToString = String.format("CloudShellCredentials{authPort=%d}", 42); GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); assertEquals(credentials, deserializedCredentials); @@ -125,8 +116,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test - public void toBuilder() { + @Test void toBuilder() { CloudShellCredentials credentials = CloudShellCredentials.newBuilder() .setAuthPort(42) @@ -140,4 +130,4 @@ public void toBuilder() { assertEquals(credentials, secondCredentials); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java index a3df59e1a..c8702a87b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -31,17 +31,17 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.oauth2.ComputeEngineCredentials.METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE; import static com.google.auth.oauth2.ImpersonatedCredentialsTest.SA_CLIENT_EMAIL; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -69,14 +69,12 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** Test case for {@link ComputeEngineCredentials}. */ -@RunWith(JUnit4.class) -public class ComputeEngineCredentialsTest extends BaseSerializationTest { + +class ComputeEngineCredentialsTest extends BaseSerializationTest { private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); @@ -128,8 +126,7 @@ public class ComputeEngineCredentialsTest extends BaseSerializationTest { }) .collect(Collectors.toMap(data -> data[0], data -> data[1])); - @Test - public void buildTokenUrlWithScopes_null_scopes() { + @Test void buildTokenUrlWithScopes_null_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); Collection scopes = credentials.getScopes(); @@ -139,8 +136,7 @@ public void buildTokenUrlWithScopes_null_scopes() { assertTrue(scopes.isEmpty()); } - @Test - public void buildTokenUrlWithScopes_empty_scopes() { + @Test void buildTokenUrlWithScopes_empty_scopes() { ComputeEngineCredentials.Builder builder = ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); ComputeEngineCredentials credentials = builder.build(); @@ -152,8 +148,7 @@ public void buildTokenUrlWithScopes_empty_scopes() { assertTrue(builder.getScopes().isEmpty()); } - @Test - public void buildTokenUrlWithScopes_single_scope() { + @Test void buildTokenUrlWithScopes_single_scope() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(Arrays.asList("foo")).build(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -164,8 +159,7 @@ public void buildTokenUrlWithScopes_single_scope() { assertEquals("foo", scopes.toArray()[0]); } - @Test - public void buildTokenUrlWithScopes_multiple_scopes() { + @Test void buildTokenUrlWithScopes_multiple_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(Arrays.asList(null, "foo", "", "bar")) @@ -179,8 +173,7 @@ public void buildTokenUrlWithScopes_multiple_scopes() { assertEquals("bar", scopes.toArray()[1]); } - @Test - public void buildTokenUrlWithScopes_defaultScopes() { + @Test void buildTokenUrlWithScopes_defaultScopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().build(); credentials = (ComputeEngineCredentials) @@ -194,8 +187,7 @@ public void buildTokenUrlWithScopes_defaultScopes() { assertEquals("bar", scopes.toArray()[1]); } - @Test - public void buildTokenUrl_nullTransport() { + @Test void buildTokenUrl_nullTransport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(null) @@ -206,8 +198,7 @@ public void buildTokenUrl_nullTransport() { assertEquals(TOKEN_URL + "?binding-enforcement=on", tokenUrl); } - @Test - public void buildTokenUrl_nullBindingEnforcement() { + @Test void buildTokenUrl_nullBindingEnforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -218,8 +209,7 @@ public void buildTokenUrl_nullBindingEnforcement() { assertEquals(TOKEN_URL + "?transport=mtls", tokenUrl); } - @Test - public void buildTokenUrl_nullTransport_nullBindingEnforcement() { + @Test void buildTokenUrl_nullTransport_nullBindingEnforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(null) @@ -230,8 +220,7 @@ public void buildTokenUrl_nullTransport_nullBindingEnforcement() { assertEquals(TOKEN_URL, softBoundTokenUrl); } - @Test - public void buildTokenUrl_mtls_transport() { + @Test void buildTokenUrl_mtls_transport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -241,8 +230,7 @@ public void buildTokenUrl_mtls_transport() { assertEquals(TOKEN_URL + "?transport=mtls", tokenUrl); } - @Test - public void buildTokenUrl_iam_enforcement() { + @Test void buildTokenUrl_iam_enforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setBindingEnforcement(ComputeEngineCredentials.BindingEnforcement.IAM_POLICY) @@ -252,8 +240,7 @@ public void buildTokenUrl_iam_enforcement() { assertEquals(TOKEN_URL + "?binding-enforcement=iam-policy", tokenUrl); } - @Test - public void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { + @Test void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -264,8 +251,7 @@ public void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { assertEquals(TOKEN_URL + "?transport=mtls&binding-enforcement=iam-policy", softBoundTokenUrl); } - @Test - public void buildTokenUrl_always_enforced() { + @Test void buildTokenUrl_always_enforced() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setBindingEnforcement(ComputeEngineCredentials.BindingEnforcement.ON) @@ -275,8 +261,7 @@ public void buildTokenUrl_always_enforced() { assertEquals(TOKEN_URL + "?binding-enforcement=on", tokenUrl); } - @Test - public void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { + @Test void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -287,8 +272,7 @@ public void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { assertEquals(TOKEN_URL + "?transport=mtls&binding-enforcement=on", hardBoundTokenUrl); } - @Test - public void buildTokenUrlHardDirectPathBound_alts_transport() { + @Test void buildTokenUrlHardDirectPathBound_alts_transport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.ALTS) @@ -298,8 +282,7 @@ public void buildTokenUrlHardDirectPathBound_alts_transport() { assertEquals(TOKEN_URL + "?transport=alts", hardBoundTokenUrl); } - @Test - public void buildScoped_scopesPresent() throws IOException { + @Test void buildScoped_scopesPresent() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials scopedCredentials = @@ -310,8 +293,7 @@ public void buildScoped_scopesPresent() throws IOException { assertEquals("foo", scopes.toArray()[0]); } - @Test - public void buildScoped_correctMargins() throws IOException { + @Test void buildScoped_correctMargins() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials scopedCredentials = @@ -324,8 +306,7 @@ public void buildScoped_correctMargins() throws IOException { ComputeEngineCredentials.COMPUTE_REFRESH_MARGIN, scopedCredentials.getRefreshMargin()); } - @Test - public void buildScoped_explicitUniverse() throws IOException { + @Test void buildScoped_explicitUniverse() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -338,8 +319,7 @@ public void buildScoped_explicitUniverse() throws IOException { assertTrue(scopedCredentials.isExplicitUniverseDomain()); } - @Test - public void createScoped_defaultScopes() { + @Test void createScoped_defaultScopes() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); Collection scopes = ((ComputeEngineCredentials) credentials).getScopes(); @@ -348,8 +328,7 @@ public void createScoped_defaultScopes() { assertEquals("foo", scopes.toArray()[0]); } - @Test - public void buildScoped_quotaProjectId() throws IOException { + @Test void buildScoped_quotaProjectId() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -361,8 +340,7 @@ public void buildScoped_quotaProjectId() throws IOException { assertEquals("some-project-id", scopedCredentials.getQuotaProjectId()); } - @Test - public void buildDefaultScoped_explicitUniverse() throws IOException { + @Test void buildDefaultScoped_explicitUniverse() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -375,8 +353,7 @@ public void buildDefaultScoped_explicitUniverse() throws IOException { assertTrue(scopedCredentials.isExplicitUniverseDomain()); } - @Test - public void create_scoped_correctMargins() { + @Test void create_scoped_correctMargins() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); @@ -385,8 +362,7 @@ public void create_scoped_correctMargins() { assertEquals(ComputeEngineCredentials.COMPUTE_REFRESH_MARGIN, credentials.getRefreshMargin()); } - @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + @Test void getRequestMetadata_hasAccessToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); ComputeEngineCredentials credentials = @@ -401,8 +377,7 @@ public void getRequestMetadata_hasAccessToken() throws IOException { assertTrue(requestHeaders.get("metadata-flavor").contains("Google")); } - @Test - public void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTokenFromRefresh() + @Test void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTokenFromRefresh() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -422,8 +397,7 @@ public void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTo TestUtils.assertNotContainsBearerToken(metadataForCopiedCredentials, ACCESS_TOKEN); } - @Test - public void getRequestMetadata_missingServiceAccount_throws() { + @Test void getRequestMetadata_missingServiceAccount_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -440,8 +414,7 @@ public void getRequestMetadata_missingServiceAccount_throws() { } } - @Test - public void getRequestMetadata_serverError_throws() { + @Test void getRequestMetadata_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -457,8 +430,7 @@ public void getRequestMetadata_serverError_throws() { } } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials explicitUniverseCredentials = ComputeEngineCredentials.newBuilder() @@ -479,8 +451,7 @@ public void equals_true() throws IOException { assertTrue(otherExplicitUniverseCredentials.equals(explicitUniverseCredentials)); } - @Test - public void equals_false_transportFactory() throws IOException { + @Test void equals_false_transportFactory() throws IOException { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); @@ -494,8 +465,7 @@ public void equals_false_transportFactory() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_explicit_containsFields() throws IOException { + @Test void toString_explicit_containsFields() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); String expectedToString = @@ -516,8 +486,7 @@ public void toString_explicit_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -531,8 +500,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void toBuilder() { + @Test void toBuilder() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setHttpTransportFactory(new MockMetadataServerTransportFactory()) @@ -544,8 +512,7 @@ public void toBuilder() { assertEquals(credentials, secondCredentials); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -565,8 +532,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test - public void getAccount_sameAs() throws IOException { + @Test void getAccount_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -581,8 +547,7 @@ public void getAccount_sameAs() throws IOException { assertFalse(headers.containsKey(MetricsUtils.API_CLIENT_HEADER)); } - @Test - public void getAccount_missing_throws() { + @Test void getAccount_missing_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -617,8 +582,7 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test - public void getAccount_emptyContent_throws() { + @Test void getAccount_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -652,8 +616,7 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test - public void sign_sameAs() { + @Test void sign_sameAs() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -666,8 +629,7 @@ public void sign_sameAs() { assertArrayEquals(expectedSignature, credentials.sign(expectedSignature)); } - @Test - public void sign_getUniverseException() { + @Test void sign_getUniverseException() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -676,16 +638,15 @@ public void sign_getUniverseException() { ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); transportFactory.transport.setStatusCode(501); - Assert.assertThrows(IOException.class, credentials::getUniverseDomain); + assertThrows(IOException.class, credentials::getUniverseDomain); byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; SigningException signingException = - Assert.assertThrows(SigningException.class, () -> credentials.sign(expectedSignature)); + assertThrows(SigningException.class, () -> credentials.sign(expectedSignature)); assertEquals("Failed to sign: Error obtaining universe domain", signingException.getMessage()); } - @Test - public void sign_getAccountFails() { + @Test void sign_getAccountFails() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -694,13 +655,12 @@ public void sign_getAccountFails() { ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); SigningException exception = - Assert.assertThrows(SigningException.class, () -> credentials.sign(expectedSignature)); + assertThrows(SigningException.class, () -> credentials.sign(expectedSignature)); assertNotNull(exception.getMessage()); assertNotNull(exception.getCause()); } - @Test - public void sign_accessDenied_throws() { + @Test void sign_accessDenied_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -731,14 +691,13 @@ public LowLevelHttpResponse execute() throws IOException { byte[] bytes = {0xD, 0xE, 0xA, 0xD}; SigningException exception = - Assert.assertThrows(SigningException.class, () -> credentials.sign(bytes)); + assertThrows(SigningException.class, () -> credentials.sign(bytes)); assertEquals("Failed to sign the provided bytes", exception.getMessage()); assertNotNull(exception.getCause()); assertTrue(exception.getCause().getMessage().contains("403")); } - @Test - public void sign_serverError_throws() { + @Test void sign_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -769,14 +728,13 @@ public LowLevelHttpResponse execute() throws IOException { byte[] bytes = {0xD, 0xE, 0xA, 0xD}; SigningException exception = - Assert.assertThrows(SigningException.class, () -> credentials.sign(bytes)); + assertThrows(SigningException.class, () -> credentials.sign(bytes)); assertEquals("Failed to sign the provided bytes", exception.getMessage()); assertNotNull(exception.getCause()); assertTrue(exception.getCause().getMessage().contains("500")); } - @Test - public void refresh_503_retryable_throws() { + @Test void refresh_503_retryable_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -798,14 +756,13 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); IOException exception = - Assert.assertThrows(IOException.class, () -> credentials.refreshAccessToken()); + assertThrows(IOException.class, () -> credentials.refreshAccessToken()); assertTrue(exception.getCause().getMessage().contains("503")); assertTrue(exception instanceof GoogleAuthException); assertTrue(((GoogleAuthException) exception).isRetryable()); } - @Test - public void refresh_non503_ioexception_throws() { + @Test void refresh_non503_ioexception_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final Queue responseSequence = new ArrayDeque<>(); IntStream.rangeClosed(400, 600).forEach(i -> responseSequence.add(i)); @@ -835,13 +792,12 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); IOException exception = - Assert.assertThrows(IOException.class, () -> credentials.refreshAccessToken()); + assertThrows(IOException.class, () -> credentials.refreshAccessToken()); assertFalse(exception instanceof GoogleAuthException); } } - @Test - public void getUniverseDomain_fromMetadata() throws IOException { + @Test void getUniverseDomain_fromMetadata() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -867,8 +823,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test - public void getUniverseDomain_fromMetadata_emptyBecomesDefault() throws IOException { + @Test void getUniverseDomain_fromMetadata_emptyBecomesDefault() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -894,8 +849,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test - public void getUniverseDomain_fromMetadata_404_default() throws IOException { + @Test void getUniverseDomain_fromMetadata_404_default() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -921,8 +875,7 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test - public void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { + @Test void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); @@ -938,8 +891,7 @@ public void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { assertEquals(0, transportFactory.transport.getRequestCount()); } - @Test - public void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { + @Test void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); @@ -955,8 +907,7 @@ public void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { assertEquals(0, transportFactory.transport.getRequestCount()); } - @Test - public void getUniverseDomain_fromMetadata_non404error_throws() throws IOException { + @Test void getUniverseDomain_fromMetadata_non404error_throws() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); MockMetadataServerTransport transport = transportFactory.transport; @@ -978,8 +929,7 @@ public void getUniverseDomain_fromMetadata_non404error_throws() throws IOExcepti } } - @Test - public void sign_emptyContent_throws() { + @Test void sign_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -1009,14 +959,13 @@ public LowLevelHttpResponse execute() throws IOException { byte[] bytes = {0xD, 0xE, 0xA, 0xD}; SigningException exception = - Assert.assertThrows(SigningException.class, () -> credentials.sign(bytes)); + assertThrows(SigningException.class, () -> credentials.sign(bytes)); assertEquals("Failed to sign the provided bytes", exception.getMessage()); assertNotNull(exception.getCause()); assertTrue(exception.getCause().getMessage().contains("Empty content")); } - @Test - public void idTokenWithAudience_sameAs() throws IOException { + @Test void idTokenWithAudience_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(STANDARD_ID_TOKEN); ComputeEngineCredentials credentials = @@ -1036,8 +985,7 @@ public void idTokenWithAudience_sameAs() throws IOException { (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test - public void idTokenWithAudience_standard() throws IOException { + @Test void idTokenWithAudience_standard() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -1056,7 +1004,7 @@ public void idTokenWithAudience_standard() throws IOException { @Test @SuppressWarnings("unchecked") - public void idTokenWithAudience_full() throws IOException { + void idTokenWithAudience_full() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -1070,7 +1018,7 @@ public void idTokenWithAudience_full() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - assertTrue("Full ID Token format not provided", p.containsKey("google")); + assertTrue(p.containsKey("google"), "Full ID Token format not provided"); ArrayMap> googleClaim = (ArrayMap>) p.get("google"); assertTrue(googleClaim.containsKey("compute_engine")); @@ -1082,7 +1030,7 @@ public void idTokenWithAudience_full() throws IOException { @Test @SuppressWarnings("unchecked") - public void idTokenWithAudience_licenses() throws IOException { + void idTokenWithAudience_licenses() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -1098,7 +1046,7 @@ public void idTokenWithAudience_licenses() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - assertTrue("Full ID Token format not provided", p.containsKey("google")); + assertTrue(p.containsKey("google"), "Full ID Token format not provided"); ArrayMap> googleClaim = (ArrayMap>) p.get("google"); assertTrue(googleClaim.containsKey("compute_engine")); @@ -1107,8 +1055,7 @@ public void idTokenWithAudience_licenses() throws IOException { assertTrue(computeEngineClaim.containsKey("license_id")); } - @Test - public void idTokenWithAudience_404StatusCode() { + @Test void idTokenWithAudience_404StatusCode() { int statusCode = HttpStatusCodes.STATUS_CODE_NOT_FOUND; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); @@ -1125,8 +1072,7 @@ public void idTokenWithAudience_404StatusCode() { exception.getMessage()); } - @Test - public void idTokenWithAudience_emptyContent() { + @Test void idTokenWithAudience_emptyContent() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setEmptyContent(true); ComputeEngineCredentials credentials = @@ -1136,8 +1082,7 @@ public void idTokenWithAudience_emptyContent() { assertEquals(METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE, exception.getMessage()); } - @Test - public void idTokenWithAudience_503StatusCode() { + @Test void idTokenWithAudience_503StatusCode() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE); ComputeEngineCredentials credentials = @@ -1156,4 +1101,4 @@ public HttpTransport create() { return transport; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java index ac042e065..19381be15 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java @@ -31,25 +31,21 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import com.google.auth.oauth2.CredentialAccessBoundary.AccessBoundaryRule; import com.google.auth.oauth2.CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link CredentialAccessBoundary} and encompassing classes. */ -@RunWith(JUnit4.class) -public class CredentialAccessBoundaryTest { - @Test - public void credentialAccessBoundary() { +class CredentialAccessBoundaryTest { + + @Test void credentialAccessBoundary() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -91,8 +87,7 @@ public void credentialAccessBoundary() { assertNull(second.getAvailabilityCondition()); } - @Test - public void credentialAccessBoundary_nullRules_throws() { + @Test void credentialAccessBoundary_nullRules_throws() { try { CredentialAccessBoundary.newBuilder().build(); fail("Should fail."); @@ -101,8 +96,7 @@ public void credentialAccessBoundary_nullRules_throws() { } } - @Test - public void credentialAccessBoundary_withoutRules_throws() { + @Test void credentialAccessBoundary_withoutRules_throws() { try { CredentialAccessBoundary.newBuilder().setRules(new ArrayList()).build(); fail("Should fail."); @@ -111,8 +105,7 @@ public void credentialAccessBoundary_withoutRules_throws() { } } - @Test - public void credentialAccessBoundary_ruleCountExceeded_throws() { + @Test void credentialAccessBoundary_ruleCountExceeded_throws() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -132,8 +125,7 @@ public void credentialAccessBoundary_ruleCountExceeded_throws() { } } - @Test - public void credentialAccessBoundary_toJson() { + @Test void credentialAccessBoundary_toJson() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -171,8 +163,7 @@ public void credentialAccessBoundary_toJson() { assertEquals(expectedJson, credentialAccessBoundary.toJson()); } - @Test - public void accessBoundaryRule_allFields() { + @Test void accessBoundaryRule_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -191,8 +182,7 @@ public void accessBoundaryRule_allFields() { assertEquals(availabilityCondition, rule.getAvailabilityCondition()); } - @Test - public void accessBoundaryRule_requiredFields() { + @Test void accessBoundaryRule_requiredFields() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -205,8 +195,7 @@ public void accessBoundaryRule_requiredFields() { assertNull(rule.getAvailabilityCondition()); } - @Test - public void accessBoundaryRule_withEmptyAvailableResource_throws() { + @Test void accessBoundaryRule_withEmptyAvailableResource_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("") @@ -218,8 +207,7 @@ public void accessBoundaryRule_withEmptyAvailableResource_throws() { } } - @Test - public void accessBoundaryRule_withoutAvailableResource_throws() { + @Test void accessBoundaryRule_withoutAvailableResource_throws() { try { AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(); fail("Should fail."); @@ -228,8 +216,7 @@ public void accessBoundaryRule_withoutAvailableResource_throws() { } } - @Test - public void accessBoundaryRule_withoutAvailablePermissions_throws() { + @Test void accessBoundaryRule_withoutAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(); fail("Should fail."); @@ -238,8 +225,7 @@ public void accessBoundaryRule_withoutAvailablePermissions_throws() { } } - @Test - public void accessBoundaryRule_withEmptyAvailablePermissions_throws() { + @Test void accessBoundaryRule_withEmptyAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -251,8 +237,7 @@ public void accessBoundaryRule_withEmptyAvailablePermissions_throws() { } } - @Test - public void accessBoundaryRule_withNullAvailablePermissions_throws() { + @Test void accessBoundaryRule_withNullAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -264,8 +249,7 @@ public void accessBoundaryRule_withNullAvailablePermissions_throws() { } } - @Test - public void accessBoundaryRule_withEmptyAvailablePermission_throws() { + @Test void accessBoundaryRule_withEmptyAvailablePermission_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -277,8 +261,7 @@ public void accessBoundaryRule_withEmptyAvailablePermission_throws() { } } - @Test - public void availabilityCondition_allFields() { + @Test void availabilityCondition_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -291,8 +274,7 @@ public void availabilityCondition_allFields() { assertEquals("description", availabilityCondition.getDescription()); } - @Test - public void availabilityCondition_expressionOnly() { + @Test void availabilityCondition_expressionOnly() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -301,8 +283,7 @@ public void availabilityCondition_expressionOnly() { assertNull(availabilityCondition.getDescription()); } - @Test - public void availabilityCondition_nullExpression_throws() { + @Test void availabilityCondition_nullExpression_throws() { try { AvailabilityCondition.newBuilder().setExpression(null).build(); fail("Should fail."); @@ -311,8 +292,7 @@ public void availabilityCondition_nullExpression_throws() { } } - @Test - public void availabilityCondition_emptyExpression_throws() { + @Test void availabilityCondition_emptyExpression_throws() { try { AvailabilityCondition.newBuilder().setExpression("").build(); fail("Should fail."); @@ -320,4 +300,4 @@ public void availabilityCondition_emptyExpression_throws() { assertEquals("The provided expression is empty.", e.getMessage()); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java index cb6f5a8cc..6d8a99407 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java @@ -31,14 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; @@ -65,13 +64,11 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link DefaultCredentialsProvider}. */ -@RunWith(JUnit4.class) -public class DefaultCredentialsProviderTest { + +class DefaultCredentialsProviderTest { private static final String USER_CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String USER_CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -105,8 +102,7 @@ public class DefaultCredentialsProviderTest { private static final String QUOTA_PROJECT_EXPLICIT = "explicit-quota-project-id"; private static final String SMBIOS_PATH_LINUX = "/sys/class/dmi/id/product_name"; - @Test - public void getDefaultCredentials_noCredentials_throws() { + @Test void getDefaultCredentials_noCredentials_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -119,8 +115,7 @@ public void getDefaultCredentials_noCredentials_throws() { } } - @Test - public void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { + @Test void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setFileSandbox(true); @@ -134,8 +129,7 @@ public void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { } } - @Test - public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { + @Test void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -155,8 +149,7 @@ public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exc } } - @Test - public void getDefaultCredentials_noCredentials_singleGceTestRequest() { + @Test void getDefaultCredentials_noCredentials_singleGceTestRequest() { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -182,8 +175,7 @@ public void getDefaultCredentials_noCredentials_singleGceTestRequest() { ComputeEngineCredentials.MAX_COMPUTE_PING_TRIES); } - @Test - public void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException { + @Test void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "Linux"); String productFilePath = SMBIOS_PATH_LINUX; @@ -193,8 +185,7 @@ public void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException assertFalse(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test - public void getDefaultCredentials_static_linux() throws IOException { + @Test void getDefaultCredentials_static_linux() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "Linux"); String productFilePath = SMBIOS_PATH_LINUX; @@ -205,8 +196,7 @@ public void getDefaultCredentials_static_linux() throws IOException { assertTrue(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test - public void getDefaultCredentials_static_windows_configuredAsLinux_notGce() throws IOException { + @Test void getDefaultCredentials_static_windows_configuredAsLinux_notGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "windows"); String productFilePath = SMBIOS_PATH_LINUX; @@ -216,8 +206,7 @@ public void getDefaultCredentials_static_windows_configuredAsLinux_notGce() thro assertFalse(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test - public void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOException { + @Test void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "macos"); String productFilePath = SMBIOS_PATH_LINUX; @@ -227,8 +216,7 @@ public void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOE assertFalse(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test - public void checkGcpLinuxPlatformData() throws Exception { + @Test void checkGcpLinuxPlatformData() throws Exception { BufferedReader reader; reader = new BufferedReader(new StringReader("HP Z440 Workstation")); assertFalse(ComputeEngineCredentials.checkProductNameOnLinux(reader)); @@ -240,8 +228,7 @@ public void checkGcpLinuxPlatformData() throws Exception { assertTrue(ComputeEngineCredentials.checkProductNameOnLinux(reader)); } - @Test - public void getDefaultCredentials_caches() throws IOException { + @Test void getDefaultCredentials_caches() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -252,8 +239,7 @@ public void getDefaultCredentials_caches() throws IOException { assertSame(firstCall, secondCall); } - @Test - public void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { + @Test void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -269,8 +255,7 @@ public void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { } } - @Test - public void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { + @Test void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -287,8 +272,7 @@ public void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoad } } - @Test - public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() + @Test void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -302,8 +286,7 @@ public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredenti assertTrue(credentials instanceof CloudShellCredentials); } - @Test - public void getDefaultCredentials_compute_providesToken() throws IOException { + @Test void getDefaultCredentials_compute_providesToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -315,8 +298,7 @@ public void getDefaultCredentials_compute_providesToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void getDefaultCredentials_cloudshell() throws IOException { + @Test void getDefaultCredentials_cloudshell() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -327,8 +309,7 @@ public void getDefaultCredentials_cloudshell() throws IOException { assertEquals(((CloudShellCredentials) defaultCredentials).getAuthPort(), 4); } - @Test - public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { + @Test void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -339,8 +320,7 @@ public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() thro assertEquals(((CloudShellCredentials) defaultCredentials).getAuthPort(), 4); } - @Test - public void getDefaultCredentials_envMissingFile_throws() { + @Test void getDefaultCredentials_envMissingFile_throws() { final String invalidPath = "/invalid/path"; MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -356,8 +336,7 @@ public void getDefaultCredentials_envMissingFile_throws() { } } - @Test - public void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { + @Test void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -376,8 +355,7 @@ public void getDefaultCredentials_envServiceAccount_providesToken() throws IOExc TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void getDefaultCredentials_envUser_providesToken() throws IOException { + @Test void getDefaultCredentials_envUser_providesToken() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -389,8 +367,7 @@ public void getDefaultCredentials_envUser_providesToken() throws IOException { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test - public void getDefaultCredentials_GdchServiceAccount() throws IOException { + @Test void getDefaultCredentials_GdchServiceAccount() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( @@ -433,7 +410,7 @@ public void getDefaultCredentials_GdchServiceAccount() throws IOException { assertNotNull(((GdchCredentials) defaultCredentials).getApiAudience()); } - public void getDefaultCredentials_quota_project() throws IOException { + void getDefaultCredentials_quota_project() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -458,8 +435,7 @@ public void getDefaultCredentials_quota_project() throws IOException { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test - public void getDefaultCredentials_compute_quotaProject() throws IOException { + @Test void getDefaultCredentials_compute_quotaProject() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv( @@ -476,8 +452,7 @@ public void getDefaultCredentials_compute_quotaProject() throws IOException { assertEquals("Google", headers.get("metadata-flavor").get(0)); } - @Test - public void getDefaultCredentials_cloudshell_quotaProject() throws IOException { + @Test void getDefaultCredentials_cloudshell_quotaProject() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -490,8 +465,7 @@ public void getDefaultCredentials_cloudshell_quotaProject() throws IOException { assertEquals(QUOTA_PROJECT_FROM_ENVIRONMENT, defaultCredentials.getQuotaProjectId()); } - @Test - public void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { + @Test void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -506,8 +480,7 @@ public void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOExceptio assertEquals(transportFactory.transport.getRequestCount(), 0); } - @Test - public void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOException { + @Test void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -526,16 +499,14 @@ public void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOExce assertEquals(transportFactory.transport.getRequestCount(), 0); } - @Test - public void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { + @Test void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); assertEquals(ComputeEngineCredentials.getMetadataServerUrl(testProvider), "http://" + testUrl); } - @Test - public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { + @Test void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -544,8 +515,7 @@ public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { "http://" + testUrl + "/computeMetadata/v1/instance/service-accounts/default/token"); } - @Test - public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { + @Test void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -559,8 +529,7 @@ public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOExce testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test - public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { + @Test void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File configDir = new File(homeDir, ".config"); File cloudConfigDir = new File(configDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); @@ -577,8 +546,7 @@ public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test - public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { + @Test void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File cloudConfigDir = new File(homeDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); InputStream userStream = @@ -594,8 +562,7 @@ public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IO testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test - public void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { + @Test void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { final String refreshTokenEnv = "2/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; final String accessTokenEnv = "2/MkSJoj1xsli0AccessToken_NKPY2"; final String refreshTokenWkf = "3/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @@ -652,8 +619,7 @@ public void close() {} public void flush() {} } - @Test - public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { + @Test void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false, true); assertNotNull(message); assertEquals(Level.WARNING, message.getLevel()); @@ -661,14 +627,12 @@ public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOExc message.getMessage().equals(DefaultCredentialsProvider.CLOUDSDK_CREDENTIALS_WARNING)); } - @Test - public void getDefaultCredentials_wellKnownFile_noGcloudWarning() throws IOException { + @Test void getDefaultCredentials_wellKnownFile_noGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false, false); assertNull(message); } - @Test - public void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { + @Test void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(true, true); assertNull(message); } @@ -743,8 +707,7 @@ public AccessToken refreshAccessToken() throws IOException { } } - @Test - public void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredentialInfo() + @Test void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredentialInfo() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); @@ -770,8 +733,7 @@ public void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCre assertEquals(SA_CLIENT_EMAIL, credentialInfo.get("Principal")); } - @Test - public void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo() + @Test void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( @@ -796,8 +758,7 @@ public void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo assertNull(credentialInfo.get("Principal")); } - @Test - public void getDefaultCredentials_wellKnownFile_userCredential_correctCredentialInfo() + @Test void getDefaultCredentials_wellKnownFile_userCredential_correctCredentialInfo() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = @@ -823,8 +784,7 @@ public void getDefaultCredentials_wellKnownFile_userCredential_correctCredential assertNull(credentialInfo.get("Principal")); } - @Test - public void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correctCredentialInfo() + @Test void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correctCredentialInfo() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -843,8 +803,7 @@ public void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correct assertNull(credentialInfo.get("Principal")); } - @Test - public void getDefaultCredentials_computeEngineCredentials_customMDSUrl_correctCredentialInfo() + @Test void getDefaultCredentials_computeEngineCredentials_customMDSUrl_correctCredentialInfo() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -1030,4 +989,4 @@ public HttpTransport create() { return transport; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java index 5f452bfd7..95ccf5295 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java @@ -31,20 +31,15 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public final class DefaultPKCEProviderTest { - @Test - public void testPkceExpected() throws NoSuchAlgorithmException { +final class DefaultPKCEProviderTest { + @Test void testPkceExpected() throws NoSuchAlgorithmException { PKCEProvider pkce = new DefaultPKCEProvider(); byte[] bytes = pkce.getCodeVerifier().getBytes(); @@ -60,10 +55,9 @@ public void testPkceExpected() throws NoSuchAlgorithmException { assertEquals(pkce.getCodeChallengeMethod(), expectedCodeChallengeMethod); } - @Test - public void testNoBase64Padding() throws NoSuchAlgorithmException { + @Test void testNoBase64Padding() throws NoSuchAlgorithmException { PKCEProvider pkce = new DefaultPKCEProvider(); assertFalse(pkce.getCodeChallenge().endsWith("=")); assertFalse(pkce.getCodeChallenge().contains("=")); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index d054d7ee6..e50460d84 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.auth.TestUtils; @@ -43,13 +43,11 @@ import java.io.IOException; import java.util.Date; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link DownscopedCredentials}. */ -@RunWith(JUnit4.class) -public class DownscopedCredentialsTest { + +class DownscopedCredentialsTest { private static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n" @@ -84,8 +82,7 @@ public HttpTransport create() { } } - @Test - public void refreshAccessToken() throws IOException { + @Test void refreshAccessToken() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -115,8 +112,7 @@ public void refreshAccessToken() throws IOException { assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, GOOGLE_DEFAULT_UNIVERSE)); } - @Test - public void refreshAccessToken_withCustomUniverseDomain() throws IOException { + @Test void refreshAccessToken_withCustomUniverseDomain() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); String universeDomain = "foobar"; GoogleCredentials sourceCredentials = @@ -149,8 +145,7 @@ public void refreshAccessToken_withCustomUniverseDomain() throws IOException { assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain)); } - @Test - public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { + @Test void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { // STS only returns expires_in if the source access token belongs to a service account. // For other source credential types, we can copy the source credentials expiration as // the generated downscoped token will always have the same expiration time as the source @@ -177,8 +172,7 @@ public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IO sourceCredentials.getAccessToken().getExpirationTime(), accessToken.getExpirationTime()); } - @Test - public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { + @Test void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -199,8 +193,7 @@ public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOEx } } - @Test - public void builder_noSourceCredential_throws() { + @Test void builder_noSourceCredential_throws() { try { DownscopedCredentials.newBuilder() .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) @@ -212,8 +205,7 @@ public void builder_noSourceCredential_throws() { } } - @Test - public void builder_noCredentialAccessBoundary_throws() throws IOException { + @Test void builder_noCredentialAccessBoundary_throws() throws IOException { try { DownscopedCredentials.newBuilder() .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) @@ -225,8 +217,7 @@ public void builder_noCredentialAccessBoundary_throws() throws IOException { } } - @Test - public void builder_noTransport_defaults() throws IOException { + @Test void builder_noTransport_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = @@ -242,8 +233,7 @@ public void builder_noTransport_defaults() throws IOException { assertEquals(OAuth2Utils.HTTP_TRANSPORT_FACTORY, credentials.getTransportFactory()); } - @Test - public void builder_noUniverseDomain_defaults() throws IOException { + @Test void builder_noUniverseDomain_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = @@ -261,8 +251,7 @@ public void builder_noUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void builder_universeDomainMismatch_throws() throws IOException { + @Test void builder_universeDomainMismatch_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); @@ -281,8 +270,7 @@ public void builder_universeDomainMismatch_throws() throws IOException { } } - @Test - public void builder_sourceUniverseDomainUnavailable_throws() throws IOException { + @Test void builder_sourceUniverseDomainUnavailable_throws() throws IOException { GoogleCredentials sourceCredentials = new MockSourceCredentialWithoutUniverseDomain(); try { @@ -343,4 +331,4 @@ public String getUniverseDomain() throws IOException { throw new IOException(); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java index e6991776d..86af78f0e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java @@ -31,20 +31,19 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.GenericJson; import java.io.IOException; import java.math.BigDecimal; import java.time.Instant; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link ExecutableResponse}. */ -public class ExecutableResponseTest { +class ExecutableResponseTest { private static final String TOKEN_TYPE_OIDC = "urn:ietf:params:oauth:token-type:id_token"; private static final String TOKEN_TYPE_SAML = "urn:ietf:params:oauth:token-type:saml2"; @@ -54,8 +53,7 @@ public class ExecutableResponseTest { private static final int EXECUTABLE_SUPPORTED_MAX_VERSION = 1; private static final int EXPIRATION_DURATION = 3600; - @Test - public void constructor_successOidcResponse() throws IOException { + @Test void constructor_successOidcResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildOidcResponse()); assertTrue(response.isSuccessful()); @@ -67,8 +65,7 @@ public void constructor_successOidcResponse() throws IOException { Instant.now().getEpochSecond() + EXPIRATION_DURATION, (long) response.getExpirationTime()); } - @Test - public void constructor_successOidcResponseMissingExpirationTimeField_notExpired() + @Test void constructor_successOidcResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("expiration_time"); @@ -84,8 +81,7 @@ public void constructor_successOidcResponseMissingExpirationTimeField_notExpired assertNull(response.getExpirationTime()); } - @Test - public void constructor_successSamlResponse() throws IOException { + @Test void constructor_successSamlResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildSamlResponse()); assertTrue(response.isSuccessful()); @@ -97,8 +93,7 @@ public void constructor_successSamlResponse() throws IOException { Instant.now().getEpochSecond() + EXPIRATION_DURATION, (long) response.getExpirationTime()); } - @Test - public void constructor_successSamlResponseMissingExpirationTimeField_notExpired() + @Test void constructor_successSamlResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildSamlResponse(); jsonResponse.remove("expiration_time"); @@ -114,8 +109,7 @@ public void constructor_successSamlResponseMissingExpirationTimeField_notExpired assertNull(response.getExpirationTime()); } - @Test - public void constructor_validErrorResponse() throws IOException { + @Test void constructor_validErrorResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildErrorResponse()); assertFalse(response.isSuccessful()); @@ -129,8 +123,7 @@ public void constructor_validErrorResponse() throws IOException { assertEquals("Caller not authorized.", response.getErrorMessage()); } - @Test - public void constructor_errorResponseMissingCode_throws() throws IOException { + @Test void constructor_errorResponseMissingCode_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; @@ -148,8 +141,7 @@ public void constructor_errorResponseMissingCode_throws() throws IOException { } } - @Test - public void constructor_errorResponseMissingMessage_throws() throws IOException { + @Test void constructor_errorResponseMissingMessage_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; @@ -168,8 +160,7 @@ public void constructor_errorResponseMissingMessage_throws() throws IOException } } - @Test - public void constructor_successResponseMissingVersionField_throws() throws IOException { + @Test void constructor_successResponseMissingVersionField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("version"); @@ -184,8 +175,7 @@ public void constructor_successResponseMissingVersionField_throws() throws IOExc } } - @Test - public void constructor_successResponseMissingSuccessField_throws() throws Exception { + @Test void constructor_successResponseMissingSuccessField_throws() throws Exception { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("success"); @@ -200,8 +190,7 @@ public void constructor_successResponseMissingSuccessField_throws() throws Excep } } - @Test - public void constructor_successResponseMissingTokenTypeField_throws() throws IOException { + @Test void constructor_successResponseMissingTokenTypeField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("token_type"); @@ -216,8 +205,7 @@ public void constructor_successResponseMissingTokenTypeField_throws() throws IOE } } - @Test - public void constructor_samlResponseMissingSubjectToken_throws() throws IOException { + @Test void constructor_samlResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildSamlResponse(); Object[] values = new Object[] {null, ""}; @@ -236,8 +224,7 @@ public void constructor_samlResponseMissingSubjectToken_throws() throws IOExcept } } - @Test - public void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { + @Test void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); Object[] values = new Object[] {null, ""}; @@ -256,8 +243,7 @@ public void constructor_oidcResponseMissingSubjectToken_throws() throws IOExcept } } - @Test - public void isExpired() throws IOException { + @Test void isExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); BigDecimal[] values = @@ -307,4 +293,4 @@ private static GenericJson buildErrorResponse() { json.put("message", "Caller not authorized."); return json; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java index 8328ac54d..b3549b6e0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java @@ -31,14 +31,15 @@ package com.google.auth.oauth2; +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.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 static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -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 com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -62,14 +63,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Test case for {@link ExternalAccountAuthorizedUserCredentials}. */ -@RunWith(JUnit4.class) -public class ExternalAccountAuthorizedUserCredentialsTest extends BaseSerializationTest { + +class ExternalAccountAuthorizedUserCredentialsTest extends BaseSerializationTest { private static final String AUDIENCE = "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID"; @@ -127,13 +126,11 @@ public HttpTransport create() { } } - @Before - public void setup() { + @BeforeEach void setup() { transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); } - @Test - public void builder_allFields() throws IOException { + @Test void builder_allFields() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -160,8 +157,7 @@ public void builder_allFields() throws IOException { assertEquals(UNIVERSE_DOMAIN, credentials.getUniverseDomain()); } - @Test - public void builder_minimumRequiredFieldsForRefresh() { + @Test void builder_minimumRequiredFieldsForRefresh() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -181,8 +177,7 @@ public void builder_minimumRequiredFieldsForRefresh() { assertNull(credentials.getQuotaProjectId()); } - @Test - public void builder_accessTokenOnly() { + @Test void builder_accessTokenOnly() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAccessToken(AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build()) @@ -199,8 +194,7 @@ public void builder_accessTokenOnly() { assertNull(credentials.getQuotaProjectId()); } - @Test - public void builder_credentialConstructor() { + @Test void builder_credentialConstructor() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -225,8 +219,7 @@ public void builder_credentialConstructor() { assertEquals(QUOTA_PROJECT, otherCredentials.getQuotaProjectId()); } - @Test - public void builder_accessTokenWithMissingRefreshFields() { + @Test void builder_accessTokenWithMissingRefreshFields() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAccessToken(AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build()) @@ -246,8 +239,7 @@ public void builder_accessTokenWithMissingRefreshFields() { assertNull(credentials.getQuotaProjectId()); } - @Test - public void builder_accessAndRefreshTokenNull_throws() { + @Test void builder_accessAndRefreshTokenNull_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder().build(); fail("Should not be able to continue without exception."); @@ -260,8 +252,7 @@ public void builder_accessAndRefreshTokenNull_throws() { } } - @Test - public void builder_missingTokenUrl_throws() { + @Test void builder_missingTokenUrl_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -278,8 +269,7 @@ public void builder_missingTokenUrl_throws() { } } - @Test - public void builder_missingClientId_throws() { + @Test void builder_missingClientId_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -296,8 +286,7 @@ public void builder_missingClientId_throws() { } } - @Test - public void builder_missingClientSecret_throws() { + @Test void builder_missingClientSecret_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -314,8 +303,7 @@ public void builder_missingClientSecret_throws() { } } - @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + @Test void builder_missingUniverseDomain_defaults() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -341,8 +329,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void toBuilder_allFields() { + @Test void toBuilder_allFields() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -362,8 +349,7 @@ public void toBuilder_allFields() { assertEquals(credentials, secondCredentials); } - @Test - public void toBuilder_missingUniverseDomain_defaults() throws IOException { + @Test void toBuilder_missingUniverseDomain_defaults() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -383,8 +369,7 @@ public void toBuilder_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, secondCredentials.getUniverseDomain()); } - @Test - public void fromJson_allFields() throws IOException { + @Test void fromJson_allFields() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson( buildJsonCredentials(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -400,8 +385,7 @@ public void fromJson_allFields() throws IOException { assertEquals(UNIVERSE_DOMAIN, credentials.getUniverseDomain()); } - @Test - public void fromJson_minimumRequiredFieldsForRefresh() throws IOException { + @Test void fromJson_minimumRequiredFieldsForRefresh() throws IOException { GenericJson json = new GenericJson(); json.put("client_id", CLIENT_ID); json.put("client_secret", CLIENT_SECRET); @@ -422,8 +406,7 @@ public void fromJson_minimumRequiredFieldsForRefresh() throws IOException { assertNull(credentials.getQuotaProjectId()); } - @Test - public void fromJson_accessTokenOnly_notSupported() throws IOException { + @Test void fromJson_accessTokenOnly_notSupported() throws IOException { GenericJson json = new GenericJson(); json.put("access_token", ACCESS_TOKEN); @@ -439,8 +422,7 @@ public void fromJson_accessTokenOnly_notSupported() throws IOException { } } - @Test - public void fromJson_missingRefreshToken_throws() throws IOException { + @Test void fromJson_missingRefreshToken_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("refresh_token"); @@ -455,8 +437,7 @@ public void fromJson_missingRefreshToken_throws() throws IOException { } } - @Test - public void fromJson_missingTokenUrl_throws() throws IOException { + @Test void fromJson_missingTokenUrl_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("token_url"); @@ -471,8 +452,7 @@ public void fromJson_missingTokenUrl_throws() throws IOException { } } - @Test - public void fromJson_missingClientId_throws() throws IOException { + @Test void fromJson_missingClientId_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_id"); @@ -487,8 +467,7 @@ public void fromJson_missingClientId_throws() throws IOException { } } - @Test - public void fromJson_missingClientSecret_throws() throws IOException { + @Test void fromJson_missingClientSecret_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_secret"); @@ -503,8 +482,7 @@ public void fromJson_missingClientSecret_throws() throws IOException { } } - @Test - public void fromJson_missingUniverseDomain_defaults() throws IOException { + @Test void fromJson_missingUniverseDomain_defaults() throws IOException { GenericJson json = buildJsonCredentials(); json.remove("universe_domain"); @@ -522,8 +500,7 @@ public void fromJson_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_allFields() throws IOException { + @Test void fromStream_allFields() throws IOException { GenericJson json = buildJsonCredentials(); ExternalAccountAuthorizedUserCredentials credentials = @@ -539,8 +516,7 @@ public void fromStream_allFields() throws IOException { assertEquals(QUOTA_PROJECT, credentials.getQuotaProjectId()); } - @Test - public void fromStream_minimumRequiredFieldsForRefresh() throws IOException { + @Test void fromStream_minimumRequiredFieldsForRefresh() throws IOException { GenericJson json = new GenericJson(); json.put( "type", GoogleCredentialsInfo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_CREDENTIALS.getFileType()); @@ -563,8 +539,7 @@ public void fromStream_minimumRequiredFieldsForRefresh() throws IOException { assertNull(credentials.getQuotaProjectId()); } - @Test - public void fromStream_accessTokenOnly_notSupported() throws IOException { + @Test void fromStream_accessTokenOnly_notSupported() throws IOException { GenericJson json = new GenericJson(); json.put("access_token", ACCESS_TOKEN); json.put( @@ -581,8 +556,7 @@ public void fromStream_accessTokenOnly_notSupported() throws IOException { } } - @Test - public void fromStream_missingRefreshToken_throws() throws IOException { + @Test void fromStream_missingRefreshToken_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("refresh_token"); @@ -597,8 +571,7 @@ public void fromStream_missingRefreshToken_throws() throws IOException { } } - @Test - public void fromStream_missingTokenUrl_throws() throws IOException { + @Test void fromStream_missingTokenUrl_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("token_url"); @@ -613,8 +586,7 @@ public void fromStream_missingTokenUrl_throws() throws IOException { } } - @Test - public void fromStream_missingClientId_throws() throws IOException { + @Test void fromStream_missingClientId_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_id"); @@ -629,8 +601,7 @@ public void fromStream_missingClientId_throws() throws IOException { } } - @Test - public void fromStream_missingClientSecret_throws() throws IOException { + @Test void fromStream_missingClientSecret_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_secret"); @@ -645,8 +616,7 @@ public void fromStream_missingClientSecret_throws() throws IOException { } } - @Test - public void fromStream_missingUniverseDomain_defaults() throws IOException { + @Test void fromStream_missingUniverseDomain_defaults() throws IOException { GenericJson json = buildJsonCredentials(); json.remove("universe_domain"); @@ -664,8 +634,7 @@ public void fromStream_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_invalidInputStream_throws() throws IOException { + @Test void fromStream_invalidInputStream_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.put("audience", new HashMap<>()); @@ -676,8 +645,7 @@ public void fromStream_invalidInputStream_throws() throws IOException { } } - @Test - public void createScoped_noChange() { + @Test void createScoped_noChange() { ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setTokenUrl(TOKEN_URL) @@ -690,8 +658,7 @@ public void createScoped_noChange() { externalAccountAuthorizedUserCredentials.createScoped(SCOPES)); } - @Test - public void createScopedRequired_false() { + @Test void createScopedRequired_false() { ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setTokenUrl(TOKEN_URL) @@ -702,8 +669,7 @@ public void createScopedRequired_false() { assertFalse(externalAccountAuthorizedUserCredentials.createScopedRequired()); } - @Test - public void getRequestMetadata() throws IOException { + @Test void getRequestMetadata() throws IOException { GoogleCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -713,8 +679,7 @@ public void getRequestMetadata() throws IOException { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test - public void getRequestMetadata_withQuotaProjectId() throws IOException { + @Test void getRequestMetadata_withQuotaProjectId() throws IOException { GoogleCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -728,8 +693,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test - public void getRequestMetadata_withAccessToken() throws IOException { + @Test void getRequestMetadata_withAccessToken() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setHttpTransportFactory(transportFactory) @@ -741,8 +705,7 @@ public void getRequestMetadata_withAccessToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void refreshAccessToken() throws IOException { + @Test void refreshAccessToken() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -752,8 +715,7 @@ public void refreshAccessToken() throws IOException { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test - public void refreshAccessToken_withRefreshTokenRotation() throws IOException { + @Test void refreshAccessToken_withRefreshTokenRotation() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -768,8 +730,7 @@ public void refreshAccessToken_withRefreshTokenRotation() throws IOException { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test - public void refreshAccessToken_genericAuthError_throws() throws IOException { + @Test void refreshAccessToken_genericAuthError_throws() throws IOException { transportFactory.transport.addResponseErrorSequence( TestUtils.buildHttpResponseException( "invalid_request", "Invalid request.", /* errorUri= */ null)); @@ -786,18 +747,18 @@ public void refreshAccessToken_genericAuthError_throws() throws IOException { } } - @Test(expected = IOException.class) - public void refreshAccessToken_genericIOError_throws() throws IOException { + @Test + void refreshAccessToken_genericIOError_throws() throws IOException { transportFactory.transport.addResponseErrorSequence(new IOException("")); ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); - credentials.refreshAccessToken(); + assertThrows(IOException.class, () -> credentials.refreshAccessToken()); } - @Test(expected = IllegalStateException.class) - public void refreshAccessToken_missingRefreshFields_throws() throws IOException { + @Test + void refreshAccessToken_missingRefreshFields_throws() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -807,11 +768,10 @@ public void refreshAccessToken_missingRefreshFields_throws() throws IOException .setHttpTransportFactory(transportFactory) .build(); - credentials.refreshAccessToken(); + assertThrows(IllegalStateException.class, () -> credentials.refreshAccessToken()); } - @Test - public void hashCode_sameCredentials() { + @Test void hashCode_sameCredentials() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -843,8 +803,7 @@ public void hashCode_sameCredentials() { assertEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void hashCode_differentCredentials() { + @Test void hashCode_differentCredentials() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -875,8 +834,7 @@ public void hashCode_differentCredentials() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void hashCode_differentCredentialsWithCredentialsFile() throws IOException { + @Test void hashCode_differentCredentialsWithCredentialsFile() throws IOException { // Optional fields that can be specified in the credentials file. List fields = Arrays.asList("audience", "revoke_url", "quota_project_id"); @@ -897,8 +855,7 @@ public void hashCode_differentCredentialsWithCredentialsFile() throws IOExceptio } } - @Test - public void equals_differentCredentials() throws IOException { + @Test void equals_differentCredentials() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -916,8 +873,7 @@ public void equals_differentCredentials() throws IOException { assertNotEquals(credentials, userCredentials); } - @Test - public void equals_differentAudience() { + @Test void equals_differentAudience() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -940,8 +896,7 @@ public void equals_differentAudience() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentClientId() { + @Test void equals_differentClientId() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -964,8 +919,7 @@ public void equals_differentClientId() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentClientSecret() { + @Test void equals_differentClientSecret() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -988,8 +942,7 @@ public void equals_differentClientSecret() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentRefreshToken() { + @Test void equals_differentRefreshToken() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1012,8 +965,7 @@ public void equals_differentRefreshToken() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentTokenUrl() { + @Test void equals_differentTokenUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1036,8 +988,7 @@ public void equals_differentTokenUrl() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentTokenInfoUrl() { + @Test void equals_differentTokenInfoUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1060,8 +1011,7 @@ public void equals_differentTokenInfoUrl() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentRevokeUrl() { + @Test void equals_differentRevokeUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1084,8 +1034,7 @@ public void equals_differentRevokeUrl() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentAccessToken() { + @Test void equals_differentAccessToken() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1108,8 +1057,7 @@ public void equals_differentAccessToken() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentQuotaProjectId() { + @Test void equals_differentQuotaProjectId() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1132,8 +1080,7 @@ public void equals_differentQuotaProjectId() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentTransportFactory() { + @Test void equals_differentTransportFactory() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1156,8 +1103,7 @@ public void equals_differentTransportFactory() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void equals_differentUniverseDomain() { + @Test void equals_differentUniverseDomain() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1181,8 +1127,7 @@ public void equals_differentUniverseDomain() { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test - public void toString_expectedFormat() { + @Test void toString_expectedFormat() { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, new Date()); ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() @@ -1220,8 +1165,7 @@ public void toString_expectedFormat() { assertEquals(expectedToString, credentials.toString()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1266,4 +1210,4 @@ private static void validateAuthHeader(MockLowLevelHttpRequest request) { assertEquals(BASIC_AUTH, authHeader.iterator().next()); assertEquals(1, authHeader.size()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java index 497ead12a..ce7affc88 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; -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.assertTrue; -import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -56,14 +56,12 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests for {@link ExternalAccountCredentials}. */ -@RunWith(JUnit4.class) -public class ExternalAccountCredentialsTest extends BaseSerializationTest { + +class ExternalAccountCredentialsTest extends BaseSerializationTest { private static final String STS_URL = "https://sts.googleapis.com/v1/token"; private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com"; @@ -88,13 +86,11 @@ public HttpTransport create() { private MockExternalAccountCredentialsTransportFactory transportFactory; - @Before - public void setup() { + @BeforeEach void setup() { transportFactory = new MockExternalAccountCredentialsTransportFactory(); } - @Test - public void fromStream_identityPoolCredentials() throws IOException { + @Test void fromStream_identityPoolCredentials() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); ExternalAccountCredentials credential = @@ -103,8 +99,7 @@ public void fromStream_identityPoolCredentials() throws IOException { assertTrue(credential instanceof IdentityPoolCredentials); } - @Test - public void fromStream_awsCredentials() throws IOException { + @Test void fromStream_awsCredentials() throws IOException { GenericJson json = buildJsonAwsCredential(); ExternalAccountCredentials credential = @@ -113,8 +108,7 @@ public void fromStream_awsCredentials() throws IOException { assertTrue(credential instanceof AwsCredentials); } - @Test - public void fromStream_pluggableAuthCredentials() throws IOException { + @Test void fromStream_pluggableAuthCredentials() throws IOException { GenericJson json = buildJsonPluggableAuthCredential(); ExternalAccountCredentials credential = @@ -123,8 +117,7 @@ public void fromStream_pluggableAuthCredentials() throws IOException { assertTrue(credential instanceof PluggableAuthCredentials); } - @Test - public void fromStream_invalidStream_throws() throws IOException { + @Test void fromStream_invalidStream_throws() throws IOException { GenericJson json = buildJsonAwsCredential(); json.put("audience", new HashMap<>()); @@ -137,8 +130,7 @@ public void fromStream_invalidStream_throws() throws IOException { } } - @Test - public void fromStream_nullTransport_throws() throws IOException { + @Test void fromStream_nullTransport_throws() throws IOException { try { ExternalAccountCredentials.fromStream( new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); @@ -148,8 +140,7 @@ public void fromStream_nullTransport_throws() throws IOException { } } - @Test - public void fromStream_nullOptionalField() throws IOException { + @Test void fromStream_nullOptionalField() throws IOException { ExternalAccountCredentials credentials = ExternalAccountCredentials.fromStream( new ByteArrayInputStream( @@ -166,8 +157,7 @@ public void fromStream_nullOptionalField() throws IOException { assertNull(credentials.getServiceAccountImpersonationUrl()); } - @Test - public void fromStream_nullStream_throws() throws IOException { + @Test void fromStream_nullStream_throws() throws IOException { try { ExternalAccountCredentials.fromStream( /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -177,8 +167,7 @@ public void fromStream_nullStream_throws() throws IOException { } } - @Test - public void fromStream_invalidWorkloadAudience_throws() throws IOException { + @Test void fromStream_invalidWorkloadAudience_throws() throws IOException { try { GenericJson json = buildJsonIdentityPoolWorkforceCredential(); json.put("audience", "invalidAudience"); @@ -190,8 +179,7 @@ public void fromStream_invalidWorkloadAudience_throws() throws IOException { } } - @Test - public void fromJson_identityPoolCredentialsWorkload() throws IOException { + @Test void fromJson_identityPoolCredentialsWorkload() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -207,8 +195,7 @@ public void fromJson_identityPoolCredentialsWorkload() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_identityPoolCredentialsWorkforce() throws IOException { + @Test void fromJson_identityPoolCredentialsWorkforce() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -225,8 +212,7 @@ public void fromJson_identityPoolCredentialsWorkforce() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() + @Test void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set( @@ -248,8 +234,7 @@ public void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptio assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOException { + @Test void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set("universe_domain", "universeDomain"); @@ -268,8 +253,7 @@ public void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOExcept assertEquals("universeDomain", credential.getUniverseDomain()); } - @Test - public void fromJson_awsCredentials() throws IOException { + @Test void fromJson_awsCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonAwsCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -283,8 +267,7 @@ public void fromJson_awsCredentials() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() throws IOException { + @Test void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson awsCredentialJson = buildJsonAwsCredential(); awsCredentialJson.set( "service_account_impersonation", buildServiceAccountImpersonationOptions(2800)); @@ -302,8 +285,7 @@ public void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() thro assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_awsCredentialsWithUniverseDomain() throws IOException { + @Test void fromJson_awsCredentialsWithUniverseDomain() throws IOException { GenericJson awsCredentialJson = buildJsonAwsCredential(); awsCredentialJson.set("universe_domain", "universeDomain"); @@ -319,8 +301,7 @@ public void fromJson_awsCredentialsWithUniverseDomain() throws IOException { assertNotNull(credential.getCredentialSource()); } - @Test - public void fromJson_pluggableAuthCredentials() throws IOException { + @Test void fromJson_pluggableAuthCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -340,8 +321,7 @@ public void fromJson_pluggableAuthCredentials() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { + @Test void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -367,7 +347,7 @@ public void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { @Test @SuppressWarnings("unchecked") - public void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() throws IOException { + void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() throws IOException { GenericJson json = buildJsonPluggableAuthCredential(); Map credentialSourceMap = (Map) json.get("credential_source"); // Add optional params to the executable config (timeout, output file path). @@ -394,8 +374,7 @@ public void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() throws I assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test - public void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOptions() + @Test void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson pluggableAuthCredentialJson = buildJsonPluggableAuthCredential(); pluggableAuthCredentialJson.set( @@ -423,7 +402,7 @@ public void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOpti @Test @SuppressWarnings("unchecked") - public void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { + void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { GenericJson json = buildJsonPluggableAuthCredential(); json.set("universe_domain", "universeDomain"); @@ -452,8 +431,7 @@ public void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOExce assertEquals("universeDomain", credential.getUniverseDomain()); } - @Test - public void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOException { + @Test void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOException { GenericJson pluggableAuthCredentialJson = buildJsonPluggableAuthCredential(); pluggableAuthCredentialJson.set("universe_domain", "universeDomain"); @@ -476,8 +454,7 @@ public void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOExcep assertNull(source.getOutputFilePath()); } - @Test - public void fromJson_nullJson_throws() throws IOException { + @Test void fromJson_nullJson_throws() throws IOException { try { ExternalAccountCredentials.fromJson(/* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); fail("Exception should be thrown."); @@ -486,8 +463,7 @@ public void fromJson_nullJson_throws() throws IOException { } } - @Test - public void fromJson_nullTransport_throws() throws IOException { + @Test void fromJson_nullTransport_throws() throws IOException { try { ExternalAccountCredentials.fromJson( new HashMap(), /* transportFactory= */ null); @@ -497,8 +473,7 @@ public void fromJson_nullTransport_throws() throws IOException { } } - @Test - public void fromJson_invalidWorkforceAudiences_throws() throws IOException { + @Test void fromJson_invalidWorkforceAudiences_throws() throws IOException { List invalidAudiences = Arrays.asList( "//iam.googleapis.com/locations/global/workloadIdentityPools/pool/providers/provider", @@ -526,8 +501,7 @@ public void fromJson_invalidWorkforceAudiences_throws() throws IOException { } } - @Test - public void constructor_builder() throws IOException { + @Test void constructor_builder() throws IOException { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -566,8 +540,7 @@ public void constructor_builder() throws IOException { assertNotNull(credentials.getCredentialSource()); } - @Test - public void constructor_builder_defaultTokenUrl() { + @Test void constructor_builder_defaultTokenUrl() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -583,8 +556,7 @@ public void constructor_builder_defaultTokenUrl() { assertEquals(STS_URL, credentials.getTokenUrl()); } - @Test - public void constructor_builder_defaultTokenUrlwithUniverseDomain() { + @Test void constructor_builder_defaultTokenUrlwithUniverseDomain() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -601,8 +573,7 @@ public void constructor_builder_defaultTokenUrlwithUniverseDomain() { assertEquals("https://sts.testdomain.org/v1/token", credentials.getTokenUrl()); } - @Test - public void constructor_builder_subjectTokenTypeEnum() { + @Test void constructor_builder_subjectTokenTypeEnum() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -619,8 +590,7 @@ public void constructor_builder_subjectTokenTypeEnum() { assertEquals(SubjectTokenTypes.SAML2.value, credentials.getSubjectTokenType()); } - @Test - public void constructor_builder_invalidTokenUrl() { + @Test void constructor_builder_invalidTokenUrl() { try { ExternalAccountCredentials.Builder builder = TestExternalAccountCredentials.newBuilder() @@ -636,8 +606,7 @@ public void constructor_builder_invalidTokenUrl() { } } - @Test - public void constructor_builder_invalidServiceAccountImpersonationUrl() { + @Test void constructor_builder_invalidServiceAccountImpersonationUrl() { try { ExternalAccountCredentials.Builder builder = TestExternalAccountCredentials.newBuilder() @@ -654,8 +623,7 @@ public void constructor_builder_invalidServiceAccountImpersonationUrl() { } } - @Test - public void constructor_builderWithInvalidWorkforceAudiences_throws() { + @Test void constructor_builderWithInvalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -689,8 +657,7 @@ public void constructor_builderWithInvalidWorkforceAudiences_throws() { } } - @Test - public void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { + @Test void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); // No exception should be thrown. @@ -704,8 +671,7 @@ public void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience .build(); } - @Test - public void constructor_builder_invalidTokenLifetime_throws() { + @Test void constructor_builder_invalidTokenLifetime_throws() { Map invalidOptionsMap = new HashMap(); invalidOptionsMap.put("token_lifetime_seconds", "thisIsAString"); @@ -736,8 +702,7 @@ public void constructor_builder_invalidTokenLifetime_throws() { } } - @Test - public void constructor_builder_stringTokenLifetime() { + @Test void constructor_builder_stringTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", "2800"); @@ -763,8 +728,7 @@ public void constructor_builder_stringTokenLifetime() { assertEquals(2800, credentials.getServiceAccountImpersonationOptions().getLifetime()); } - @Test - public void constructor_builder_bigDecimalTokenLifetime() { + @Test void constructor_builder_bigDecimalTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", new BigDecimal("2800")); @@ -790,8 +754,7 @@ public void constructor_builder_bigDecimalTokenLifetime() { assertEquals(2800, credentials.getServiceAccountImpersonationOptions().getLifetime()); } - @Test - public void constructor_builder_integerTokenLifetime() { + @Test void constructor_builder_integerTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", Integer.valueOf(2800)); @@ -817,8 +780,7 @@ public void constructor_builder_integerTokenLifetime() { assertEquals(2800, credentials.getServiceAccountImpersonationOptions().getLifetime()); } - @Test - public void constructor_builder_lowTokenLifetime_throws() { + @Test void constructor_builder_lowTokenLifetime_throws() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", 599); @@ -847,8 +809,7 @@ public void constructor_builder_lowTokenLifetime_throws() { } } - @Test - public void constructor_builder_highTokenLifetime_throws() { + @Test void constructor_builder_highTokenLifetime_throws() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", 43201); @@ -877,8 +838,7 @@ public void constructor_builder_highTokenLifetime_throws() { } } - @Test - public void exchangeExternalCredentialForAccessToken() throws IOException { + @Test void exchangeExternalCredentialForAccessToken() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -901,8 +861,7 @@ public void exchangeExternalCredentialForAccessToken() throws IOException { validateMetricsHeader(headers, "file", false, false); } - @Test - public void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { + @Test void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -926,8 +885,7 @@ public void exchangeExternalCredentialForAccessToken_withInternalOptions() throw assertEquals(internalOptions.toString(), query.get("options")); } - @Test - public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() + @Test void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() throws IOException { ExternalAccountCredentials identityPoolCredential = ExternalAccountCredentials.fromJson( @@ -960,8 +918,7 @@ public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserPro } } - @Test - public void + @Test void exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() throws IOException { ExternalAccountCredentials credential = @@ -987,8 +944,7 @@ public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserPro assertEquals(internalOptions.toString(), query.get("options")); } - @Test - public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() + @Test void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -1024,8 +980,7 @@ public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersona validateMetricsHeader(headers, "url", true, false); } - @Test - public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOptions() + @Test void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOptions() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -1060,8 +1015,7 @@ public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersona assertEquals("2800s", query.get("lifetime")); } - @Test - public void exchangeExternalCredentialForAccessToken_throws() throws IOException { + @Test void exchangeExternalCredentialForAccessToken_throws() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -1084,8 +1038,7 @@ public void exchangeExternalCredentialForAccessToken_throws() throws IOException } } - @Test - public void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredentialsThrows() + @Test void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredentialsThrows() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); json.put("service_account_impersonation_url", "https://iamcredentials.googleapis.com"); @@ -1105,8 +1058,7 @@ public void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredenti } } - @Test - public void getRequestMetadata_withQuotaProjectId() throws IOException { + @Test void getRequestMetadata_withQuotaProjectId() throws IOException { TestExternalAccountCredentials testCredentials = (TestExternalAccountCredentials) TestExternalAccountCredentials.newBuilder() @@ -1124,8 +1076,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException { assertEquals("quotaProjectId", requestMetadata.get("x-goog-user-project").get(0)); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { Map impersonationOpts = new HashMap() { { @@ -1158,8 +1109,7 @@ public void serialize() throws IOException, ClassNotFoundException { deserializedCredentials.toBuilder().getHttpTransportFactory().getClass()); } - @Test - public void validateTokenUrl_validUrls() { + @Test void validateTokenUrl_validUrls() { List validUrls = Arrays.asList( "https://sts.googleapis.com", @@ -1180,8 +1130,7 @@ public void validateTokenUrl_validUrls() { } } - @Test - public void validateTokenUrl_invalidUrls() { + @Test void validateTokenUrl_invalidUrls() { List invalidUrls = Arrays.asList( "sts.googleapis.com", @@ -1203,8 +1152,7 @@ public void validateTokenUrl_invalidUrls() { } } - @Test - public void validateServiceAccountImpersonationUrls_validUrls() { + @Test void validateServiceAccountImpersonationUrls_validUrls() { List validUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -1226,8 +1174,7 @@ public void validateServiceAccountImpersonationUrls_validUrls() { } } - @Test - public void validateServiceAccountImpersonationUrls_invalidUrls() { + @Test void validateServiceAccountImpersonationUrls_invalidUrls() { List invalidUrls = Arrays.asList( "iamcredentials.googleapis.com", @@ -1394,4 +1341,4 @@ public String retrieveSubjectToken() { return "subjectToken"; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java index 1dc05d06f..07268e219 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java @@ -31,15 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; - +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.auth.oauth2.ExternalAccountCredentials.SubjectTokenTypes; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExternalAccountSupplierContextTest { +class ExternalAccountSupplierContextTest { - @Test - public void constructor_builder() { + @Test void constructor_builder() { String expectedAudience = "//iam.googleapis.com/locations/global/workloadPools/pool/providers/provider"; String expectedTokenType = SubjectTokenTypes.JWT.value; @@ -53,8 +51,7 @@ public void constructor_builder() { assertEquals(expectedTokenType, context.getSubjectTokenType()); } - @Test - public void constructor_builder_subjectTokenEnum() { + @Test void constructor_builder_subjectTokenEnum() { String expectedAudience = "//iam.googleapis.com/locations/global/workloadPools/pool/providers/provider"; SubjectTokenTypes expectedTokenType = SubjectTokenTypes.JWT; @@ -67,4 +64,4 @@ public void constructor_builder_subjectTokenEnum() { assertEquals(expectedAudience, context.getAudience()); assertEquals(expectedTokenType.value, context.getSubjectTokenType()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java index bef50360c..1695c16d0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java @@ -31,14 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; @@ -54,13 +53,11 @@ import java.nio.file.Files; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link GdchCredentials}. */ -@RunWith(JUnit4.class) -public class GdchCredentialsTest extends BaseSerializationTest { + +class GdchCredentialsTest extends BaseSerializationTest { private static final String FORMAT_VERSION = GdchCredentials.SUPPORTED_FORMAT_VERSION; private static final String PRIVATE_KEY_ID = "d84a4fefcf50791d4a90f2d7af17469d6282df9d"; static final String PRIVATE_KEY_PKCS8 = @@ -87,8 +84,7 @@ public class GdchCredentialsTest extends BaseSerializationTest { private static final URI API_AUDIENCE = URI.create("https://gdch-api-audience"); private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); - @Test - public void fromJSON_getProjectId() throws IOException { + @Test void fromJSON_getProjectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -103,8 +99,7 @@ public void fromJSON_getProjectId() throws IOException { assertEquals(PROJECT_ID, credentials.getProjectId()); } - @Test - public void fromJSON_getServiceIdentityName() throws IOException { + @Test void fromJSON_getServiceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -119,8 +114,7 @@ public void fromJSON_getServiceIdentityName() throws IOException { assertEquals(SERVICE_IDENTITY_NAME, credentials.getServiceIdentityName()); } - @Test - public void fromJSON_getCaCertPath() throws IOException { + @Test void fromJSON_getCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -135,8 +129,7 @@ public void fromJSON_getCaCertPath() throws IOException { assertEquals(CA_CERT_PATH, credentials.getCaCertPath()); } - @Test - public void fromJSON_getTokenServerUri() throws IOException { + @Test void fromJSON_getTokenServerUri() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -151,8 +144,7 @@ public void fromJSON_getTokenServerUri() throws IOException { assertEquals(TOKEN_SERVER_URI, credentials.getTokenServerUri()); } - @Test - public void fromJSON_nullFormatVersion() throws IOException { + @Test void fromJSON_nullFormatVersion() throws IOException { GenericJson json = writeGdchServiceAccountJson( null, @@ -177,8 +169,7 @@ public void fromJSON_nullFormatVersion() throws IOException { } } - @Test - public void fromJSON_nullProjectId() throws IOException { + @Test void fromJSON_nullProjectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -203,8 +194,7 @@ public void fromJSON_nullProjectId() throws IOException { } } - @Test - public void fromJSON_nullPrivateKeyId() throws IOException { + @Test void fromJSON_nullPrivateKeyId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -229,8 +219,7 @@ public void fromJSON_nullPrivateKeyId() throws IOException { } } - @Test - public void fromJSON_nullPrivateKey() throws IOException { + @Test void fromJSON_nullPrivateKey() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -255,8 +244,7 @@ public void fromJSON_nullPrivateKey() throws IOException { } } - @Test - public void fromJSON_nullServiceIdentityName() throws IOException { + @Test void fromJSON_nullServiceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -281,8 +269,7 @@ public void fromJSON_nullServiceIdentityName() throws IOException { } } - @Test - public void fromJSON_nullCaCertPath() throws IOException { + @Test void fromJSON_nullCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -296,8 +283,7 @@ public void fromJSON_nullCaCertPath() throws IOException { assertNull(credentials.getCaCertPath()); } - @Test - public void fromJSON_nullTokenServerUri() throws IOException { + @Test void fromJSON_nullTokenServerUri() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -322,8 +308,7 @@ public void fromJSON_nullTokenServerUri() throws IOException { } } - @Test - public void fromJSON_invalidFormatVersion() throws IOException { + @Test void fromJSON_invalidFormatVersion() throws IOException { GenericJson json = writeGdchServiceAccountJson( "100", @@ -344,8 +329,7 @@ public void fromJSON_invalidFormatVersion() throws IOException { } } - @Test - public void fromJSON_invalidCaCertPath() throws IOException { + @Test void fromJSON_invalidCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -364,8 +348,7 @@ public void fromJSON_invalidCaCertPath() throws IOException { } } - @Test - public void fromJSON_emptyCaCertPath() throws IOException { + @Test void fromJSON_emptyCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -379,8 +362,7 @@ public void fromJSON_emptyCaCertPath() throws IOException { assertEquals("", credentials.getCaCertPath()); } - @Test - public void fromJSON_transportFactoryForGdch() throws IOException { + @Test void fromJSON_transportFactoryForGdch() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -396,8 +378,7 @@ public void fromJSON_transportFactoryForGdch() throws IOException { credentials.getTransportFactory().getClass()); } - @Test - public void fromJSON_hasAccessToken() throws IOException { + @Test void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = writeGdchServiceAccountJson( @@ -417,8 +398,7 @@ public void fromJSON_hasAccessToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void createWithGdchAudience_correct() throws IOException { + @Test void createWithGdchAudience_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -445,8 +425,7 @@ public void createWithGdchAudience_correct() throws IOException { assertEquals(API_AUDIENCE, gdchWithAudience.getApiAudience()); } - @Test - public void createWithGdchAudience_nullApiAudience() throws IOException { + @Test void createWithGdchAudience_nullApiAudience() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -466,8 +445,7 @@ public void createWithGdchAudience_nullApiAudience() throws IOException { } } - @Test - public void createAssertion_correct() throws IOException { + @Test void createAssertion_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -494,8 +472,7 @@ public void createAssertion_correct() throws IOException { assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); } - @Test - public void refreshAccessToken_correct() throws IOException { + @Test void refreshAccessToken_correct() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = @@ -531,8 +508,7 @@ public void refreshAccessToken_correct() throws IOException { assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); } - @Test - public void refreshAccessToken_nullApiAudience() throws IOException { + @Test void refreshAccessToken_nullApiAudience() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = @@ -563,8 +539,7 @@ public void refreshAccessToken_nullApiAudience() throws IOException { } } - @Test - public void getIssuerSubjectValue_correct() throws IOException { + @Test void getIssuerSubjectValue_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -582,8 +557,7 @@ public void getIssuerSubjectValue_correct() throws IOException { GdchCredentials.getIssuerSubjectValue(PROJECT_ID, SERVICE_IDENTITY_NAME)); } - @Test - public void equals_same() throws IOException { + @Test void equals_same() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -613,8 +587,7 @@ public void equals_same() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_projectId() throws IOException { + @Test void equals_false_projectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -644,8 +617,7 @@ public void equals_false_projectId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_keyId() throws IOException { + @Test void equals_false_keyId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -675,8 +647,7 @@ public void equals_false_keyId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_serviceIdentityName() throws IOException { + @Test void equals_false_serviceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -706,8 +677,7 @@ public void equals_false_serviceIdentityName() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_caCertPath() throws IOException { + @Test void equals_false_caCertPath() throws IOException { File tmpDirectory = Files.createTempDirectory("tmpDirectory").toFile(); File testCaCertFile = File.createTempFile("testCert", ".pem", tmpDirectory); GenericJson json = @@ -741,8 +711,7 @@ public void equals_false_caCertPath() throws IOException { testCaCertFile.delete(); } - @Test - public void equals_false_tokenServer() throws IOException { + @Test void equals_false_tokenServer() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -772,8 +741,7 @@ public void equals_false_tokenServer() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_apiAudience() throws IOException { + @Test void equals_false_apiAudience() throws IOException { URI otherApiAudience = URI.create("https://foo1.com/bar"); GenericJson json = @@ -804,8 +772,7 @@ public void equals_false_apiAudience() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -831,8 +798,7 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -860,8 +826,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize_correct() throws IOException, ClassNotFoundException { + @Test void serialize_correct() throws IOException, ClassNotFoundException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = writeGdchServiceAccountJson( @@ -940,4 +905,4 @@ static InputStream writeGdchServiceAccountStream( tokenServerUri); return TestUtils.jsonToInputStream(json); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java index 51880ddcc..7bbf88b5c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java @@ -5,7 +5,7 @@ import java.net.URI; import java.util.Map; -public class GdchCredentialsTestUtil { +class GdchCredentialsTestUtil { public static void registerGdchCredentialWithMockTransport( GdchCredentials credentials, MockTokenServerTransport transport, @@ -24,4 +24,4 @@ public static GdchCredentials fromJson( throws IOException { return GdchCredentials.fromJson(json, transportFactory); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java index 4fd5da43e..ec367d54b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java @@ -31,16 +31,14 @@ 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 java.io.File; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GoogleAuthUtilsTest { +class GoogleAuthUtilsTest { - @Test - public void getWellKnownCredentialsPath_correct() { + @Test void getWellKnownCredentialsPath_correct() { DefaultCredentialsProvider provider = new DefaultCredentialsProviderTest.TestDefaultCredentialsProvider(); // since the TestDefaultCredentialsProvider properties and envs are not set, @@ -55,4 +53,4 @@ public void getWellKnownCredentialsPath_correct() { assertNotNull(obtainedPath); assertEquals(obtainedPath, wellKnownFile.getAbsolutePath()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java index cd577bbf5..c00810718 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -31,8 +31,14 @@ 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.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.http.HttpStatusCodes; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Clock; @@ -52,13 +58,11 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link GoogleCredentials}. */ -@RunWith(JUnit4.class) -public class GoogleCredentialsTest extends BaseSerializationTest { + +class GoogleCredentialsTest extends BaseSerializationTest { private static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -95,8 +99,7 @@ public class GoogleCredentialsTest extends BaseSerializationTest { private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com"; private static final String TPC_UNIVERSE = "foo.bar"; - @Test - public void getApplicationDefault_nullTransport_throws() throws IOException { + @Test void getApplicationDefault_nullTransport_throws() throws IOException { try { GoogleCredentials.getApplicationDefault(null); fail(); @@ -105,8 +108,7 @@ public void getApplicationDefault_nullTransport_throws() throws IOException { } } - @Test - public void fromStream_unknownType_throws() throws IOException { + @Test void fromStream_unknownType_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); GenericJson json = new GenericJson(); json.put("type", "unsupported_credential"); @@ -124,8 +126,7 @@ public void fromStream_unknownType_throws() throws IOException { } } - @Test - public void fromStream_nullTransport_throws() throws IOException { + @Test void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { GoogleCredentials.fromStream(stream, null); @@ -135,8 +136,7 @@ public void fromStream_nullTransport_throws() throws IOException { } } - @Test - public void fromStream_noType_throws() throws IOException { + @Test void fromStream_noType_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); GenericJson json = ServiceAccountCredentialsTest.writeServiceAccountJson( @@ -152,14 +152,12 @@ public void fromStream_noType_throws() throws IOException { } } - @Test - public void fromStream_nullStream_throws() { + @Test void fromStream_nullStream_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); assertThrows(NullPointerException.class, () -> GoogleCredentials.parseJsonInputStream(null)); } - @Test - public void fromStream_serviceAccount_noUniverse_providesToken() throws IOException { + @Test void fromStream_serviceAccount_noUniverse_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -181,8 +179,7 @@ public void fromStream_serviceAccount_noUniverse_providesToken() throws IOExcept TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void fromStream_serviceAccount_Universe_noToken() throws IOException { + @Test void fromStream_serviceAccount_Universe_noToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -200,8 +197,7 @@ public void fromStream_serviceAccount_Universe_noToken() throws IOException { assertNotNull(((ServiceAccountCredentials) credentials).getSelfSignedJwtCredentialsWithScope()); } - @Test - public void fromStream_serviceAccountNoClientId_throws() throws IOException { + @Test void fromStream_serviceAccountNoClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -209,8 +205,7 @@ public void fromStream_serviceAccountNoClientId_throws() throws IOException { testFromStreamException(serviceAccountStream, "client_id"); } - @Test - public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { + @Test void fromStream_serviceAccountNoClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -218,8 +213,7 @@ public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { testFromStreamException(serviceAccountStream, "client_email"); } - @Test - public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { + @Test void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -227,8 +221,7 @@ public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { testFromStreamException(serviceAccountStream, "private_key"); } - @Test - public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { + @Test void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -236,8 +229,7 @@ public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException testFromStreamException(serviceAccountStream, "private_key_id"); } - @Test - public void fromStream_gdchServiceAccount_correct() throws IOException { + @Test void fromStream_gdchServiceAccount_correct() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( @@ -272,8 +264,7 @@ public void fromStream_gdchServiceAccount_correct() throws IOException { assertNotNull(((GdchCredentials) credentials).getApiAudience()); } - @Test - public void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOException { + @Test void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( null, @@ -287,8 +278,7 @@ public void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOExcep testFromStreamException(gdchServiceAccountStream, "format_version"); } - @Test - public void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException { + @Test void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -302,8 +292,7 @@ public void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException testFromStreamException(gdchServiceAccountStream, "project"); } - @Test - public void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOException { + @Test void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -317,8 +306,7 @@ public void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOExcept testFromStreamException(gdchServiceAccountStream, "private_key_id"); } - @Test - public void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOException { + @Test void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -332,8 +320,7 @@ public void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOExceptio testFromStreamException(gdchServiceAccountStream, "private_key"); } - @Test - public void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws IOException { + @Test void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -347,8 +334,7 @@ public void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws I testFromStreamException(gdchServiceAccountStream, "name"); } - @Test - public void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOException { + @Test void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -362,8 +348,7 @@ public void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOExce testFromStreamException(gdchServiceAccountStream, "token_uri"); } - @Test - public void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IOException { + @Test void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( "100", @@ -379,8 +364,7 @@ public void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IO String.format("Only format version %s is supported", GDCH_SA_FORMAT_VERSION)); } - @Test - public void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOException { + @Test void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -396,8 +380,7 @@ public void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOExc String.format("Error reading certificate file from CA cert path")); } - @Test - public void fromStream_userCredentials_providesToken() throws IOException { + @Test void fromStream_userCredentials_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(USER_CLIENT_ID, USER_CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -412,8 +395,7 @@ public void fromStream_userCredentials_providesToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void fromStream_userCredentials_defaultUniverse() throws IOException { + @Test void fromStream_userCredentials_defaultUniverse() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -424,24 +406,21 @@ public void fromStream_userCredentials_defaultUniverse() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_userCredentials_NoClientId_throws() throws IOException { + @Test void fromStream_userCredentials_NoClientId_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(null, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_id"); } - @Test - public void fromStream_userCredentials_NoClientSecret_throws() throws IOException { + @Test void fromStream_userCredentials_NoClientSecret_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(USER_CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_secret"); } - @Test - public void fromStream_userCredentials_NoRefreshToken_throws() throws IOException { + @Test void fromStream_userCredentials_NoRefreshToken_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, null, QUOTA_PROJECT); @@ -449,8 +428,7 @@ public void fromStream_userCredentials_NoRefreshToken_throws() throws IOExceptio testFromStreamException(userStream, "refresh_token"); } - @Test - public void fromStream_identityPoolCredentials_providesToken() throws IOException { + @Test void fromStream_identityPoolCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -469,8 +447,7 @@ public void fromStream_identityPoolCredentials_providesToken() throws IOExceptio TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test - public void fromStream_identityPoolCredentials_defaultUniverse() throws IOException { + @Test void fromStream_identityPoolCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -486,8 +463,7 @@ public void fromStream_identityPoolCredentials_defaultUniverse() throws IOExcept assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_awsCredentials_providesToken() throws IOException { + @Test void fromStream_awsCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -506,8 +482,7 @@ public void fromStream_awsCredentials_providesToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test - public void fromStream_awsCredentials_defaultUniverse() throws IOException { + @Test void fromStream_awsCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -523,8 +498,7 @@ public void fromStream_awsCredentials_defaultUniverse() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_pluggableAuthCredentials_providesToken() throws IOException { + @Test void fromStream_pluggableAuthCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -546,8 +520,7 @@ public void fromStream_pluggableAuthCredentials_providesToken() throws IOExcepti TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test - public void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { + @Test void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -559,8 +532,7 @@ public void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOExcep assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_externalAccountAuthorizedUserCredentials_providesToken() + @Test void fromStream_externalAccountAuthorizedUserCredentials_providesToken() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); @@ -574,8 +546,7 @@ public void fromStream_externalAccountAuthorizedUserCredentials_providesToken() TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test - public void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() + @Test void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); @@ -589,8 +560,7 @@ public void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse( assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { + @Test void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -631,8 +601,7 @@ public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOE assertEquals(ImpersonatedCredentialsTest.QUOTA_PROJECT_ID, headerValues.get(0)); } - @Test - public void fromStream_Impersonation_defaultUniverse() throws IOException { + @Test void fromStream_Impersonation_defaultUniverse() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -656,8 +625,7 @@ public void fromStream_Impersonation_defaultUniverse() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { + @Test void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -695,8 +663,7 @@ public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test - public void createScoped_overloadCallsImplementation() { + @Test void createScoped_overloadCallsImplementation() { final AtomicReference> called = new AtomicReference<>(); final GoogleCredentials expectedScopedCredentials = new GoogleCredentials(); @@ -715,8 +682,7 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(ImmutableList.of("foo", "bar"), called.get()); } - @Test - public void create_withoutUniverse() throws IOException { + @Test void create_withoutUniverse() throws IOException { AccessToken token = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); GoogleCredentials credentials = GoogleCredentials.create(token); @@ -724,8 +690,7 @@ public void create_withoutUniverse() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test - public void create_withUniverse() throws IOException { + @Test void create_withUniverse() throws IOException { AccessToken token = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); GoogleCredentials credentials = GoogleCredentials.create("some-universe", token); @@ -733,8 +698,7 @@ public void create_withUniverse() throws IOException { assertEquals(true, credentials.isExplicitUniverseDomain()); } - @Test - public void buildWithQuotaProject() { + @Test void buildWithQuotaProject() { final GoogleCredentials googleCredentials = new GoogleCredentials.Builder().setQuotaProjectId("old_quota").build(); GoogleCredentials withUpdatedQuota = googleCredentials.createWithQuotaProject("new_quota"); @@ -749,8 +713,7 @@ public void buildWithQuotaProject() { assertEquals(null, sameCredentials.getQuotaProjectId()); } - @Test - public void buildWithUniverseDomain() throws IOException { + @Test void buildWithUniverseDomain() throws IOException { final GoogleCredentials original = new GoogleCredentials.Builder().setUniverseDomain("universe1").build(); GoogleCredentials updated = original.toBuilder().setUniverseDomain("universe2").build(); @@ -769,8 +732,7 @@ public void buildWithUniverseDomain() throws IOException { assertEquals(false, withNull.isExplicitUniverseDomain()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { final GoogleCredentials testCredentials = new GoogleCredentials.Builder().build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(testCredentials); assertEquals(testCredentials, deserializedCredentials); @@ -779,8 +741,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { String expectedToString = String.format( "GoogleCredentials{quotaProjectId=%s, universeDomain=%s, isExplicitUniverseDomain=%s}", @@ -790,8 +751,7 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { GoogleCredentials credentials = GoogleCredentials.newBuilder().setUniverseDomain("some-domain").build(); GoogleCredentials otherCredentials = @@ -799,8 +759,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { GoogleCredentials credentials = GoogleCredentials.newBuilder().setUniverseDomain("some-domain").build(); GoogleCredentials otherCredentials = @@ -820,8 +779,7 @@ private static void testFromStreamException(InputStream stream, String expectedM } } - @Test - public void getCredentialInfo_serviceAccountCredentials() throws IOException { + @Test void getCredentialInfo_serviceAccountCredentials() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -834,8 +792,7 @@ public void getCredentialInfo_serviceAccountCredentials() throws IOException { assertEquals(SA_CLIENT_EMAIL, credentialInfo.get("Principal")); } - @Test - public void getCredentialInfo_userCredentials() throws IOException { + @Test void getCredentialInfo_userCredentials() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, null); @@ -848,8 +805,7 @@ public void getCredentialInfo_userCredentials() throws IOException { assertNull(credentialInfo.get("Principal")); } - @Test - public void getCredentialInfo_gdchCredentials() throws IOException { + @Test void getCredentialInfo_gdchCredentials() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -868,8 +824,7 @@ public void getCredentialInfo_gdchCredentials() throws IOException { assertNull(credentialInfo.get("Principal")); } - @Test - public void getCredentialInfo_externalAccount() throws IOException { + @Test void getCredentialInfo_externalAccount() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -888,8 +843,7 @@ public void getCredentialInfo_externalAccount() throws IOException { assertNull(credentialInfo.get("Principal")); } - @Test - public void getCredentialInfo_externalAccountUserCredentials() throws IOException { + @Test void getCredentialInfo_externalAccountUserCredentials() throws IOException { InputStream externalAccountUserCredentialStream = ExternalAccountAuthorizedUserCredentialsTest.writeExternalAccountUserCredentialStream( USER_CLIENT_ID, @@ -908,8 +862,7 @@ public void getCredentialInfo_externalAccountUserCredentials() throws IOExceptio assertNull(credentialInfo.get("Principal")); } - @Test - public void getCredentialInfo_impersonatedServiceAccount() throws IOException { + @Test void getCredentialInfo_impersonatedServiceAccount() throws IOException { InputStream impersonationCredentialsStream = ImpersonatedCredentialsTest.writeImpersonationCredentialsStream( ImpersonatedCredentialsTest.IMPERSONATION_OVERRIDE_URL, @@ -927,4 +880,4 @@ public void getCredentialInfo_impersonatedServiceAccount() throws IOException { assertEquals( ImpersonatedCredentialsTest.IMPERSONATED_CLIENT_EMAIL, credentialInfo.get("Principal")); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java index bf7946164..1949b1608 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java @@ -31,10 +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; @@ -46,7 +45,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 +55,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 { +final class ITDownscopingTest { // Output copied from the setup script (downscoping-with-cab-setup.sh). private static final String GCS_BUCKET_NAME = "cab-int-bucket-cbi3qrv5"; @@ -92,8 +91,7 @@ public final class ITDownscopingTest { * downscoped token. 2. Validating that we do not have permission to retrieve a different object * in the same bucket. */ - @Test - public void downscoping_serviceAccountSourceWithRefresh() throws IOException { + @Test void downscoping_serviceAccountSourceWithRefresh() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -147,4 +145,4 @@ private void retrieveObjectFromGcs(Credentials credentials, String objectName) HttpResponse response = request.execute(); assertTrue(response.isSuccessStatusCode()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index 25982e544..90ba2e972 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java @@ -31,9 +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; @@ -55,8 +54,8 @@ import java.time.Instant; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Integration tests for Workload Identity Federation. @@ -66,7 +65,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 { +final class ITWorkloadIdentityFederationTest { // Copy output from workloadidentityfederation-setup. private static final String AUDIENCE_PREFIX = @@ -79,8 +78,7 @@ 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"); } @@ -92,8 +90,7 @@ public void setup() throws IOException { * exchanged for a GCP access token via GCP STS endpoint and then to impersonate the original * service account key. Retrieves the OIDC token from a file. */ - @Test - public void identityPoolCredentials() throws IOException { + @Test void identityPoolCredentials() throws IOException { IdentityPoolCredentials identityPoolCredentials = (IdentityPoolCredentials) ExternalAccountCredentials.fromJson( @@ -111,8 +108,7 @@ public void identityPoolCredentials() throws IOException { * exchanged for a GCP access token via GCP STS endpoint and then to impersonate the original * service account key. */ - @Test - public void awsCredentials() throws Exception { + @Test void awsCredentials() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -162,8 +158,7 @@ public void awsCredentials() throws Exception { * the external subject token to be exchanged for a GCP access token via GCP STS endpoint and then * to impersonate the original service account key. */ - @Test - public void awsCredentials_withProgrammaticAuth() throws Exception { + @Test void awsCredentials_withProgrammaticAuth() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -213,8 +208,7 @@ public void awsCredentials_withProgrammaticAuth() throws Exception { * exchanged for a GCP access token via GCP STS endpoint and then to impersonate the original * service account key. Runs an executable to get the OIDC token. */ - @Test - public void pluggableAuthCredentials() throws IOException { + @Test void pluggableAuthCredentials() throws IOException { PluggableAuthCredentials pluggableAuthCredentials = (PluggableAuthCredentials) ExternalAccountCredentials.fromJson( @@ -227,8 +221,7 @@ public void pluggableAuthCredentials() throws IOException { * Sets the service account impersonation object in configuration JSON with a non-default value * for token_lifetime_seconds and validates that the lifetime is used for the access token. */ - @Test - public void identityPoolCredentials_withServiceAccountImpersonationOptions() throws IOException { + @Test void identityPoolCredentials_withServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialConfig = buildIdentityPoolCredentialConfig(); Map map = new HashMap(); map.put("token_lifetime_seconds", 2800); @@ -254,8 +247,7 @@ public void identityPoolCredentials_withServiceAccountImpersonationOptions() thr * service account key. Retrieves the OIDC token from a Supplier that returns the subject token * when get() is called. */ - @Test - public void identityPoolCredentials_withProgrammaticAuth() throws IOException { + @Test void identityPoolCredentials_withProgrammaticAuth() throws IOException { IdentityPoolSubjectTokenSupplier tokenSupplier = (ExternalAccountSupplierContext context) -> { @@ -471,4 +463,4 @@ public AwsSecurityCredentials getCredentials(ExternalAccountSupplierContext cont return this.credentials; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index 54a3753e6..c8338fcc2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -30,32 +30,28 @@ */ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +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.HttpStatusCodes; import com.google.auth.Credentials; import com.google.auth.ServiceAccountSigner; import com.google.common.collect.ImmutableMap; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import org.mockito.Mockito; -@RunWith(JUnit4.class) -public class IamUtilsTest { +class IamUtilsTest { private static final String CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; private ServiceAccountCredentials credentials; - @Before - public void setup() throws IOException { + @BeforeEach void setup() throws IOException { // Mock this call for the Credentials because the IAM SignBlob RPC requires an access token. The // call is initialized with HttpCredentialsAdapter which will make a call to get the access // token @@ -64,8 +60,7 @@ public void setup() throws IOException { Mockito.when(credentials.getUniverseDomain()).thenReturn("googleapis.com"); } - @Test - public void sign_success_noRetry() { + @Test void sign_success_noRetry() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -90,8 +85,7 @@ public void sign_success_noRetry() { // The SignBlob RPC will retry up to three times before it gives up. This test will return two // 5xx status codes before returning a success. This test covers the cases where the number of // retry attempts is below the configured retry attempt count bounds (3 attempts). - @Test - public void sign_retryTwoTimes_success() { + @Test void sign_retryTwoTimes_success() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -124,8 +118,7 @@ public void sign_retryTwoTimes_success() { // The rpc will retry up to three times before it gives up. This test will enqueue three failed // status codes + messages before returning a success. After the third retry attempt, the request // will try one last time and the result will be reported back to the user. - @Test - public void sign_retryThreeTimes_success() { + @Test void sign_retryThreeTimes_success() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -161,8 +154,7 @@ public void sign_retryThreeTimes_success() { // The rpc will retry up to three times before it gives up. This test will enqueue four failed // status codes + messages before returning a success. After the third retry attempt, the request // will try one last time and the result will be reported back to the user. - @Test - public void sign_retryThreeTimes_exception() { + @Test void sign_retryThreeTimes_exception() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -206,8 +198,7 @@ public void sign_retryThreeTimes_exception() { assertEquals(4, transportFactory.getTransport().getNumRequests()); } - @Test - public void sign_4xxError_noRetry_exception() { + @Test void sign_4xxError_noRetry_exception() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -240,4 +231,4 @@ public void sign_4xxError_noRetry_exception() { // Only one request will have been made for a 4xx error (no retries) assertEquals(1, transportFactory.getTransport().getNumRequests()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java index 7dbf770c3..170c0d9ce 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java @@ -31,19 +31,15 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; - +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link IdTokenCredentials}. */ -@RunWith(JUnit4.class) -public class IdTokenCredentialsTest extends BaseSerializationTest { - @Test - public void hashCode_equals() throws IOException { +class IdTokenCredentialsTest extends BaseSerializationTest { + + @Test void hashCode_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -68,8 +64,7 @@ public void hashCode_equals() throws IOException { assertEquals(tokenCredential.hashCode(), otherCredential.hashCode()); } - @Test - public void toString_equals() throws IOException { + @Test void toString_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -94,8 +89,7 @@ public void toString_equals() throws IOException { assertEquals(tokenCredential.toString(), otherCredential.toString()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); @@ -113,4 +107,4 @@ public void serialize() throws IOException, ClassNotFoundException { IdTokenCredentials deserializedCredentials = serializeAndDeserialize(tokenCredential); assertEquals(tokenCredential, deserializedCredentials); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java index a8831a21b..00cf72b3b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java @@ -31,19 +31,16 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Date; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for AccessToken */ -@RunWith(JUnit4.class) -public class IdTokenTest extends BaseSerializationTest { + +class IdTokenTest extends BaseSerializationTest { private static final String TOKEN_1 = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjM0OTRiMWU3ODZjZGFkMDkyZTQyMzc2NmJiZTM3ZjU0ZWQ4N2IyMmQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhdWQiOiJodHRwczovL2Zvby5iYXIiLCJhenAiOiJzdmMtMi00MjlAbWluZXJhbC1taW51dGlhLTgyMC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInN1YiI6IjEwMDE0NzEwNjk5Njc2NDQ3OTA4NSIsImVtYWlsIjoic3ZjLTItNDI5QG1pbmVyYWwtbWludXRpYS04MjAuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaWF0IjoxNTY1Mzg3NTM4LCJleHAiOjE1NjUzOTExMzh9.foo"; @@ -53,31 +50,27 @@ public class IdTokenTest extends BaseSerializationTest { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2NjAxNjMxNjAsImV4cCI6MTY5MTY5OTE2MCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6ImFibTHag3M0x20ifQ.foo"; private static final Date EXPIRATION_DATE = new Date((long) 1565391138 * 1000); - @Test - public void constructor() throws IOException { + @Test void constructor() throws IOException { IdToken idToken = IdToken.create(TOKEN_1); assertEquals(TOKEN_1, idToken.getTokenValue()); assertEquals(EXPIRATION_DATE, idToken.getExpirationTime()); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertTrue(accessToken.equals(otherAccessToken)); assertTrue(otherAccessToken.equals(accessToken)); } - @Test - public void equals_false_token() throws IOException { + @Test void equals_false_token() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_2); assertFalse(accessToken.equals(otherAccessToken)); assertFalse(otherAccessToken.equals(accessToken)); } - @Test - public void toString_test() throws IOException { + @Test void toString_test() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); String expectedToString = String.format( @@ -86,15 +79,13 @@ public void toString_test() throws IOException { assertEquals(expectedToString, accessToken.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); @@ -102,9 +93,8 @@ public void serialize() throws IOException, ClassNotFoundException { assertEquals(accessToken.toString(), deserializedAccessToken.toString()); } - @Test - public void token_with_0x20() throws IOException { + @Test void token_with_0x20() throws IOException { IdToken accessToken = IdToken.create(TOKEN_WITH_0x20); assertEquals(TOKEN_WITH_0x20, accessToken.getTokenValue()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java index 2ee80c3d3..465324e65 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java @@ -31,21 +31,21 @@ 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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.auth.oauth2.IdentityPoolCredentialSource.IdentityPoolCredentialSourceType; import java.util.HashMap; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link IdentityPoolCredentialSource}. */ -@RunWith(JUnit4.class) -public class IdentityPoolCredentialsSourceTest { - @Test - public void constructor_certificateConfig() { +class IdentityPoolCredentialsSourceTest { + + @Test void constructor_certificateConfig() { Map certificateMap = new HashMap<>(); certificateMap.put("certificate_config_location", "/path/to/certificate"); @@ -63,8 +63,7 @@ public void constructor_certificateConfig() { credentialSource.getCertificateConfig().getCertificateConfigLocation()); } - @Test - public void constructor_certificateConfig_useDefault() { + @Test void constructor_certificateConfig_useDefault() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); @@ -79,8 +78,7 @@ public void constructor_certificateConfig_useDefault() { assertTrue(credentialSource.getCertificateConfig().useDefaultCertificateConfig()); } - @Test - public void constructor_certificateConfig_missingRequiredFields_throws() { + @Test void constructor_certificateConfig_missingRequiredFields_throws() { Map certificateMap = new HashMap<>(); // Missing both use_default_certificate_config and certificate_config_location. certificateMap.put("trust_chain_path", "path/to/trust/chain"); @@ -97,8 +95,7 @@ public void constructor_certificateConfig_missingRequiredFields_throws() { exception.getMessage()); } - @Test - public void constructor_certificateConfig_bothFieldsSet_throws() { + @Test void constructor_certificateConfig_bothFieldsSet_throws() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); certificateMap.put("certificate_config_location", "/path/to/certificate"); @@ -116,8 +113,7 @@ public void constructor_certificateConfig_bothFieldsSet_throws() { exception.getMessage()); } - @Test - public void constructor_certificateConfig_trustChainPath() { + @Test void constructor_certificateConfig_trustChainPath() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); certificateMap.put("trust_chain_path", "path/to/trust/chain"); @@ -134,8 +130,7 @@ public void constructor_certificateConfig_trustChainPath() { "path/to/trust/chain", credentialSource.getCertificateConfig().getTrustChainPath()); } - @Test - public void constructor_certificateConfig_invalidType_throws() { + @Test void constructor_certificateConfig_invalidType_throws() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", "invalid-type"); @@ -151,4 +146,4 @@ public void constructor_certificateConfig_invalidType_throws() { "Invalid type for 'use_default_certificate_config' in certificate configuration: expected Boolean, got String.", exception.getMessage()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java index cce03e085..7993a9c58 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java @@ -31,10 +31,16 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY; -import static org.junit.Assert.*; + import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -59,21 +65,21 @@ import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link IdentityPoolCredentials}. */ -@RunWith(MockitoJUnitRunner.class) -public class IdentityPoolCredentialsTest extends BaseSerializationTest { +@ExtendWith(MockitoExtension.class) +class IdentityPoolCredentialsTest extends BaseSerializationTest { private static final String STS_URL = "https://sts.googleapis.com/v1/token"; private static final IdentityPoolSubjectTokenSupplier testProvider = (ExternalAccountSupplierContext context) -> "testSubjectToken"; - @Test - public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + @Test void createdScoped_clonedCredentialWithAddedScopes() throws IOException { IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder(createBaseFileSourcedCredentials()) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -103,8 +109,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { assertEquals("universeDomain", newCredentials.getUniverseDomain()); } - @Test - public void retrieveSubjectToken_fileSourced() throws IOException { + @Test void retrieveSubjectToken_fileSourced() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -129,8 +134,7 @@ public void retrieveSubjectToken_fileSourced() throws IOException { assertEquals(credential, subjectToken); } - @Test - public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { + @Test void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -170,8 +174,7 @@ public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException assertEquals("subjectToken", subjectToken); } - @Test - public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { + @Test void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -191,8 +194,7 @@ public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOExc } } - @Test - public void retrieveSubjectToken_noFile_throws() { + @Test void retrieveSubjectToken_noFile_throws() { Map credentialSourceMap = new HashMap<>(); String path = "badPath"; credentialSourceMap.put("file", path); @@ -214,8 +216,7 @@ public void retrieveSubjectToken_noFile_throws() { } } - @Test - public void retrieveSubjectToken_urlSourced() throws IOException { + @Test void retrieveSubjectToken_urlSourced() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -231,8 +232,7 @@ public void retrieveSubjectToken_urlSourced() throws IOException { assertEquals(transportFactory.transport.getSubjectToken(), subjectToken); } - @Test - public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { + @Test void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -256,8 +256,7 @@ public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { assertEquals(transportFactory.transport.getSubjectToken(), subjectToken); } - @Test - public void retrieveSubjectToken_urlSourcedCredential_throws() { + @Test void retrieveSubjectToken_urlSourcedCredential_throws() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -282,8 +281,7 @@ public void retrieveSubjectToken_urlSourcedCredential_throws() { } } - @Test - public void retrieveSubjectToken_provider() throws IOException { + @Test void retrieveSubjectToken_provider() throws IOException { ExternalAccountSupplierContext emptyContext = ExternalAccountSupplierContext.newBuilder().setAudience("").setSubjectTokenType("").build(); IdentityPoolCredentials credentials = @@ -297,8 +295,7 @@ public void retrieveSubjectToken_provider() throws IOException { assertEquals(testProvider.getSubjectToken(emptyContext), subjectToken); } - @Test - public void retrieveSubjectToken_providerThrowsError() throws IOException { + @Test void retrieveSubjectToken_providerThrowsError() throws IOException { IOException testException = new IOException("test"); IdentityPoolSubjectTokenSupplier errorProvider = @@ -319,8 +316,7 @@ public void retrieveSubjectToken_providerThrowsError() throws IOException { } } - @Test - public void retrieveSubjectToken_supplierPassesContext() throws IOException { + @Test void retrieveSubjectToken_supplierPassesContext() throws IOException { ExternalAccountSupplierContext expectedContext = ExternalAccountSupplierContext.newBuilder() .setAudience(createBaseFileSourcedCredentials().getAudience()) @@ -342,8 +338,7 @@ public void retrieveSubjectToken_supplierPassesContext() throws IOException { credentials.retrieveSubjectToken(); } - @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -370,8 +365,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc ExternalAccountCredentialsTest.validateMetricsHeader(headers, "url", false, false); } - @Test - public void refreshAccessToken_internalOptionsSet() throws IOException { + @Test void refreshAccessToken_internalOptionsSet() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -403,8 +397,7 @@ public void refreshAccessToken_internalOptionsSet() throws IOException { assertEquals(expectedInternalOptions.toString(), query.get("options")); } - @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -434,8 +427,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept ExternalAccountCredentialsTest.validateMetricsHeader(headers, "url", true, false); } - @Test - public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + @Test void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -475,8 +467,7 @@ public void refreshAccessToken_withServiceAccountImpersonationOptions() throws I ExternalAccountCredentialsTest.validateMetricsHeader(headers, "url", true, true); } - @Test - public void refreshAccessToken_Provider() throws IOException { + @Test void refreshAccessToken_Provider() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -502,8 +493,7 @@ public void refreshAccessToken_Provider() throws IOException { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "programmatic", false, false); } - @Test - public void refreshAccessToken_providerWithServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_providerWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -532,8 +522,7 @@ public void refreshAccessToken_providerWithServiceAccountImpersonation() throws ExternalAccountCredentialsTest.validateMetricsHeader(headers, "programmatic", true, false); } - @Test - public void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -567,8 +556,7 @@ public void refreshAccessToken_workforceWithServiceAccountImpersonation() throws assertEquals(expectedInternalOptions.toString(), query.get("options")); } - @Test - public void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() + @Test void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -603,8 +591,7 @@ public void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() assertEquals("2800s", query.get("lifetime")); } - @Test - public void identityPoolCredentialSource_validFormats() { + @Test void identityPoolCredentialSource_validFormats() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -646,8 +633,7 @@ public void identityPoolCredentialSource_validFormats() { } } - @Test - public void identityPoolCredentialSource_caseInsensitive() { + @Test void identityPoolCredentialSource_caseInsensitive() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -689,8 +675,7 @@ public void identityPoolCredentialSource_caseInsensitive() { } } - @Test - public void identityPoolCredentialSource_invalidSourceType() { + @Test void identityPoolCredentialSource_invalidSourceType() { try { new IdentityPoolCredentialSource(new HashMap<>()); fail("Should not be able to continue without exception."); @@ -701,8 +686,7 @@ public void identityPoolCredentialSource_invalidSourceType() { } } - @Test - public void identityPoolCredentialSource_invalidFormatType() { + @Test void identityPoolCredentialSource_invalidFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -718,8 +702,7 @@ public void identityPoolCredentialSource_invalidFormatType() { } } - @Test - public void identityPoolCredentialSource_nullFormatType() { + @Test void identityPoolCredentialSource_nullFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -735,8 +718,7 @@ public void identityPoolCredentialSource_nullFormatType() { } } - @Test - public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { + @Test void identityPoolCredentialSource_subjectTokenFieldNameUnset() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -754,8 +736,7 @@ public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { } } - @Test - public void builder_allFields() throws IOException { + @Test void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentialSource credentialSource = createFileCredentialSource(); @@ -790,8 +771,7 @@ public void builder_allFields() throws IOException { assertEquals("universeDomain", credentials.getUniverseDomain()); } - @Test - public void builder_subjectTokenSupplier() { + @Test void builder_subjectTokenSupplier() { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -812,8 +792,7 @@ public void builder_subjectTokenSupplier() { assertEquals(testProvider, credentials.getIdentityPoolSubjectTokenSupplier()); } - @Test - public void builder_invalidWorkforceAudiences_throws() { + @Test void builder_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -847,8 +826,7 @@ public void builder_invalidWorkforceAudiences_throws() { } } - @Test - public void builder_emptyWorkforceUserProjectWithWorkforceAudience() { + @Test void builder_emptyWorkforceUserProjectWithWorkforceAudience() { // No exception should be thrown. IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder() @@ -866,8 +844,7 @@ public void builder_emptyWorkforceUserProjectWithWorkforceAudience() { assertTrue(credentials.isWorkforcePoolConfiguration()); } - @Test - public void builder_supplierAndCredSourceThrows() { + @Test void builder_supplierAndCredSourceThrows() { try { IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder() @@ -886,8 +863,7 @@ public void builder_supplierAndCredSourceThrows() { } } - @Test - public void builder_noSupplierOrCredSourceThrows() throws IOException { + @Test void builder_noSupplierOrCredSourceThrows() throws IOException { try { IdentityPoolCredentials credentials = @@ -904,8 +880,7 @@ public void builder_noSupplierOrCredSourceThrows() throws IOException { } } - @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + @Test void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentialSource credentialSource = createFileCredentialSource(); @@ -939,8 +914,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void newBuilder_allFields() throws IOException { + @Test void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -981,8 +955,7 @@ public void newBuilder_allFields() throws IOException { assertEquals(credentials.getUniverseDomain(), newBuilderCreds.getUniverseDomain()); } - @Test - public void newBuilder_noUniverseDomain_defaults() throws IOException { + @Test void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -1022,8 +995,7 @@ public void newBuilder_noUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, newBuilderCreds.getUniverseDomain()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { IdentityPoolCredentials testCredentials = IdentityPoolCredentials.newBuilder(createBaseFileSourcedCredentials()) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -1040,8 +1012,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(Clock.SYSTEM, deserializedCredentials.clock); } - @Test - public void build_withCertificateSourceAndCustomX509Provider_success() + @Test void build_withCertificateSourceAndCustomX509Provider_success() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Create an empty KeyStore and a spy on a custom X509Provider. KeyStore keyStore = KeyStore.getInstance("JKS"); @@ -1070,23 +1041,22 @@ public void build_withCertificateSourceAndCustomX509Provider_success() .build(); // Verify successful creation and correct internal setup. - assertNotNull("Credentials should be successfully created", credentials); + assertNotNull(credentials, "Credentials should be successfully created"); assertTrue( - "Subject token supplier should be for certificates", credentials.getIdentityPoolSubjectTokenSupplier() - instanceof CertificateIdentityPoolSubjectTokenSupplier); + instanceof CertificateIdentityPoolSubjectTokenSupplier, + "Subject token supplier should be for certificates"); assertEquals( - "Metrics header should indicate certificate source", IdentityPoolCredentials.CERTIFICATE_METRICS_HEADER_VALUE, - credentials.getCredentialSourceType()); + credentials.getCredentialSourceType(), + "Metrics header should indicate certificate source"); // Verify the custom provider methods were called during build. verify(x509Provider).getKeyStore(); verify(x509Provider).getCertificatePath(); } - @Test - public void build_withDefaultCertificate_throwsOnTransportInitFailure() { + @Test void build_withDefaultCertificate_throwsOnTransportInitFailure() { // Setup credential source to use default certificate config. Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", false); @@ -1111,8 +1081,7 @@ public void build_withDefaultCertificate_throwsOnTransportInitFailure() { exception.getMessage()); } - @Test - public void build_withCustomProvider_throwsOnGetKeyStore() + @Test void build_withCustomProvider_throwsOnGetKeyStore() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Simulate a scenario where the X509Provider fails to load the KeyStore, typically due to an // IOException when reading the certificate or private key files. @@ -1141,8 +1110,7 @@ public void build_withCustomProvider_throwsOnGetKeyStore() exception.getMessage()); } - @Test - public void build_withCustomProvider_throwsOnGetCertificatePath() + @Test void build_withCustomProvider_throwsOnGetCertificatePath() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Simulate a scenario where the X509Provider cannot access or read the certificate // configuration file needed to determine the certificate path, resulting in an IOException. @@ -1304,4 +1272,4 @@ void setShouldThrowOnGetCertificatePath(boolean shouldThrow) { this.shouldThrowOnGetCertificatePath = shouldThrow; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java index 1cfde9cf8..f8a593652 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java @@ -31,15 +31,15 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -71,14 +71,12 @@ import java.util.List; import java.util.Map; import java.util.TimeZone; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Test case for {@link ImpersonatedCredentials}. */ -@RunWith(JUnit4.class) -public class ImpersonatedCredentialsTest extends BaseSerializationTest { + +class ImpersonatedCredentialsTest extends BaseSerializationTest { public static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -157,8 +155,7 @@ public class ImpersonatedCredentialsTest extends BaseSerializationTest { private GoogleCredentials sourceCredentials; private MockIAMCredentialsServiceTransportFactory mockTransportFactory; - @Before - public void setup() throws IOException { + @BeforeEach void setup() throws IOException { sourceCredentials = getSourceCredentials(); mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); } @@ -180,8 +177,7 @@ static GoogleCredentials getSourceCredentials() throws IOException { return sourceCredentials; } - @Test() - public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { + @Test() void fromJson_userAsSource_WithQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -203,8 +199,7 @@ public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() - public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { + @Test() void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -226,8 +221,7 @@ public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() - public void fromJson_userAsSource_MissingDelegatesField() throws IOException { + @Test() void fromJson_userAsSource_MissingDelegatesField() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -250,8 +244,7 @@ public void fromJson_userAsSource_MissingDelegatesField() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() - public void fromJson_ServiceAccountAsSource() throws IOException { + @Test() void fromJson_ServiceAccountAsSource() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, DELEGATES, QUOTA_PROJECT_ID, IMMUTABLE_SCOPES_LIST); @@ -267,8 +260,7 @@ public void fromJson_ServiceAccountAsSource() throws IOException { assertTrue(sourceCredentials instanceof ServiceAccountCredentials); } - @Test() - public void fromJson_InvalidFormat() throws IOException { + @Test() void fromJson_InvalidFormat() throws IOException { GenericJson json = buildInvalidCredentialsJson(); try { ImpersonatedCredentials.fromJson(json, mockTransportFactory); @@ -278,8 +270,7 @@ public void fromJson_InvalidFormat() throws IOException { } } - @Test() - public void createScopedRequired_True() { + @Test() void createScopedRequired_True() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -291,8 +282,7 @@ public void createScopedRequired_True() { assertTrue(targetCredentials.createScopedRequired()); } - @Test() - public void createScopedRequired_False() { + @Test() void createScopedRequired_False() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -304,8 +294,7 @@ public void createScopedRequired_False() { assertFalse(targetCredentials.createScopedRequired()); } - @Test - public void createScoped() { + @Test void createScoped() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -327,8 +316,7 @@ public void createScoped() { assertEquals(Arrays.asList("scope1", "scope2"), scoped_credentials.getScopes()); } - @Test - public void createScoped_existingAccessTokenInvalidated() throws IOException { + @Test void createScoped_existingAccessTokenInvalidated() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -352,8 +340,7 @@ public void createScoped_existingAccessTokenInvalidated() throws IOException { assertNull(scoped_credentials.getAccessToken()); } - @Test - public void createScopedWithImmutableScopes() { + @Test void createScopedWithImmutableScopes() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -375,8 +362,7 @@ public void createScopedWithImmutableScopes() { assertEquals(Arrays.asList("scope1", "scope2"), scoped_credentials.getScopes()); } - @Test - public void createScopedWithIamEndpointOverride() { + @Test void createScopedWithIamEndpointOverride() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -394,8 +380,7 @@ public void createScopedWithIamEndpointOverride() { targetCredentials.getIamEndpointOverride(), scoped_credentials.getIamEndpointOverride()); } - @Test - public void refreshAccessToken_unauthorized() throws IOException { + @Test void refreshAccessToken_unauthorized() throws IOException { String expectedMessage = "The caller does not have permission"; mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory @@ -423,8 +408,7 @@ public void refreshAccessToken_unauthorized() throws IOException { } } - @Test() - public void refreshAccessToken_malformedTarget() throws IOException { + @Test() void refreshAccessToken_malformedTarget() throws IOException { String invalidTargetEmail = "foo"; String expectedMessage = "Request contains an invalid argument"; @@ -453,16 +437,14 @@ public void refreshAccessToken_malformedTarget() throws IOException { } } - @Test() - public void credential_with_zero_lifetime() throws IllegalStateException { + @Test() void credential_with_zero_lifetime() throws IllegalStateException { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, IMMUTABLE_SCOPES_LIST, 0); assertEquals(3600, targetCredentials.getLifetime()); } - @Test() - public void credential_with_invalid_lifetime() throws IOException, IllegalStateException { + @Test() void credential_with_invalid_lifetime() throws IOException, IllegalStateException { try { ImpersonatedCredentials targetCredentials = @@ -482,8 +464,7 @@ public void credential_with_invalid_lifetime() throws IOException, IllegalStateE } } - @Test() - public void credential_with_invalid_scope() throws IOException, IllegalStateException { + @Test() void credential_with_invalid_scope() throws IOException, IllegalStateException { assertThrows( NullPointerException.class, () -> @@ -491,8 +472,7 @@ public void credential_with_invalid_scope() throws IOException, IllegalStateExce sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, null, VALID_LIFETIME)); } - @Test() - public void refreshAccessToken_success() throws IOException, IllegalStateException { + @Test() void refreshAccessToken_success() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -517,8 +497,7 @@ public void refreshAccessToken_success() throws IOException, IllegalStateExcepti assertTrue(requestHeader.containsKey("authorization")); } - @Test() - public void refreshAccessToken_success_SSJflow() throws IOException, IllegalStateException { + @Test() void refreshAccessToken_success_SSJflow() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -543,8 +522,7 @@ public void refreshAccessToken_success_SSJflow() throws IOException, IllegalStat DEFAULT_IMPERSONATION_URL, mockTransportFactory.getTransport().getRequest().getUrl()); } - @Test() - public void refreshAccessToken_success_nonGDU() throws IOException, IllegalStateException { + @Test() void refreshAccessToken_success_nonGDU() throws IOException, IllegalStateException { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(TEST_UNIVERSE_DOMAIN); transportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -571,8 +549,7 @@ public void refreshAccessToken_success_nonGDU() throws IOException, IllegalState assertEquals(NONGDU_IMPERSONATION_URL, transportFactory.getTransport().getRequest().getUrl()); } - @Test - public void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { + @Test void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -595,8 +572,7 @@ public void refreshAccessToken_endpointOverride() throws IOException, IllegalSta IMPERSONATION_OVERRIDE_URL, mockTransportFactory.getTransport().getRequest().getUrl()); } - @Test() - public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { + @Test() void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -618,8 +594,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalS assertEquals(QUOTA_PROJECT_ID, headerValues.get(0)); } - @Test() - public void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { + @Test() void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -637,8 +612,7 @@ public void getRequestMetadata_withoutQuotaProjectId() throws IOException, Illeg assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test() - public void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { + @Test() void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -656,8 +630,7 @@ public void refreshAccessToken_delegates_success() throws IOException, IllegalSt assertEquals(ACCESS_TOKEN, targetCredentials.refreshAccessToken().getTokenValue()); } - @Test - public void refreshAccessToken_GMT_dateParsedCorrectly() + @Test void refreshAccessToken_GMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -683,8 +656,7 @@ public void refreshAccessToken_GMT_dateParsedCorrectly() == targetCredentials.refreshAccessToken().getExpirationTimeMillis()); } - @Test - public void refreshAccessToken_nonGMT_dateParsedCorrectly() + @Test void refreshAccessToken_nonGMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -710,8 +682,7 @@ public void refreshAccessToken_nonGMT_dateParsedCorrectly() == targetCredentials.refreshAccessToken().getExpirationTimeMillis()); } - @Test - public void refreshAccessToken_invalidDate() throws IllegalStateException { + @Test void refreshAccessToken_invalidDate() throws IllegalStateException { String expectedMessage = "Unparseable date"; mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken("foo"); @@ -734,8 +705,7 @@ public void refreshAccessToken_invalidDate() throws IllegalStateException { } } - @Test - public void getAccount_sameAs() { + @Test void getAccount_sameAs() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -751,8 +721,7 @@ public void getAccount_sameAs() { assertEquals(IMPERSONATED_CLIENT_EMAIL, targetCredentials.getAccount()); } - @Test - public void sign_sameAs() { + @Test void sign_sameAs() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -774,8 +743,7 @@ public void sign_sameAs() { assertArrayEquals(expectedSignature, targetCredentials.sign(expectedSignature)); } - @Test - public void sign_requestIncludesDelegates() throws IOException { + @Test void sign_requestIncludesDelegates() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -806,8 +774,7 @@ public void sign_requestIncludesDelegates() throws IOException { assertEquals(delegates, body.get("delegates")); } - @Test - public void sign_usesSourceCredentials() { + @Test void sign_usesSourceCredentials() { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date expiry = c.getTime(); @@ -840,8 +807,7 @@ public void sign_usesSourceCredentials() { assertEquals("Bearer source-token", request.getFirstHeaderValue("Authorization")); } - @Test - public void sign_accessDenied_throws() { + @Test void sign_accessDenied_throws() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -873,8 +839,7 @@ public void sign_accessDenied_throws() { } } - @Test - public void sign_serverError_throws() { + @Test void sign_serverError_throws() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -906,8 +871,7 @@ public void sign_serverError_throws() { } } - @Test - public void sign_sameAs_nonGDU() { + @Test void sign_sameAs_nonGDU() { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory("test.com"); @@ -938,8 +902,7 @@ public void sign_sameAs_nonGDU() { assertArrayEquals(expectedSignature, targetCredentials.sign(expectedSignature)); } - @Test - public void sign_universeDomainException() throws IOException { + @Test void sign_universeDomainException() throws IOException { // Currently, no credentials allowed as source credentials throws exception for // getUniverseDomain(), mock this behavior for test only. ServiceAccountCredentials // should not throw for getUniverseDomain() calls. @@ -964,8 +927,7 @@ public void sign_universeDomainException() throws IOException { assertEquals("Failed to sign: Error obtaining universe domain", exception.getMessage()); } - @Test - public void idTokenWithAudience_sameAs() throws IOException { + @Test void idTokenWithAudience_sameAs() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -996,8 +958,7 @@ public void idTokenWithAudience_sameAs() throws IOException { (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test - public void idTokenWithAudience_withEmail() throws IOException { + @Test void idTokenWithAudience_withEmail() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1033,8 +994,7 @@ public void idTokenWithAudience_withEmail() throws IOException { assertTrue(requestHeader.containsKey("authorization")); } - @Test - public void idTokenWithAudience_sameAs_nonGDU() throws IOException { + @Test void idTokenWithAudience_sameAs_nonGDU() throws IOException { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory("test.com"); transportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -1072,8 +1032,7 @@ public void idTokenWithAudience_sameAs_nonGDU() throws IOException { (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test - public void idToken_withServerError() { + @Test void idToken_withServerError() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1106,8 +1065,7 @@ public void idToken_withServerError() { } } - @Test - public void idToken_withOtherError() { + @Test void idToken_withOtherError() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1140,8 +1098,7 @@ public void idToken_withOtherError() { } } - @Test - public void universeDomain_defaultUniverse() throws IOException { + @Test void universeDomain_defaultUniverse() throws IOException { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -1154,8 +1111,7 @@ public void universeDomain_defaultUniverse() throws IOException { assertTrue(impersonatedCredentials.isDefaultUniverseDomain()); } - @Test - public void universeDomain_getFromSourceCredentials() throws IOException { + @Test void universeDomain_getFromSourceCredentials() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); ImpersonatedCredentials impersonatedCredentials = @@ -1173,8 +1129,7 @@ public void universeDomain_getFromSourceCredentials() throws IOException { assertFalse(impersonatedCredentials.isExplicitUniverseDomain()); } - @Test - public void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws IOException { + @Test void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); IllegalStateException illegalStateException = @@ -1196,8 +1151,7 @@ public void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws illegalStateException.getMessage()); } - @Test - public void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOException { + @Test void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); ImpersonatedCredentials impersonatedCredentials = @@ -1217,16 +1171,14 @@ public void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOExce assertTrue(impersonatedCredentials.isExplicitUniverseDomain()); } - @Test - public void scopes_userConfigured() { + @Test void scopes_userConfigured() { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.newBuilder().setScopes(IMMUTABLE_SCOPES_LIST).build(); assertArrayEquals( IMMUTABLE_SCOPES_LIST.toArray(), impersonatedCredentials.getScopes().toArray()); } - @Test - public void scopes_fromJson() throws IOException { + @Test void scopes_fromJson() throws IOException { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.fromJson( buildImpersonationCredentialsJson( @@ -1239,8 +1191,7 @@ public void scopes_fromJson() throws IOException { // Tests that user configured scopes has precedence over the one in the json. // From the ADC flow, the json is parsed and the credential is returned back // to the user - @Test - public void scopes_userConfiguredAndFromJson() throws IOException { + @Test void scopes_userConfiguredAndFromJson() throws IOException { List userConfiguredScopes = ImmutableList.of("nonsense-scopes"); ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.fromJson( @@ -1253,8 +1204,7 @@ public void scopes_userConfiguredAndFromJson() throws IOException { userConfiguredScopes.toArray(), newImpersonatedCredentials.getScopes().toArray()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1280,8 +1230,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); @@ -1427,4 +1376,4 @@ static InputStream writeImpersonationCredentialsStream( buildImpersonationCredentialsJson(impersonationUrl, delegates, quotaProjectId, scopes); return TestUtils.jsonToInputStream(json); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java index f95bd4cab..169f83885 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java @@ -31,22 +31,19 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static com.google.auth.oauth2.AwsCredentialsTest.buildAwsImdsv2CredentialSource; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import com.google.auth.oauth2.ExternalAccountCredentialsTest.MockExternalAccountCredentialsTransportFactory; import com.google.common.collect.ImmutableList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link InternalAwsSecurityCredentialsSupplier}. */ -@RunWith(JUnit4.class) -public class InternalAwsSecurityCredentialsSupplierTest { - @Test - public void shouldUseMetadataServer_withRequiredEnvironmentVariables() { + +class InternalAwsSecurityCredentialsSupplierTest { + @Test void shouldUseMetadataServer_withRequiredEnvironmentVariables() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -68,8 +65,7 @@ public void shouldUseMetadataServer_withRequiredEnvironmentVariables() { } } - @Test - public void shouldUseMetadataServer_missingRegion() { + @Test void shouldUseMetadataServer_missingRegion() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -85,8 +81,7 @@ public void shouldUseMetadataServer_missingRegion() { assertTrue(supplier.shouldUseMetadataServer()); } - @Test - public void shouldUseMetadataServer_missingAwsAccessKeyId() { + @Test void shouldUseMetadataServer_missingAwsAccessKeyId() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -107,8 +102,7 @@ public void shouldUseMetadataServer_missingAwsAccessKeyId() { } } - @Test - public void shouldUseMetadataServer_missingAwsSecretAccessKey() { + @Test void shouldUseMetadataServer_missingAwsSecretAccessKey() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -129,8 +123,7 @@ public void shouldUseMetadataServer_missingAwsSecretAccessKey() { } } - @Test - public void shouldUseMetadataServer_missingAwsSecurityCreds() { + @Test void shouldUseMetadataServer_missingAwsSecurityCreds() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -150,8 +143,7 @@ public void shouldUseMetadataServer_missingAwsSecurityCreds() { } } - @Test - public void shouldUseMetadataServer_noEnvironmentVars() { + @Test void shouldUseMetadataServer_noEnvironmentVars() { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -162,4 +154,4 @@ public void shouldUseMetadataServer_noEnvironmentVars() { transportFactory); assertTrue(supplier.shouldUseMetadataServer()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java index dff076658..1bba79bef 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java @@ -31,22 +31,17 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - +import static org.junit.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 { +class JwtClaimsTest { - @Test - public void testMergeOverwritesFields() { + @Test void testMergeOverwritesFields() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -66,8 +61,7 @@ public void testMergeOverwritesFields() { assertEquals("subject-2", merged.getSubject()); } - @Test - public void testMergeDefaultValues() { + @Test void testMergeDefaultValues() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -82,8 +76,7 @@ public void testMergeDefaultValues() { assertEquals("subject-1", merged.getSubject()); } - @Test - public void testMergeNull() { + @Test void testMergeNull() { JwtClaims claims1 = JwtClaims.newBuilder().build(); JwtClaims claims2 = JwtClaims.newBuilder().build(); JwtClaims merged = claims1.merge(claims2); @@ -95,8 +88,7 @@ public void testMergeNull() { assertTrue(merged.getAdditionalClaims().isEmpty()); } - @Test - public void testEquals() { + @Test void testEquals() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -113,15 +105,13 @@ public void testEquals() { assertEquals(claims1, claims2); } - @Test - public void testAdditionalClaimsDefaults() { + @Test void testAdditionalClaimsDefaults() { JwtClaims claims = JwtClaims.newBuilder().build(); assertNotNull(claims.getAdditionalClaims()); assertTrue(claims.getAdditionalClaims().isEmpty()); } - @Test - public void testMergeAdditionalClaims() { + @Test void testMergeAdditionalClaims() { JwtClaims claims1 = JwtClaims.newBuilder().setAdditionalClaims(Collections.singletonMap("foo", "bar")).build(); JwtClaims claims2 = @@ -140,8 +130,7 @@ public void testMergeAdditionalClaims() { assertEquals("qwer", mergedAdditionalClaims.get("asdf")); } - @Test - public void testIsComplete() { + @Test void testIsComplete() { // Test JwtClaim is complete if audience is not set but scope is provided. JwtClaims claims = JwtClaims.newBuilder() @@ -151,4 +140,4 @@ public void testIsComplete() { .build(); assertTrue(claims.isComplete()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java index 900245492..6c654f659 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java @@ -31,12 +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.fail; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; @@ -47,12 +46,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" @@ -79,8 +75,7 @@ static PrivateKey getPrivateKey() { } } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -101,8 +96,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(deserializedCredentials.getClock(), Clock.SYSTEM); } - @Test - public void builder_requiresPrivateKey() { + @Test void builder_requiresPrivateKey() { try { JwtClaims claims = JwtClaims.newBuilder() @@ -117,8 +111,7 @@ public void builder_requiresPrivateKey() { } } - @Test - public void builder_requiresClaims() { + @Test void builder_requiresClaims() { try { JwtCredentials.newBuilder() .setPrivateKeyId(PRIVATE_KEY_ID) @@ -130,8 +123,7 @@ public void builder_requiresClaims() { } } - @Test - public void builder_requiresCompleteClaims() { + @Test void builder_requiresCompleteClaims() { try { JwtClaims claims = JwtClaims.newBuilder().build(); JwtCredentials.newBuilder() @@ -145,8 +137,7 @@ public void builder_requiresCompleteClaims() { } } - @Test - public void jwtWithClaims_overwritesClaims() throws IOException { + @Test void jwtWithClaims_overwritesClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -170,8 +161,7 @@ public void jwtWithClaims_overwritesClaims() throws IOException { verifyJwtAccess(metadata, "some-audience2", "some-issuer2", "some-subject2", PRIVATE_KEY_ID); } - @Test - public void jwtWithClaims_defaultsClaims() throws IOException { + @Test void jwtWithClaims_defaultsClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -190,8 +180,7 @@ public void jwtWithClaims_defaultsClaims() throws IOException { verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", PRIVATE_KEY_ID); } - @Test - public void getRequestMetadata_hasJwtAccess() throws IOException { + @Test void getRequestMetadata_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -209,8 +198,7 @@ public void getRequestMetadata_hasJwtAccess() throws IOException { verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", PRIVATE_KEY_ID); } - @Test - public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { + @Test void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -235,8 +223,7 @@ public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOExce Collections.singletonMap("foo", "bar")); } - @Test - public void privateKeyIdNull() throws IOException { + @Test void privateKeyIdNull() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -254,8 +241,7 @@ public void privateKeyIdNull() throws IOException { verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", null); } - @Test - public void privateKeyIdNotSpecified() throws IOException { + @Test void privateKeyIdNotSpecified() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -295,15 +281,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()); @@ -314,4 +300,4 @@ private void verifyJwtAccess( assertEquals(entry.getValue(), signature.getPayload().get(entry.getKey())); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java index 631547349..a3aba5ad1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java @@ -31,6 +31,9 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static com.google.auth.TestUtils.getDefaultExpireTime; import static com.google.auth.oauth2.ImpersonatedCredentialsTest.DEFAULT_IMPERSONATION_URL; import static com.google.auth.oauth2.ImpersonatedCredentialsTest.IMMUTABLE_SCOPES_LIST; @@ -46,9 +49,6 @@ import static com.google.auth.oauth2.UserCredentialsTest.CLIENT_ID; import static com.google.auth.oauth2.UserCredentialsTest.CLIENT_SECRET; import static com.google.auth.oauth2.UserCredentialsTest.REFRESH_TOKEN; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import ch.qos.logback.classic.spi.ILoggingEvent; import com.google.api.client.http.HttpStatusCodes; @@ -62,8 +62,8 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.KeyValuePair; @@ -73,7 +73,7 @@ * credentials test classes with addition of test logging appender setup and test logic for logging. * This duplicates tests setups, but centralizes logging test setup in this class. */ -public class LoggingTest { +class LoggingTest { private TestAppender setupTestLogger(Class clazz) { TestAppender testAppender = new TestAppender(); @@ -83,16 +83,14 @@ private TestAppender setupTestLogger(Class clazz) { return testAppender; } - @BeforeClass - public static void setup() { + @BeforeAll static void setup() { // mimic GOOGLE_SDK_JAVA_LOGGING = true TestEnvironmentProvider testEnvironmentProvider = new TestEnvironmentProvider(); testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); } - @Test - public void userCredentials_getRequestMetadata_fromRefreshToken_hasAccessToken() + @Test void userCredentials_getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(UserCredentials.class); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -154,8 +152,7 @@ boolean isValidJson(String jsonString) { } } - @Test - public void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws IOException { + @Test void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(ServiceAccountCredentials.class); GoogleCredentials credentials = ServiceAccountCredentialsTest.createDefaultBuilderWithToken(ACCESS_TOKEN) @@ -200,8 +197,7 @@ public void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws testAppender.stop(); } - @Test - public void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() + @Test void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { TestAppender testAppender = setupTestLogger(ServiceAccountCredentials.class); String nonGDU = "test.com"; @@ -259,8 +255,7 @@ public void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudience testAppender.stop(); } - @Test() - public void impersonatedCredentials_refreshAccessToken_success() + @Test() void impersonatedCredentials_refreshAccessToken_success() throws IOException, IllegalStateException { TestAppender testAppender = setupTestLogger(ImpersonatedCredentials.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = @@ -312,8 +307,7 @@ public void impersonatedCredentials_refreshAccessToken_success() testAppender.stop(); } - @Test - public void idTokenWithAudience_withEmail() throws IOException { + @Test void idTokenWithAudience_withEmail() throws IOException { TestAppender testAppender = setupTestLogger(IamUtils.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); @@ -373,8 +367,7 @@ public void idTokenWithAudience_withEmail() throws IOException { testAppender.stop(); } - @Test - public void sign_sameAs() throws IOException { + @Test void sign_sameAs() throws IOException { TestAppender testAppender = setupTestLogger(IamUtils.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); @@ -430,8 +423,7 @@ public void sign_sameAs() throws IOException { testAppender.stop(); } - @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + @Test void getRequestMetadata_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(ComputeEngineCredentials.class); MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -473,7 +465,7 @@ public void getRequestMetadata_hasAccessToken() throws IOException { @Test @SuppressWarnings("unchecked") - public void idTokenWithAudience_full() throws IOException { + void idTokenWithAudience_full() throws IOException { TestAppender testAppender = setupTestLogger(ComputeEngineCredentials.class); MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -488,7 +480,7 @@ public void idTokenWithAudience_full() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - assertTrue("Full ID Token format not provided", p.containsKey("google")); + assertTrue(p.containsKey("google"), "Full ID Token format not provided"); ArrayMap googleClaim = (ArrayMap) p.get("google"); assertTrue(googleClaim.containsKey("compute_engine")); @@ -522,4 +514,4 @@ public void idTokenWithAudience_full() throws IOException { testAppender.events.get(2).getKeyValuePairs().get(0).value); testAppender.stop(); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java index abad61f32..81d0d8ad1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java @@ -31,23 +31,20 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -public class LoggingUtilsTest { +class LoggingUtilsTest { private TestEnvironmentProvider testEnvironmentProvider; - @Before - public void setup() { + @BeforeEach void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } - @Test - public void testIsLoggingEnabled_true() { + @Test void testIsLoggingEnabled_true() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); assertTrue(LoggingUtils.isLoggingEnabled()); @@ -59,9 +56,8 @@ public void testIsLoggingEnabled_true() { assertTrue(LoggingUtils.isLoggingEnabled()); } - @Test - public void testIsLoggingEnabled_defaultToFalse() { + @Test void testIsLoggingEnabled_defaultToFalse() { LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); assertFalse(LoggingUtils.isLoggingEnabled()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java index eb035d09c..65d0ae791 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java @@ -31,17 +31,14 @@ package com.google.auth.oauth2; -import static org.junit.Assert.*; - +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.auth.CredentialTypeForMetrics; import com.google.auth.oauth2.MetricsUtils.RequestType; import java.util.regex.Pattern; -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 MetricsUtilsTest { +class MetricsUtilsTest { static final String VERSION_PATTERN = "gl-java/[\\d\\._-]+ auth/\\d+\\.\\d+\\.\\d+(-sp\\.\\d+)?(-SNAPSHOT)?"; static final String AUTH_REQUEST_TYPE_PATTERN = @@ -53,19 +50,17 @@ public class MetricsUtilsTest { static final String METRICS_PATTERN_NO_CRED_TYPE = VERSION_PATTERN + AUTH_REQUEST_TYPE_PATTERN; private static void assertPatterns(String contentToTest, String patternString) { - assertNotNull("metric header string should not be null", contentToTest); + assertNotNull(contentToTest, "metric header string should not be null"); Pattern pattern = Pattern.compile(patternString); assertTrue(pattern.matcher(contentToTest).matches()); } - @Test - public void getLanguageAndAuthLibraryVersionsTest() { + @Test void getLanguageAndAuthLibraryVersionsTest() { String version = MetricsUtils.getLanguageAndAuthLibraryVersions(); assertPatterns(version, VERSION_PATTERN); } - @Test - public void getGoogleCredentialsMetricsHeaderTest() { + @Test void getGoogleCredentialsMetricsHeaderTest() { String metricsStringNoRequestType = MetricsUtils.getGoogleCredentialsMetricsHeader( RequestType.UNTRACKED, CredentialTypeForMetrics.USER_CREDENTIALS); @@ -86,4 +81,4 @@ public void getGoogleCredentialsMetricsHeaderTest() { RequestType.UNTRACKED, CredentialTypeForMetrics.DO_NOT_SEND); assertPatterns(metricsStringNoTypes, VERSION_PATTERN); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java index ce36548e2..ee51b4e1f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java @@ -66,4 +66,4 @@ int runTasksExhaustively() { int numTasks() { return tasks.size(); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java index d1bfdaecf..5d4f41ed1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java @@ -31,10 +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; import com.google.api.client.json.GenericJson; @@ -299,4 +298,4 @@ public void setExpireTime(String expireTime) { public void setMetadataServerContentType(String contentType) { this.metadataServerContentType = contentType; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java b/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java index 00976e00f..c6d0f7fea 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java @@ -12,4 +12,4 @@ public class MockHttpTransportFactory implements HttpTransportFactory { public HttpTransport create() { return transport; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java index cbd57d115..de34a253e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java @@ -228,4 +228,4 @@ public LowLevelHttpResponse execute() throws IOException { return this.request; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java index a1df56b4b..4bc3c9154 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java @@ -53,4 +53,4 @@ public MockIAMCredentialsServiceTransport getTransport() { public HttpTransport create() { return transport; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java index 725a124fc..650951c3d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java @@ -352,4 +352,4 @@ protected boolean isMtlsConfigRequestUrl(String url) { ComputeEngineCredentials.getMetadataServerUrl() + SecureSessionAgent.S2A_CONFIG_ENDPOINT_POSTFIX); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java b/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java index 0d98a9a8e..82884b82c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java @@ -78,4 +78,4 @@ private void checkNotSet() { Preconditions.checkState(this.metadata == null); Preconditions.checkState(this.exception == null); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java index 5b1b3fded..52e3d5376 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java @@ -31,9 +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; import com.google.api.client.http.LowLevelHttpResponse; @@ -201,4 +200,4 @@ public void setReturnAccessBoundarySessionKey(boolean returnAccessBoundarySessio public int getRequestCount() { return requestCount; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java index 3ef4df2fe..60af67959 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java @@ -92,4 +92,4 @@ private MockLowLevelHttpResponse makeSuccessResponse() { successResponse.setContent(SUCCESS_CONTENT); return successResponse; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java index a61c185b5..b16cac1be 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java @@ -437,4 +437,4 @@ private void validateAdditionalParameters(Map query) { } } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java index a1d5831ad..66220d164 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java @@ -11,4 +11,4 @@ public class MockTokenServerTransportFactory implements HttpTransportFactory { public HttpTransport create() { return transport; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java index 62aa08225..7e50d9577 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java @@ -31,15 +31,15 @@ package com.google.auth.oauth2; +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 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 com.google.api.client.util.Clock; import com.google.auth.TestClock; @@ -70,17 +70,15 @@ 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.Ignore; -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.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; /** 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"; @@ -90,25 +88,21 @@ 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() { + @Test void constructor_storesAccessToken() { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); } - @Test - public void constructor_overrideMargin() throws Throwable { + @Test void constructor_overrideMargin() throws Throwable { Duration staleMargin = Duration.ofMinutes(3); Duration expirationMargin = Duration.ofMinutes(2); @@ -188,8 +182,7 @@ public AccessToken refreshAccessToken() throws IOException { lastMetadata = credentials.getRequestMetadata(); } - @Test - public void getAuthenticationType_returnsOAuth2() { + @Test void getAuthenticationType_returnsOAuth2() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -199,8 +192,7 @@ public void getAuthenticationType_returnsOAuth2() { assertEquals(credentials.getAuthenticationType(), "OAuth2"); } - @Test - public void hasRequestMetadata_returnsTrue() { + @Test void hasRequestMetadata_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -210,8 +202,7 @@ public void hasRequestMetadata_returnsTrue() { assertTrue(credentials.hasRequestMetadata()); } - @Test - public void hasRequestMetadataOnly_returnsTrue() { + @Test void hasRequestMetadataOnly_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -221,8 +212,7 @@ public void hasRequestMetadataOnly_returnsTrue() { assertTrue(credentials.hasRequestMetadata()); } - @Test - public void addChangeListener_notifiesOnRefresh() throws IOException { + @Test void addChangeListener_notifiesOnRefresh() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -259,8 +249,7 @@ public void addChangeListener_notifiesOnRefresh() throws IOException { assertEquals(2, listener.callCount); } - @Test - public void removeChangeListener_unregisters_observer() throws IOException { + @Test void removeChangeListener_unregisters_observer() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -296,8 +285,7 @@ public void removeChangeListener_unregisters_observer() throws IOException { assertEquals(2, listener.callCount); } - @Test - public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { + @Test void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -350,8 +338,7 @@ public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test - public void getRequestMetadata_async() throws IOException { + @Test void getRequestMetadata_async() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -420,8 +407,7 @@ public void getRequestMetadata_async() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test - public void getRequestMetadata_async_refreshRace() + @Test void getRequestMetadata_async_refreshRace() throws ExecutionException, InterruptedException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -479,8 +465,7 @@ public Map> call() throws Exception { assertEquals(metadata, callback.metadata); } - @Test - public void getRequestMetadata_temporaryToken_hasToken() throws IOException { + @Test void getRequestMetadata_temporaryToken_hasToken() throws IOException { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); @@ -489,8 +474,7 @@ public void getRequestMetadata_temporaryToken_hasToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { + @Test void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); @@ -559,8 +543,7 @@ public AccessToken refreshAccessToken() { } } - @Test - public void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { + @Test 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); @@ -628,8 +611,7 @@ public AccessToken refreshAccessToken() { } } - @Test - public void getRequestMetadata_singleFlightErrorSharing() { + @Test void getRequestMetadata_singleFlightErrorSharing() { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -675,12 +657,7 @@ public Map> call() throws Exception { Throwable actualBlockingError = assertThrows( ExecutionException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - blockingCall.get(); - } - }) + () -> blockingCall.get()) .getCause(); assertEquals(error, actualBlockingError); @@ -688,17 +665,11 @@ public void run() throws Throwable { RuntimeException actualAsyncError = assertThrows( RuntimeException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - callback1.awaitResult(); - } - }); + () -> callback1.awaitResult()); assertEquals(error, actualAsyncError); } - @Test - public void getRequestMetadata_syncErrorsIncludeCallingStackframe() { + @Test void getRequestMetadata_syncErrorsIncludeCallingStackframe() { final OAuth2Credentials creds = new OAuth2Credentials() { @Override @@ -728,8 +699,7 @@ public AccessToken refreshAccessToken() { assertEquals(expectedStacktrace, actualStacktrace); } - @Test - public void refresh_refreshesToken() throws IOException { + @Test void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -764,8 +734,7 @@ public void refresh_refreshesToken() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test - public void refreshIfExpired_refreshesToken() throws IOException { + @Test void refreshIfExpired_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -808,15 +777,14 @@ public void refreshIfExpired_refreshesToken() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test(expected = IllegalStateException.class) - public void refresh_temporaryToken_throws() throws IOException { + @Test + void refresh_temporaryToken_throws() throws IOException { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); - credentials.refresh(); + assertThrows(IllegalStateException.class, () -> credentials.refresh()); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken1, null)).build(); @@ -826,8 +794,7 @@ public void equals_true() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_accessToken() throws IOException { + @Test void equals_false_accessToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = @@ -838,8 +805,7 @@ public void equals_false_accessToken() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken("1/MkSJoj1xsli0AccessToken_NKPY2", null); OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); @@ -853,8 +819,7 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -863,8 +828,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -876,8 +840,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - @Ignore - public void updateTokenValueBeforeWake() throws IOException, InterruptedException { + @Disabled void updateTokenValueBeforeWake() throws IOException, InterruptedException { final SettableFuture refreshedTokenFuture = SettableFuture.create(); AccessToken refreshedToken = new AccessToken("2/MkSJoj1xsli0AccessToken_NKPY2", null); refreshedTokenFuture.set(refreshedToken); @@ -985,4 +948,4 @@ public void onChanged(OAuth2Credentials credentials) throws IOException { callCount++; } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java index 1e636f813..523c4d6a6 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -31,10 +31,10 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.oauth2.OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN; import static com.google.auth.oauth2.OAuth2Credentials.DEFAULT_REFRESH_MARGIN; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import com.google.auth.TestUtils; import java.io.IOException; @@ -44,17 +44,14 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** 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() { + @Test void builder() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -72,8 +69,7 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test - public void builder_withRefreshAndExpirationMargins() { + @Test void builder_withRefreshAndExpirationMargins() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -100,8 +96,7 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test - public void builder_onlyRefreshMarginSet() { + @Test void builder_onlyRefreshMarginSet() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -126,8 +121,7 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test - public void builder_onlyExpirationMarginSet() { + @Test void builder_onlyExpirationMarginSet() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -151,8 +145,7 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test - public void builder_noAccessToken() { + @Test void builder_noAccessToken() { OAuth2CredentialsWithRefresh.newBuilder() .setRefreshHandler( new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @@ -164,8 +157,7 @@ public AccessToken refreshAccessToken() { .build(); } - @Test - public void builder_noRefreshHandler_throws() { + @Test void builder_noRefreshHandler_throws() { try { OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(); fail("Should fail as a refresh handler must be provided."); @@ -174,8 +166,7 @@ public void builder_noRefreshHandler_throws() { } } - @Test - public void builder_noExpirationTimeInAccessToken_throws() { + @Test void builder_noExpirationTimeInAccessToken_throws() { try { OAuth2CredentialsWithRefresh.newBuilder() .setAccessToken(new AccessToken("accessToken", null)) @@ -186,8 +177,7 @@ public void builder_noExpirationTimeInAccessToken_throws() { } } - @Test - public void refreshAccessToken_delegateToRefreshHandler() throws IOException { + @Test void refreshAccessToken_delegateToRefreshHandler() throws IOException { final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = OAuth2CredentialsWithRefresh.newBuilder() @@ -206,8 +196,7 @@ public AccessToken refreshAccessToken() { assertEquals(refreshedToken, accessToken); } - @Test - public void getRequestMetadata() throws IOException { + @Test void getRequestMetadata() throws IOException { URI uri = URI.create("http://googleapis.com/testapi/v1/foo"); final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = @@ -226,4 +215,4 @@ public AccessToken refreshAccessToken() { TestUtils.assertContainsBearerToken(metadata, refreshedToken.getTokenValue()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java index 20f831917..d82999c68 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java @@ -31,17 +31,16 @@ package com.google.auth.oauth2; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static com.google.auth.oauth2.OAuth2Utils.generateBasicAuthHeader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link OAuth2Utils}. */ -public class OAuth2UtilsTest { +class OAuth2UtilsTest { - @Test - public void testValidCredentials() { + @Test void testValidCredentials() { String username = "testUser"; String password = "testPassword"; String expectedHeader = "Basic dGVzdFVzZXI6dGVzdFBhc3N3b3Jk"; @@ -51,8 +50,7 @@ public void testValidCredentials() { assertEquals(expectedHeader, actualHeader); } - @Test - public void testEmptyUsername_throws() { + @Test void testEmptyUsername_throws() { String username = ""; String password = "testPassword"; @@ -63,8 +61,7 @@ public void testEmptyUsername_throws() { }); } - @Test - public void testEmptyPassword_throws() { + @Test void testEmptyPassword_throws() { String username = "testUser"; String password = ""; @@ -75,8 +72,7 @@ public void testEmptyPassword_throws() { }); } - @Test - public void testNullUsername_throws() { + @Test void testNullUsername_throws() { String username = null; String password = "testPassword"; @@ -87,8 +83,7 @@ public void testNullUsername_throws() { }); } - @Test - public void testNullPassword_throws() { + @Test void testNullPassword_throws() { String username = "testUser"; String password = null; @@ -98,4 +93,4 @@ public void testNullPassword_throws() { generateBasicAuthHeader(username, password); }); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java index 84e522a73..3ccef3bd8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java @@ -31,25 +31,21 @@ 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 com.google.auth.TestUtils; import java.io.IOException; -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 { + +final 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() { + @Test void getMessage_fullFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", "errorUri"); assertEquals("errorCode", e.getErrorCode()); @@ -61,8 +57,7 @@ public void getMessage_fullFormat() { assertEquals(expectedMessage, e.getMessage()); } - @Test - public void getMessage_descriptionFormat() { + @Test void getMessage_descriptionFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", /* errorUri= */ null); assertEquals("errorCode", e.getErrorCode()); @@ -74,8 +69,7 @@ public void getMessage_descriptionFormat() { assertEquals(expectedMessage, e.getMessage()); } - @Test - public void getMessage_baseFormat() { + @Test void getMessage_baseFormat() { OAuthException e = new OAuthException("errorCode", /* errorDescription= */ null, /* errorUri= */ null); @@ -87,8 +81,7 @@ public void getMessage_baseFormat() { assertEquals(expectedMessage, e.getMessage()); } - @Test - public void createFromHttpResponseException() throws IOException { + @Test void createFromHttpResponseException() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException("errorCode", "errorDescription", "errorUri")); @@ -102,8 +95,7 @@ public void createFromHttpResponseException() throws IOException { assertEquals(expectedMessage, e.getMessage()); } - @Test - public void createFromHttpResponseException_descriptionFormat() throws IOException { + @Test void createFromHttpResponseException_descriptionFormat() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException( @@ -118,8 +110,7 @@ public void createFromHttpResponseException_descriptionFormat() throws IOExcepti assertEquals(expectedMessage, e.getMessage()); } - @Test - public void createFromHttpResponseException_baseFormat() throws IOException { + @Test void createFromHttpResponseException_baseFormat() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException( @@ -132,4 +123,4 @@ public void createFromHttpResponseException_baseFormat() throws IOException { String expectedMessage = String.format(BASE_MESSAGE_FORMAT, "errorCode"); assertEquals(expectedMessage, e.getMessage()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java index cd321daf3..6433053c6 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java @@ -31,9 +31,12 @@ package com.google.auth.oauth2; +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 static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; -import static org.junit.Assert.*; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -50,10 +53,10 @@ import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link PluggableAuthCredentials}. */ -public class PluggableAuthCredentialsTest extends BaseSerializationTest { +class PluggableAuthCredentialsTest extends BaseSerializationTest { // The default timeout for waiting for the executable to finish (30 seconds). private static final int DEFAULT_EXECUTABLE_TIMEOUT_MS = 30 * 1000; // The minimum timeout for waiting for the executable to finish (5 seconds). @@ -84,8 +87,7 @@ public HttpTransport create() { } } - @Test - public void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { + @Test void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { PluggableAuthCredentials credential = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -94,8 +96,7 @@ public void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { assertEquals(subjectToken, "pluggableAuthToken"); } - @Test - public void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { + @Test void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { String command = "/path/to/executable"; String timeout = "5000"; String outputFile = "/path/to/output/file"; @@ -136,8 +137,7 @@ public void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOExcept assertEquals(envMap.get("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE"), outputFile); } - @Test - public void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { + @Test void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { String command = "/path/to/executable"; final ExecutableOptions[] providedOptions = {null}; @@ -174,8 +174,7 @@ public void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOEx assertNull(envMap.get("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE")); } - @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -203,8 +202,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc ExternalAccountCredentialsTest.validateMetricsHeader(headers, "executable", false, false); } - @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + @Test void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -244,8 +242,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept ExternalAccountCredentialsTest.validateMetricsHeader(headers, "executable", true, false); } - @Test - public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + @Test void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -290,8 +287,7 @@ public void refreshAccessToken_withServiceAccountImpersonationOptions() throws I ExternalAccountCredentialsTest.validateMetricsHeader(headers, "executable", true, true); } - @Test - public void pluggableAuthCredentialSource_allFields() { + @Test void pluggableAuthCredentialSource_allFields() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -306,8 +302,7 @@ public void pluggableAuthCredentialSource_allFields() { assertEquals(credentialSource.getOutputFilePath(), "/path/to/output/file"); } - @Test - public void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { + @Test void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -319,8 +314,7 @@ public void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { assertNull(credentialSource.getOutputFilePath()); } - @Test - public void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { + @Test void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -345,8 +339,7 @@ public void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { } } - @Test - public void pluggableAuthCredentialSource_validTimeoutProvided() { + @Test void pluggableAuthCredentialSource_validTimeoutProvided() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -365,8 +358,7 @@ public void pluggableAuthCredentialSource_validTimeoutProvided() { } } - @Test - public void pluggableAuthCredentialSource_missingExecutableField_throws() { + @Test void pluggableAuthCredentialSource_missingExecutableField_throws() { try { new PluggableAuthCredentialSource(new HashMap<>()); fail("Should not be able to continue without exception."); @@ -376,8 +368,7 @@ public void pluggableAuthCredentialSource_missingExecutableField_throws() { } } - @Test - public void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { + @Test void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -392,8 +383,7 @@ public void pluggableAuthCredentialSource_missingExecutableCommandField_throws() } } - @Test - public void builder_allFields() throws IOException { + @Test void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -432,8 +422,7 @@ public void builder_allFields() throws IOException { assertEquals("universeDomain", credentials.getUniverseDomain()); } - @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + @Test void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -471,8 +460,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void newBuilder_allFields() throws IOException { + @Test void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -513,8 +501,7 @@ public void newBuilder_allFields() throws IOException { assertEquals(credentials.getUniverseDomain(), newBuilderCreds.getUniverseDomain()); } - @Test - public void newBuilder_noUniverseDomain_defaults() throws IOException { + @Test void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -554,8 +541,7 @@ public void newBuilder_noUniverseDomain_defaults() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, newBuilderCreds.getUniverseDomain()); } - @Test - public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + @Test void createdScoped_clonedCredentialWithAddedScopes() throws IOException { PluggableAuthCredentials credentials = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -587,8 +573,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { assertEquals("universeDomain", newCredentials.getUniverseDomain()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { PluggableAuthCredentials testCredentials = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -639,4 +624,4 @@ static InputStream writeCredentialsStream(String tokenUrl) throws IOException { json.put("credential_source", credentialSource); return TestUtils.jsonToInputStream(json); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java index bf4d0eea7..d5537840b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java @@ -31,36 +31,38 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; /** Tests for {@link PluggableAuthException}. */ -public class PluggableAuthExceptionTest { +class PluggableAuthExceptionTest { private static final String MESSAGE_FORMAT = "Error code %s: %s"; - @Test - public void constructor() { + @Test void constructor() { PluggableAuthException e = new PluggableAuthException("errorCode", "errorDescription"); assertEquals("errorCode", e.getErrorCode()); assertEquals("errorDescription", e.getErrorDescription()); } - @Test(expected = NullPointerException.class) - public void constructor_nullErrorCode_throws() { - new PluggableAuthException(/* errorCode= */ null, "errorDescription"); + @Test + void constructor_nullErrorCode_throws() { + assertThrows( + NullPointerException.class, + () -> new PluggableAuthException(/* errorCode= */ null, "errorDescription")); } - @Test(expected = NullPointerException.class) - public void constructor_nullErrorDescription_throws() { - new PluggableAuthException("errorCode", /* errorDescription= */ null); + @Test + void constructor_nullErrorDescription_throws() { + assertThrows( + NullPointerException.class, + () -> new PluggableAuthException("errorCode", /* errorDescription= */ null)); } - @Test - public void getMessage() { + @Test void getMessage() { PluggableAuthException e = new PluggableAuthException("errorCode", "errorDescription"); String expectedMessage = String.format("Error code %s: %s", "errorCode", "errorDescription"); assertEquals(expectedMessage, e.getMessage()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java index 88d5312a5..2babb0569 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java @@ -31,10 +31,10 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; @@ -42,6 +42,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.mockito.Mockito; import com.google.api.client.json.GenericJson; import com.google.auth.oauth2.ExecutableHandler.ExecutableOptions; import com.google.auth.oauth2.PluggableAuthHandler.InternalProcessBuilder; @@ -57,14 +58,14 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; -/** Tests for {@link PluggableAuthHandler}. */ -@RunWith(MockitoJUnitRunner.class) -public class PluggableAuthHandlerTest { +/** Unit tests for {@link PluggableAuthHandler}. */ +@ExtendWith(MockitoExtension.class) +class PluggableAuthHandlerTest { private static final String TOKEN_TYPE_OIDC = "urn:ietf:params:oauth:token-type:id_token"; private static final String TOKEN_TYPE_SAML = "urn:ietf:params:oauth:token-type:saml2"; private static final String ID_TOKEN = "header.payload.signature"; @@ -99,8 +100,7 @@ public String getOutputFilePath() { } }; - @Test - public void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { + @Test void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -143,8 +143,7 @@ public void retrieveTokenFromExecutable_oidcResponse() throws IOException, Inter assertEquals(expectedMap, currentEnv); } - @Test - public void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { + @Test void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -188,8 +187,7 @@ public void retrieveTokenFromExecutable_samlResponse() throws IOException, Inter assertEquals(expectedMap, currentEnv); } - @Test - public void retrieveTokenFromExecutable_errorResponse_throws() + @Test void retrieveTokenFromExecutable_errorResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -221,8 +219,7 @@ public void retrieveTokenFromExecutable_errorResponse_throws() } } - @Test - public void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() + @Test void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -279,8 +276,7 @@ public void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFiel } } - @Test - public void + @Test void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFieldWithOutputFileSpecified_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -354,8 +350,7 @@ public String getOutputFilePath() { } } - @Test - public void + @Test void retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -430,8 +425,7 @@ public String getOutputFilePath() { } } - @Test - public void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() + @Test void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -486,8 +480,7 @@ public String getOutputFilePath() { assertEquals(ID_TOKEN, token); } - @Test - public void retrieveTokenFromExecutable_withInvalidOutputFile_throws() + @Test void retrieveTokenFromExecutable_withInvalidOutputFile_throws() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -540,8 +533,7 @@ public String getOutputFilePath() { } } - @Test - public void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() + @Test void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -607,8 +599,7 @@ public String getOutputFilePath() { assertEquals(ID_TOKEN, token); } - @Test - public void retrieveTokenFromExecutable_expiredResponse_throws() + @Test void retrieveTokenFromExecutable_expiredResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -640,8 +631,7 @@ public void retrieveTokenFromExecutable_expiredResponse_throws() } } - @Test - public void retrieveTokenFromExecutable_invalidVersion_throws() + @Test void retrieveTokenFromExecutable_invalidVersion_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -679,8 +669,7 @@ public void retrieveTokenFromExecutable_invalidVersion_throws() } } - @Test - public void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws IOException { + @Test void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws IOException { // In order to use Pluggable Auth, GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES must be set to 1. // If set to 0, a runtime exception should be thrown. TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -700,8 +689,7 @@ public void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws } } - @Test - public void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { + @Test void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -752,8 +740,7 @@ public void getExecutableResponse_oidcResponse() throws IOException, Interrupted assertEquals(expectedMap, currentEnv); } - @Test - public void getExecutableResponse_samlResponse() throws IOException, InterruptedException { + @Test void getExecutableResponse_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -806,8 +793,7 @@ public void getExecutableResponse_samlResponse() throws IOException, Interrupted verify(mockProcess, times(1)).destroy(); } - @Test - public void getExecutableResponse_errorResponse() throws IOException, InterruptedException { + @Test void getExecutableResponse_errorResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -854,8 +840,7 @@ public void getExecutableResponse_errorResponse() throws IOException, Interrupte assertEquals(expectedMap, currentEnv); } - @Test - public void getExecutableResponse_timeoutExceeded_throws() + @Test void getExecutableResponse_timeoutExceeded_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -885,8 +870,7 @@ public void getExecutableResponse_timeoutExceeded_throws() verify(mockProcess, times(1)).destroy(); } - @Test - public void getExecutableResponse_nonZeroExitCode_throws() + @Test void getExecutableResponse_nonZeroExitCode_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -919,8 +903,7 @@ public void getExecutableResponse_nonZeroExitCode_throws() verify(mockProcess, times(1)).destroy(); } - @Test - public void getExecutableResponse_processInterrupted_throws() + @Test void getExecutableResponse_processInterrupted_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -952,8 +935,7 @@ public void getExecutableResponse_processInterrupted_throws() verify(mockProcess, times(1)).destroy(); } - @Test - public void getExecutableResponse_invalidResponse_throws() + @Test void getExecutableResponse_invalidResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -1043,4 +1025,4 @@ Process start() { } }; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java index 30345d17a..e76a72557 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java @@ -30,21 +30,17 @@ */ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** Test cases for {@linkSecureSessionAgentConfig}. */ -@RunWith(JUnit4.class) -public class SecureSessionAgentConfigTest { + +class SecureSessionAgentConfigTest { private static final String S2A_PLAINTEXT_ADDRESS = "plaintext"; private static final String S2A_MTLS_ADDRESS = "mtls"; - @Test - public void createS2AConfig_success() { + @Test void createS2AConfig_success() { SecureSessionAgentConfig config = SecureSessionAgentConfig.createBuilder() .setPlaintextAddress(S2A_PLAINTEXT_ADDRESS) @@ -54,10 +50,9 @@ public void createS2AConfig_success() { assertEquals(S2A_MTLS_ADDRESS, config.getMtlsAddress()); } - @Test - public void createEmptyS2AConfig_success() { + @Test void createEmptyS2AConfig_success() { SecureSessionAgentConfig config = SecureSessionAgentConfig.createBuilder().build(); assertTrue(config.getPlaintextAddress().isEmpty()); assertTrue(config.getMtlsAddress().isEmpty()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java index eb6f92a23..1fb2111b8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java @@ -30,26 +30,22 @@ */ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.HttpStatusCodes; import com.google.auth.oauth2.ComputeEngineCredentialsTest.MockMetadataServerTransportFactory; import com.google.common.collect.ImmutableMap; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test cases for {@link SecureSessionAgent}. */ -@RunWith(JUnit4.class) -public class SecureSessionAgentTest { + +class SecureSessionAgentTest { private static final String INVALID_JSON_KEY = "invalid_key"; private static final String S2A_PLAINTEXT_ADDRESS = "plaintext"; private static final String S2A_MTLS_ADDRESS = "mtls"; - @Test - public void getS2AAddress_validAddress() { + @Test void getS2AAddress_validAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -68,8 +64,7 @@ public void getS2AAddress_validAddress() { assertEquals(S2A_MTLS_ADDRESS, mtlsS2AAddress); } - @Test - public void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { + @Test void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -88,8 +83,7 @@ public void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { assertTrue(mtlsS2AAddress.isEmpty()); } - @Test - public void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { + @Test void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -109,8 +103,7 @@ public void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { assertTrue(mtlsS2AAddress.isEmpty()); } - @Test - public void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintextEmptyAddress() { + @Test void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintextEmptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -129,8 +122,7 @@ public void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintext assertEquals(S2A_MTLS_ADDRESS, mtlsS2AAddress); } - @Test - public void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddress() { + @Test void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -148,4 +140,4 @@ public void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddre assertEquals(S2A_PLAINTEXT_ADDRESS, plaintextS2AAddress); assertTrue(mtlsS2AAddress.isEmpty()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 1561bb341..1905721d7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -31,17 +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.assertThrows; -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.http.HttpResponseException; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.json.GenericJson; @@ -80,13 +79,11 @@ 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 { static final String CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -160,8 +157,7 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti return createDefaultBuilderWithKey(privateKey); } - @Test - public void setLifetime() throws IOException { + @Test void setLifetime() throws IOException { ServiceAccountCredentials.Builder builder = createDefaultBuilder(); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.getLifetime()); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); @@ -174,8 +170,7 @@ public void setLifetime() throws IOException { assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); } - @Test - public void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { + @Test void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { try { createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(); fail( @@ -187,15 +182,13 @@ public void setLifetime_invalid_lifetime() throws IOException, IllegalStateExcep } } - @Test - public void createWithCustomLifetime() throws IOException { + @Test void createWithCustomLifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); credentials = credentials.createWithCustomLifetime(4000); assertEquals(4000, credentials.getLifetime()); } - @Test - public void createdScoped_clones() throws IOException { + @Test void createdScoped_clones() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilderWithKey(privateKey) @@ -220,8 +213,7 @@ public void createdScoped_clones() throws IOException { SCOPES.toArray(), ((ServiceAccountCredentials) credentials).getScopes().toArray()); } - @Test - public void createdDelegated_clones() throws IOException { + @Test void createdDelegated_clones() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilderWithKey(privateKey) @@ -245,8 +237,7 @@ public void createdDelegated_clones() throws IOException { assertEquals(USER, ((ServiceAccountCredentials) credentials).getServiceAccountUser()); } - @Test - public void createAssertion_correct() throws IOException { + @Test void createAssertion_correct() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = createDefaultBuilderWithScopes(scopes); ServiceAccountCredentials credentials = builder.setServiceAccountUser(USER).build(); @@ -265,8 +256,7 @@ public void createAssertion_correct() throws IOException { assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); } - @Test - public void createAssertion_defaultScopes_correct() throws IOException { + @Test void createAssertion_defaultScopes_correct() throws IOException { List defaultScopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = createDefaultBuilder(); builder.setScopes(null, defaultScopes).setServiceAccountUser(USER); @@ -288,8 +278,7 @@ public void createAssertion_defaultScopes_correct() throws IOException { assertEquals(Joiner.on(' ').join(defaultScopes), payload.get("scope")); } - @Test - public void createAssertion_custom_lifetime() throws IOException { + @Test void createAssertion_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -301,8 +290,7 @@ public void createAssertion_custom_lifetime() throws IOException { assertEquals(currentTimeMillis / 1000 + 4000, (long) payload.getExpirationTimeSeconds()); } - @Test - public void createAssertionForIdToken_correct() throws IOException { + @Test void createAssertionForIdToken_correct() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilder() @@ -325,8 +313,7 @@ public void createAssertionForIdToken_correct() throws IOException { assertEquals(USER, payload.getSubject()); } - @Test - public void createAssertionForIdToken_custom_lifetime() throws IOException { + @Test void createAssertionForIdToken_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -339,8 +326,7 @@ public void createAssertionForIdToken_custom_lifetime() throws IOException { assertEquals(currentTimeMillis / 1000 + 4000, (long) payload.getExpirationTimeSeconds()); } - @Test - public void createAssertionForIdToken_incorrect() throws IOException { + @Test void createAssertionForIdToken_incorrect() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -367,8 +353,7 @@ public void createAssertionForIdToken_incorrect() throws IOException { assertEquals(USER, payload.getSubject()); } - @Test - public void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() + @Test void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() throws IOException { GoogleCredentials credentials = createDefaultBuilderWithToken(ACCESS_TOKEN).build(); @@ -378,8 +363,8 @@ public void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() 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")); + e.getMessage().contains("Scopes and uri are not configured for service account"), + "expected to fail with exception"); } GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); @@ -389,8 +374,7 @@ public void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void createdScoped_withUniverse_selfSignedJwt() throws IOException { + @Test void createdScoped_withUniverse_selfSignedJwt() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setUniverseDomain("foo.bar").build(); @@ -399,8 +383,8 @@ public void createdScoped_withUniverse_selfSignedJwt() throws IOException { 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")); + e.getMessage().contains("Scopes and uri are not configured for service account"), + "expected to fail with exception"); } GoogleCredentials scopedCredentials = credentials.createScoped("dummy.scope"); @@ -429,8 +413,7 @@ public void createdScoped_withUniverse_selfSignedJwt() throws IOException { verifyJwtAccess(metadata, "dummy.default.scope2"); } - @Test - public void noScopes_withUniverse_selfSignedJwt() throws IOException { + @Test void noScopes_withUniverse_selfSignedJwt() throws IOException { GoogleCredentials credentials = createDefaultBuilder().setUniverseDomain("foo.bar").build(); try { @@ -438,8 +421,8 @@ public void noScopes_withUniverse_selfSignedJwt() throws IOException { 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")); + e.getMessage().contains("Scopes and uri are not configured for service account"), + "expected to fail with exception"); } Map> metadata = credentials.getRequestMetadata(CALL_URI); @@ -447,8 +430,7 @@ public void noScopes_withUniverse_selfSignedJwt() throws IOException { verifyJwtAccess(metadata, null); } - @Test - public void createdScoped_defaultScopes() throws IOException { + @Test void createdScoped_defaultScopes() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -485,8 +467,7 @@ public void createdScoped_defaultScopes() throws IOException { assertEquals("dummy.default.scope", credentials.getDefaultScopes().toArray()[0]); } - @Test - public void createScopedRequired_emptyScopes() throws IOException { + @Test void createScopedRequired_emptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, EMPTY_SCOPES); @@ -494,8 +475,7 @@ public void createScopedRequired_emptyScopes() throws IOException { assertTrue(credentials.createScopedRequired()); } - @Test - public void createScopedRequired_nonEmptyScopes() throws IOException { + @Test void createScopedRequired_nonEmptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, SCOPES); @@ -503,8 +483,7 @@ public void createScopedRequired_nonEmptyScopes() throws IOException { assertFalse(credentials.createScopedRequired()); } - @Test - public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { + @Test void createScopedRequired_nonEmptyDefaultScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null, SCOPES); @@ -512,8 +491,7 @@ public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { assertFalse(credentials.createScopedRequired()); } - @Test - public void fromJSON_getProjectId() throws IOException { + @Test void fromJSON_getProjectId() throws IOException { GenericJson json = writeServiceAccountJson(PROJECT_ID, null, null); ServiceAccountCredentials credentials = @@ -522,8 +500,7 @@ public void fromJSON_getProjectId() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromJSON_Universe_getUniverseDomain() throws IOException { + @Test void fromJSON_Universe_getUniverseDomain() throws IOException { GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "foo.bar"); ServiceAccountCredentials credentials = @@ -531,8 +508,7 @@ public void fromJSON_Universe_getUniverseDomain() throws IOException { assertEquals("foo.bar", credentials.getUniverseDomain()); } - @Test - public void fromJSON_getProjectIdNull() throws IOException { + @Test void fromJSON_getProjectIdNull() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(null, null, null); @@ -542,8 +518,7 @@ public void fromJSON_getProjectIdNull() throws IOException { assertNull(credentials.getProjectId()); } - @Test - public void fromJSON_hasAccessToken() throws IOException { + @Test void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, null, null); @@ -555,8 +530,7 @@ public void fromJSON_hasAccessToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void fromJSON_withUniverse_selfSignedJwt() throws IOException { + @Test void fromJSON_withUniverse_selfSignedJwt() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "foo.bar"); @@ -568,8 +542,7 @@ public void fromJSON_withUniverse_selfSignedJwt() throws IOException { verifyJwtAccess(metadata, "dummy.scope"); } - @Test - public void fromJSON_tokenServerUri() throws IOException { + @Test void fromJSON_tokenServerUri() throws IOException { final String tokenServerUri = "https://foo.com/bar"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -580,8 +553,7 @@ public void fromJSON_tokenServerUri() throws IOException { assertEquals(URI.create(tokenServerUri), credentials.getTokenServerUri()); } - @Test - public void fromJson_hasQuotaProjectId() throws IOException { + @Test void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, QUOTA_PROJECT, null); @@ -596,16 +568,14 @@ public void fromJson_hasQuotaProjectId() throws IOException { Collections.singletonList(QUOTA_PROJECT)); } - @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + @Test void getRequestMetadata_hasAccessToken() throws IOException { GoogleCredentials credentials = createDefaultBuilderWithToken(ACCESS_TOKEN).setScopes(SCOPES).build(); Map> metadata = credentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + @Test 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); @@ -626,14 +596,12 @@ public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOExcep com.google.auth.oauth2.TestUtils.validateMetricsHeader(accessTokenRequestHeader, "at", "sa"); } - @Test - public void getUniverseDomain_defaultUniverse() throws IOException { + @Test void getUniverseDomain_defaultUniverse() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void refreshAccessToken_refreshesToken() throws IOException { + @Test void refreshAccessToken_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -648,8 +616,7 @@ public void refreshAccessToken_refreshesToken() throws IOException { TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test - public void refreshAccessToken_tokenExpiry() throws IOException { + @Test void refreshAccessToken_tokenExpiry() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -668,8 +635,7 @@ public void refreshAccessToken_tokenExpiry() throws IOException { assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); } - @Test - public void refreshAccessToken_IOException_Retry() throws IOException { + @Test void refreshAccessToken_IOException_Retry() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -687,8 +653,7 @@ public void refreshAccessToken_IOException_Retry() throws IOException { TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test - public void refreshAccessToken_retriesServerErrors() throws IOException { + @Test void refreshAccessToken_retriesServerErrors() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -707,8 +672,7 @@ public void refreshAccessToken_retriesServerErrors() throws IOException { TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test - public void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { + @Test void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -727,8 +691,7 @@ public void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test - public void refreshAccessToken_defaultRetriesDisabled() throws IOException { + @Test void refreshAccessToken_defaultRetriesDisabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -758,8 +721,7 @@ public void refreshAccessToken_defaultRetriesDisabled() throws IOException { } } - @Test - public void refreshAccessToken_maxRetries_maxDelay() throws IOException { + @Test void refreshAccessToken_maxRetries_maxDelay() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = @@ -791,8 +753,7 @@ public void refreshAccessToken_maxRetries_maxDelay() throws IOException { } } - @Test - public void refreshAccessToken_RequestFailure_retried() throws IOException { + @Test void refreshAccessToken_RequestFailure_retried() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = @@ -825,8 +786,7 @@ public void refreshAccessToken_RequestFailure_retried() throws IOException { } } - @Test - public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + @Test void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -855,8 +815,7 @@ public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { } } - @Test - public void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOException { + @Test void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -892,8 +851,7 @@ public void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws com.google.auth.oauth2.TestUtils.validateMetricsHeader(idTokenRequestHeader, "it", "sa"); } - @Test - public void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() + @Test void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -918,8 +876,7 @@ public void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test - public void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { + @Test void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { String nonGDU = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(nonGDU); @@ -949,8 +906,7 @@ public void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws I tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test - public void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { + @Test void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { String nonGDU = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(nonGDU); @@ -978,8 +934,7 @@ public void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() thr tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test - public void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOException { + @Test void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.setError(new IOException("404 Not Found")); ServiceAccountCredentials credentials = @@ -996,8 +951,7 @@ public void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOExcept assertThrows(IOException.class, tokenCredential::refresh); } - @Test - public void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOException { + @Test void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOException { String universeDomain = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(universeDomain); @@ -1025,8 +979,7 @@ public void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOExceptio assertThrows(IOException.class, tokenCredential::refresh); } - @Test - public void getScopes_nullReturnsEmpty() throws IOException { + @Test void getScopes_nullReturnsEmpty() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); Collection scopes = credentials.getScopes(); @@ -1034,14 +987,12 @@ public void getScopes_nullReturnsEmpty() throws IOException { assertTrue(scopes.isEmpty()); } - @Test - public void getAccount_sameAs() throws IOException { + @Test void getAccount_sameAs() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); assertEquals(CLIENT_EMAIL, credentials.getAccount()); } - @Test - public void sign_sameAs() + @Test void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] toSign = {0xD, 0xE, 0xA, 0xD}; ServiceAccountCredentials credentials = createDefaultBuilder().build(); @@ -1054,8 +1005,7 @@ public void sign_sameAs() assertArrayEquals(signature.sign(), signedBytes); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1080,8 +1030,7 @@ public void equals_true() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_clientId() throws IOException { + @Test void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1106,8 +1055,7 @@ public void equals_false_clientId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_email() throws IOException { + @Test void equals_false_email() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1132,8 +1080,7 @@ public void equals_false_email() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_super() throws IOException { + @Test void equals_false_super() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1161,8 +1108,7 @@ public void equals_false_super() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_keyId() throws IOException { + @Test void equals_false_keyId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1187,8 +1133,7 @@ public void equals_false_keyId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_scopes() throws IOException { + @Test void equals_false_scopes() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1213,8 +1158,7 @@ public void equals_false_scopes() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_transportFactory() throws IOException { + @Test void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1240,8 +1184,7 @@ public void equals_false_transportFactory() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_tokenServer() throws IOException { + @Test 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(); @@ -1267,8 +1210,7 @@ public void equals_false_tokenServer() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1302,8 +1244,7 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1335,8 +1276,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void hashCode_not_equals_quota() throws IOException { + @Test void hashCode_not_equals_quota() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1361,8 +1301,7 @@ public void hashCode_not_equals_quota() throws IOException { assertNotEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -1390,8 +1329,7 @@ public void serialize() throws IOException, ClassNotFoundException { deserializedCredentials.toBuilder().getHttpTransportFactory().getClass()); } - @Test - public void fromStream_nullTransport_throws() throws IOException { + @Test void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { ServiceAccountCredentials.fromStream(stream, null); @@ -1401,8 +1339,7 @@ public void fromStream_nullTransport_throws() throws IOException { } } - @Test - public void fromStream_nullStream_throws() throws IOException { + @Test void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); @@ -1412,8 +1349,7 @@ public void fromStream_nullStream_throws() throws IOException { } } - @Test - public void fromStream_providesToken() throws IOException { + @Test void fromStream_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -1428,24 +1364,21 @@ public void fromStream_providesToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void fromStream_noClientId_throws() throws IOException { + @Test void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(null, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); testFromStreamException(serviceAccountStream, "client_id"); } - @Test - public void fromStream_noClientEmail_throws() throws IOException { + @Test void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, null, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); testFromStreamException(serviceAccountStream, "client_email"); } - @Test - public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { + @Test void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.setError(new IOException("Invalid grant: Account not found")); @@ -1469,24 +1402,21 @@ public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOExcep } } - @Test - public void fromStream_noPrivateKey_throws() throws IOException { + @Test void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, null, PRIVATE_KEY_ID); testFromStreamException(serviceAccountStream, "private_key"); } - @Test - public void fromStream_noPrivateKeyId_throws() throws IOException { + @Test void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, null); testFromStreamException(serviceAccountStream, "private_key_id"); } - @Test - public void getUriForSelfSignedJWT() { + @Test void getUriForSelfSignedJWT() { assertNull(ServiceAccountCredentials.getUriForSelfSignedJWT(null)); URI uri = URI.create("https://compute.googleapis.com/compute/v1/projects/"); @@ -1494,22 +1424,19 @@ public void getUriForSelfSignedJWT() { assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } - @Test - public void getUriForSelfSignedJWT_noHost() { + @Test 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() { + @Test 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 getRequestMetadata_setsQuotaProjectId() throws IOException { + @Test void getRequestMetadata_setsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1535,8 +1462,7 @@ public void getRequestMetadata_setsQuotaProjectId() throws IOException { assertEquals("my-quota-project-id", headerValues.get(0)); } - @Test - public void getRequestMetadata_noQuotaProjectId() throws IOException { + @Test void getRequestMetadata_noQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1558,8 +1484,7 @@ public void getRequestMetadata_noQuotaProjectId() throws IOException { assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test - public void getRequestMetadata_withCallback() throws IOException { + @Test void getRequestMetadata_withCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1595,11 +1520,10 @@ 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_withScopes_withUniverseDomain_SelfSignedJwt() throws IOException { + @Test void getRequestMetadata_withScopes_withUniverseDomain_SelfSignedJwt() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1635,11 +1559,10 @@ 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_withScopes_selfSignedJWT() throws IOException { + @Test void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1664,8 +1587,7 @@ public void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { credentials.getMetricsCredentialType()); } - @Test - public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { + @Test void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1700,8 +1622,7 @@ public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() thr TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test - public void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { + @Test void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1718,8 +1639,7 @@ public void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { verifyJwtAccess(metadata, null); } - @Test - public void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOException { + @Test void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1737,8 +1657,7 @@ public void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOExcept verifyJwtAccess(metadata, "dummy.scope"); } - @Test - public void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { + @Test void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1774,11 +1693,10 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test - public void createScopes_existingAccessTokenInvalidated() throws IOException { + @Test void createScopes_existingAccessTokenInvalidated() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1806,15 +1724,15 @@ private void verifyJwtAccess(Map> metadata, String expected 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()); @@ -1904,4 +1822,4 @@ private static void testFromStreamException(InputStream stream, String expectedM assertTrue(expected.getMessage().contains(expectedMessageContent)); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index 2f6533195..65bee2a3c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -31,16 +31,16 @@ package com.google.auth.oauth2; +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; -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 com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -65,13 +65,11 @@ 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"; @@ -97,8 +95,7 @@ public class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTes private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final String QUOTA_PROJECT = "sample-quota-project-id"; - @Test - public void constructor_allParameters_constructs() throws IOException { + @Test void constructor_allParameters_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -117,8 +114,7 @@ public void constructor_allParameters_constructs() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void constructor_noClientId_constructs() throws IOException { + @Test void constructor_noClientId_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) @@ -127,8 +123,7 @@ public void constructor_noClientId_constructs() throws IOException { .build(); } - @Test - public void constructor_noPrivateKeyId_constructs() throws IOException { + @Test void constructor_noPrivateKeyId_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -137,8 +132,7 @@ public void constructor_noPrivateKeyId_constructs() throws IOException { .build(); } - @Test - public void constructor_noEmail_throws() throws IOException { + @Test void constructor_noEmail_throws() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); try { ServiceAccountJwtAccessCredentials.newBuilder() @@ -152,8 +146,7 @@ public void constructor_noEmail_throws() throws IOException { } } - @Test - public void constructor_noPrivateKey_throws() { + @Test void constructor_noPrivateKey_throws() { try { ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -166,32 +159,28 @@ public void constructor_noPrivateKey_throws() { } } - @Test - public void getAuthenticationType_returnsJwtAccess() throws IOException { + @Test void getAuthenticationType_returnsJwtAccess() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); assertEquals(credentials.getAuthenticationType(), "JWTAccess"); } - @Test - public void hasRequestMetadata_returnsTrue() throws IOException { + @Test void hasRequestMetadata_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); assertTrue(credentials.hasRequestMetadata()); } - @Test - public void hasRequestMetadataOnly_returnsTrue() throws IOException { + @Test void hasRequestMetadataOnly_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); assertTrue(credentials.hasRequestMetadataOnly()); } - @Test - public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { + @Test void getRequestMetadata_blocking_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -206,8 +195,7 @@ public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test - public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { + @Test void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -223,8 +211,7 @@ public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOExcep verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test - public void getRequestMetadata_blocking_noURI_throws() throws IOException { + @Test void getRequestMetadata_blocking_noURI_throws() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -242,8 +229,7 @@ public void getRequestMetadata_blocking_noURI_throws() throws IOException { } } - @Test - public void getRequestMetadata_blocking_cached() throws IOException { + @Test void getRequestMetadata_blocking_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -267,8 +253,7 @@ public void getRequestMetadata_blocking_cached() throws IOException { assertEquals(metadata1, metadata2); } - @Test - public void getRequestMetadata_blocking_cache_expired() throws IOException { + @Test void getRequestMetadata_blocking_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -292,8 +277,7 @@ public void getRequestMetadata_blocking_cache_expired() throws IOException { assertNotEquals(metadata1, metadata2); } - @Test - public void getRequestMetadata_async_hasJwtAccess() throws IOException { + @Test void getRequestMetadata_async_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -311,8 +295,7 @@ public void getRequestMetadata_async_hasJwtAccess() throws IOException { verifyJwtAccess(callback.metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test - public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { + @Test void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -331,8 +314,7 @@ public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOExceptio verifyJwtAccess(callback.metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test - public void getRequestMetadata_async_noURI_exception() throws IOException { + @Test void getRequestMetadata_async_noURI_exception() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -349,8 +331,7 @@ public void getRequestMetadata_async_noURI_exception() throws IOException { assertNotNull(callback.exception); } - @Test - public void getRequestMetadata_async_cache_expired() throws IOException { + @Test void getRequestMetadata_async_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -377,8 +358,7 @@ public void getRequestMetadata_async_cache_expired() throws IOException { assertNotEquals(callback1.metadata, callback2.metadata); } - @Test - public void getRequestMetadata_async_cached() throws IOException { + @Test void getRequestMetadata_async_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -405,8 +385,7 @@ public void getRequestMetadata_async_cached() throws IOException { assertEquals(callback1.metadata, callback2.metadata); } - @Test - public void getRequestMetadata_contains_quotaProjectId() throws IOException { + @Test void getRequestMetadata_contains_quotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -425,8 +404,7 @@ public void getRequestMetadata_contains_quotaProjectId() throws IOException { Collections.singletonList(QUOTA_PROJECT)); } - @Test - public void getAccount_sameAs() throws IOException { + @Test void getAccount_sameAs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -438,8 +416,7 @@ public void getAccount_sameAs() throws IOException { assertEquals(SA_CLIENT_EMAIL, credentials.getAccount()); } - @Test - public void sign_sameAs() + @Test void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); byte[] toSign = {0xD, 0xE, 0xA, 0xD}; @@ -457,8 +434,7 @@ public void sign_sameAs() assertArrayEquals(signature.sign(), signedBytes); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -480,8 +456,7 @@ public void equals_true() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_clientId() throws IOException { + @Test void equals_false_clientId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -503,8 +478,7 @@ public void equals_false_clientId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_email() throws IOException { + @Test void equals_false_email() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -526,8 +500,7 @@ public void equals_false_email() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_keyId() throws IOException { + @Test void equals_false_keyId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -549,8 +522,7 @@ public void equals_false_keyId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_callUri() throws IOException { + @Test void equals_false_callUri() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); final URI otherCallUri = URI.create("https://foo.com/bar"); ServiceAccountJwtAccessCredentials credentials = @@ -573,8 +545,7 @@ public void equals_false_callUri() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -593,8 +564,7 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test void hashCode_equals() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -615,8 +585,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test void serialize() throws IOException, ClassNotFoundException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -636,8 +605,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test - public void fromStream_nullStream_throws() throws IOException { + @Test void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); @@ -647,8 +615,7 @@ public void fromStream_nullStream_throws() throws IOException { } } - @Test - public void fromStream_hasJwtAccess() throws IOException { + @Test void fromStream_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -660,8 +627,7 @@ public void fromStream_hasJwtAccess() throws IOException { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test - public void fromStream_defaultURI_hasJwtAccess() throws IOException { + @Test void fromStream_defaultURI_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -674,8 +640,7 @@ public void fromStream_defaultURI_hasJwtAccess() throws IOException { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test - public void fromStream_noClientId_throws() throws IOException { + @Test void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -683,8 +648,7 @@ public void fromStream_noClientId_throws() throws IOException { testFromStreamException(serviceAccountStream, "client_id"); } - @Test - public void fromStream_noClientEmail_throws() throws IOException { + @Test void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -692,8 +656,7 @@ public void fromStream_noClientEmail_throws() throws IOException { testFromStreamException(serviceAccountStream, "client_email"); } - @Test - public void fromStream_noPrivateKey_throws() throws IOException { + @Test void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -701,8 +664,7 @@ public void fromStream_noPrivateKey_throws() throws IOException { testFromStreamException(serviceAccountStream, "private_key"); } - @Test - public void fromStream_noPrivateKeyId_throws() throws IOException { + @Test void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -710,8 +672,7 @@ public void fromStream_noPrivateKeyId_throws() throws IOException { testFromStreamException(serviceAccountStream, "private_key_id"); } - @Test - public void jwtWithClaims_overrideAudience() throws IOException { + @Test void jwtWithClaims_overrideAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -728,8 +689,7 @@ public void jwtWithClaims_overrideAudience() throws IOException { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, URI.create("new-audience"), SA_PRIVATE_KEY_ID); } - @Test - public void jwtWithClaims_noAudience() throws IOException { + @Test void jwtWithClaims_noAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -746,8 +706,7 @@ public void jwtWithClaims_noAudience() throws IOException { } } - @Test - public void jwtWithClaims_defaultAudience() throws IOException { + @Test void jwtWithClaims_defaultAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -763,8 +722,7 @@ public void jwtWithClaims_defaultAudience() throws IOException { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, URI.create("default-audience"), SA_PRIVATE_KEY_ID); } - @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + @Test void getRequestMetadataSetsQuotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -783,8 +741,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { assertEquals("my-quota-project-id", headerValues.get(0)); } - @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + @Test void getRequestMetadataNoQuotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -799,8 +756,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test - public void getRequestMetadataWithCallback() throws IOException { + @Test void getRequestMetadataWithCallback() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -830,11 +786,10 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test - public void fromJSON_noUniverseDomain() throws IOException { + @Test void fromJSON_noUniverseDomain() throws IOException { GenericJson json = writeServiceAccountJson( SA_CLIENT_ID, @@ -854,8 +809,7 @@ public void fromJSON_noUniverseDomain() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromJSON_UniverseDomainSet() throws IOException { + @Test void fromJSON_UniverseDomainSet() throws IOException { GenericJson json = writeServiceAccountJson( SA_CLIENT_ID, @@ -875,8 +829,7 @@ public void fromJSON_UniverseDomainSet() throws IOException { assertEquals("example.com", credentials.getUniverseDomain()); } - @Test - public void fromPkcs8_NoUniverseDomain() throws IOException { + @Test void fromPkcs8_NoUniverseDomain() throws IOException { ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -888,8 +841,7 @@ public void fromPkcs8_NoUniverseDomain() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void fromPkcs8_CustomUniverseDomain() throws IOException { + @Test void fromPkcs8_CustomUniverseDomain() throws IOException { ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, @@ -907,8 +859,7 @@ public void fromPkcs8_CustomUniverseDomain() throws IOException { assertEquals("example.com", credentials.getUniverseDomain()); } - @Test - public void builder_defaultUniverseDomain() throws IOException { + @Test void builder_defaultUniverseDomain() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -921,8 +872,7 @@ public void builder_defaultUniverseDomain() throws IOException { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test - public void builder_customUniverseDomain() throws IOException { + @Test void builder_customUniverseDomain() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -944,15 +894,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()); @@ -1004,4 +954,4 @@ private GenericJson writeServiceAccountJson( json.put("type", GoogleCredentialsInfo.SERVICE_ACCOUNT_CREDENTIALS.getFileType()); return json; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java index 68d1edc96..80353ecc2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java @@ -31,8 +31,8 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -48,27 +48,25 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.KeyValuePair; import org.slf4j.event.Level; // part of Slf4jUtils test that needs logback dependency -public class Slf4jUtilsLogbackTest { +class Slf4jUtilsLogbackTest { private static final Logger LOGGER = LoggerFactory.getLogger(Slf4jUtilsLogbackTest.class); private TestEnvironmentProvider testEnvironmentProvider; - @Before - public void setup() { + @BeforeEach void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } - @Test - public void testLogWithMDC_slf4jLogger() { + @Test void testLogWithMDC_slf4jLogger() { TestAppender testAppender = setupTestLogger(); @@ -90,8 +88,7 @@ public void testLogWithMDC_slf4jLogger() { testAppender.stop(); } - @Test - public void testLogWithMDC_INFO() { + @Test void testLogWithMDC_INFO() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.INFO, new HashMap<>(), "test message"); @@ -100,8 +97,7 @@ public void testLogWithMDC_INFO() { testAppender.stop(); } - @Test - public void testLogWithMDC_TRACE_notEnabled() { + @Test void testLogWithMDC_TRACE_notEnabled() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.TRACE, new HashMap<>(), "test message"); @@ -109,8 +105,7 @@ public void testLogWithMDC_TRACE_notEnabled() { testAppender.stop(); } - @Test - public void testLogWithMDC_WARN() { + @Test void testLogWithMDC_WARN() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.WARN, new HashMap<>(), "test message"); @@ -119,8 +114,7 @@ public void testLogWithMDC_WARN() { testAppender.stop(); } - @Test - public void testLogWithMDC_ERROR() { + @Test void testLogWithMDC_ERROR() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.ERROR, new HashMap<>(), "test message"); @@ -129,8 +123,7 @@ public void testLogWithMDC_ERROR() { testAppender.stop(); } - @Test - public void testLogGenericData() { + @Test void testLogGenericData() { // mimic GOOGLE_SDK_JAVA_LOGGING = true testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); @@ -150,16 +143,13 @@ public void testLogGenericData() { assertEquals(2, keyValuePairs.size()); for (KeyValuePair kvp : keyValuePairs) { - assertTrue( - "Key should be either 'key1' or 'token'", - kvp.key.equals("key1") || kvp.key.equals("token")); + assertTrue(kvp.key.equals("key1", "Key should be either 'key1' or 'token'") || kvp.key.equals("token")); } testAppender.stop(); } - @Test - public void testLogRequest() throws IOException { + @Test void testLogRequest() throws IOException { // mimic GOOGLE_SDK_JAVA_LOGGING = true testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); @@ -213,4 +203,4 @@ private TestAppender setupTestLogger() { ((ch.qos.logback.classic.Logger) LOGGER).addAppender(testAppender); return testAppender; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java index 97a215f56..2468f01a7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java @@ -31,31 +31,33 @@ 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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.auth.oauth2.Slf4jUtils.LoggerFactoryProvider; import java.util.logging.Level; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.helpers.NOPLogger; -public class Slf4jUtilsTest { +class Slf4jUtilsTest { private TestEnvironmentProvider testEnvironmentProvider; - @Before - public void setup() { + @BeforeEach void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } // This test mimics GOOGLE_SDK_JAVA_LOGGING != true - @Test - public void testGetLogger_loggingDisabled_shouldGetNOPLogger() { + @Test void testGetLogger_loggingDisabled_shouldGetNOPLogger() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "false"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); Logger logger = Slf4jUtils.getLogger(Slf4jUtilsTest.class); @@ -66,8 +68,7 @@ public void testGetLogger_loggingDisabled_shouldGetNOPLogger() { } // This test require binding (e.g. logback) be present - @Test - public void testGetLogger_loggingEnabled_slf4jBindingPresent() { + @Test void testGetLogger_loggingEnabled_slf4jBindingPresent() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); Logger logger = Slf4jUtils.getLogger(LoggingUtilsTest.class); @@ -75,8 +76,7 @@ public void testGetLogger_loggingEnabled_slf4jBindingPresent() { assertNotEquals(NOPLogger.class, logger.getClass()); } - @Test - public void testGetLogger_loggingEnabled_noBinding() { + @Test void testGetLogger_loggingEnabled_noBinding() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); // Create a mock LoggerFactoryProvider @@ -93,14 +93,12 @@ public void testGetLogger_loggingEnabled_noBinding() { assertTrue(logger instanceof org.slf4j.helpers.NOPLogger); } - @Test - public void testCheckIfClazzAvailable() { + @Test void testCheckIfClazzAvailable() { assertFalse(Slf4jUtils.checkIfClazzAvailable("fake.class.should.not.be.in.classpath")); assertTrue(Slf4jUtils.checkIfClazzAvailable("org.slf4j.event.KeyValuePair")); } - @Test - public void testMatchLevelSevere() { + @Test void testMatchLevelSevere() { assertEquals( org.slf4j.event.Level.ERROR, Slf4jLoggingHelpers.matchUtilLevelToSLF4JLevel(Level.SEVERE)); assertEquals( @@ -112,4 +110,4 @@ public void testMatchLevelSevere() { assertEquals( org.slf4j.event.Level.TRACE, Slf4jLoggingHelpers.matchUtilLevelToSLF4JLevel(Level.FINER)); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java index e91558fa7..36ededd91 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java @@ -31,10 +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; import com.google.api.client.util.GenericData; @@ -45,15 +44,13 @@ import java.util.Collections; 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; +import org.junit.jupiter.api.function.Executable; /** Tests for {@link StsRequestHandler}. */ -@RunWith(JUnit4.class) -public final class StsRequestHandlerTest { + +final class StsRequestHandlerTest { private static final String TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; @@ -63,13 +60,11 @@ public final class StsRequestHandlerTest { private MockStsTransport transport; - @Before - public void setup() { + @BeforeEach void setup() { transport = new MockStsTransport(); } - @Test - public void exchangeToken() throws IOException { + @Test void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType") .setScopes(Collections.singletonList(OAuth2Utils.CLOUD_PLATFORM_SCOPE)) @@ -102,8 +97,7 @@ public void exchangeToken() throws IOException { assertEquals(expectedRequestContent.getUnknownKeys(), actualRequestContent); } - @Test - public void exchangeToken_withOptionalParams() throws IOException { + @Test void exchangeToken_withOptionalParams() throws IOException { // Return optional params scope and the refresh_token. transport.addScopeSequence(Arrays.asList("scope1", "scope2", "scope3")); transport.addRefreshTokenSequence("refreshToken"); @@ -166,8 +160,7 @@ public void exchangeToken_withOptionalParams() throws IOException { assertEquals(expectedRequestContent.getUnknownKeys(), actualRequestContent); } - @Test - public void exchangeToken_throwsException() throws IOException { + @Test void exchangeToken_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -183,20 +176,14 @@ public void exchangeToken_throwsException() throws IOException { OAuthException e = assertThrows( OAuthException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + () -> requestHandler.exchangeToken()); assertEquals("invalidRequest", e.getErrorCode()); assertNull(e.getErrorDescription()); assertNull(e.getErrorUri()); } - @Test - public void exchangeToken_withOptionalParams_throwsException() throws IOException { + @Test void exchangeToken_withOptionalParams_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -211,20 +198,14 @@ public void exchangeToken_withOptionalParams_throwsException() throws IOExceptio OAuthException e = assertThrows( OAuthException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + () -> requestHandler.exchangeToken()); assertEquals("invalidRequest", e.getErrorCode()); assertEquals("errorDescription", e.getErrorDescription()); assertEquals("errorUri", e.getErrorUri()); } - @Test - public void exchangeToken_ioException() { + @Test void exchangeToken_ioException() { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -239,17 +220,11 @@ public void exchangeToken_ioException() { IOException thrownException = assertThrows( IOException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + () -> requestHandler.exchangeToken()); assertEquals(e, thrownException); } - @Test - public void exchangeToken_noExpiresInReturned() throws IOException { + @Test 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); @@ -275,8 +250,7 @@ public void exchangeToken_noExpiresInReturned() throws IOException { assertNull(response.getExpiresInSeconds()); } - @Test - public void exchangeToken_withAccessBoundarySessionKey() throws IOException { + @Test void exchangeToken_withAccessBoundarySessionKey() throws IOException { transport.setReturnAccessBoundarySessionKey(/* returnAccessBoundarySessionKey= */ true); StsTokenExchangeRequest stsTokenExchangeRequest = @@ -292,4 +266,4 @@ public void exchangeToken_withAccessBoundarySessionKey() throws IOException { // Validate response. assertEquals(transport.getAccessBoundarySessionKey(), response.getAccessBoundarySessionKey()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java b/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java index 66fd046fd..d0101d3ba 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java @@ -37,7 +37,7 @@ import java.util.List; /** Logback appender used to set up tests. */ -public class TestAppender extends AppenderBase { +class TestAppender extends AppenderBase { public List events = new ArrayList<>(); @Override @@ -50,4 +50,4 @@ protected void append(ILoggingEvent eventObject) { public void clearEvents() { events.clear(); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java b/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java index 9e6de1108..a5acb238f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java @@ -16,4 +16,4 @@ public TestEnvironmentProvider setEnv(String name, String value) { environmentVariables.put(name, value); return this; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java b/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java index 99af8c106..6a3aec7ce 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java @@ -31,13 +31,12 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; -public class TestUtils { +class TestUtils { static void validateMetricsHeader( Map> headers, String requestType, String credentialType) { assertTrue(headers.containsKey(MetricsUtils.API_CLIENT_HEADER)); @@ -69,4 +68,4 @@ static void validateMetricsHeader( } assertEquals(expectedMetricsValue, actualMetricsValue); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index 5168cb90e..0a658d959 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java @@ -30,11 +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.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; @@ -51,13 +50,10 @@ import java.io.Reader; import java.util.Arrays; import java.util.List; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class TokenVerifierTest { +class TokenVerifierTest { private static final String ES256_TOKEN = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im1wZjBEQSJ9.eyJhdWQiOiIvcHJvamVjdHMvNjUyNTYyNzc2Nzk4L2FwcHMvY2xvdWQtc2FtcGxlcy10ZXN0cy1waHAtaWFwIiwiZW1haWwiOiJjaGluZ29yQGdvb2dsZS5jb20iLCJleHAiOjE1ODQwNDc2MTcsImdvb2dsZSI6eyJhY2Nlc3NfbGV2ZWxzIjpbImFjY2Vzc1BvbGljaWVzLzUxODU1MTI4MDkyNC9hY2Nlc3NMZXZlbHMvcmVjZW50U2VjdXJlQ29ubmVjdERhdGEiLCJhY2Nlc3NQb2xpY2llcy81MTg1NTEyODA5MjQvYWNjZXNzTGV2ZWxzL3Rlc3ROb09wIiwiYWNjZXNzUG9saWNpZXMvNTE4NTUxMjgwOTI0L2FjY2Vzc0xldmVscy9ldmFwb3JhdGlvblFhRGF0YUZ1bGx5VHJ1c3RlZCJdfSwiaGQiOiJnb29nbGUuY29tIiwiaWF0IjoxNTg0MDQ3MDE3LCJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwic3ViIjoiYWNjb3VudHMuZ29vZ2xlLmNvbToxMTIxODE3MTI3NzEyMDE5NzI4OTEifQ.yKNtdFY5EKkRboYNexBdfugzLhC3VuGyFcuFYA8kgpxMqfyxa41zkML68hYKrWu2kOBTUW95UnbGpsIi_u1fiA"; @@ -83,8 +79,7 @@ public long currentTimeMillis() { } }; - @Test - public void verifyExpiredToken() { + @Test void verifyExpiredToken() { for (String token : ALL_TOKENS) { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build(); try { @@ -96,8 +91,7 @@ public void verifyExpiredToken() { } } - @Test - public void verifyExpectedAudience() { + @Test void verifyExpectedAudience() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setAudience("expected audience").build(); for (String token : ALL_TOKENS) { @@ -110,8 +104,7 @@ public void verifyExpectedAudience() { } } - @Test - public void verifyExpectedIssuer() { + @Test void verifyExpectedIssuer() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build(); for (String token : ALL_TOKENS) { try { @@ -123,8 +116,7 @@ public void verifyExpectedIssuer() { } } - @Test - public void verifyEs256Token404CertificateUrl() { + @Test void verifyEs256Token404CertificateUrl() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -163,8 +155,7 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test - public void verifyEs256TokenPublicKeyMismatch() { + @Test void verifyEs256TokenPublicKeyMismatch() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -200,8 +191,7 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test - public void verifyPublicKeyStoreIntermittentError() throws VerificationException, IOException { + @Test void verifyPublicKeyStoreIntermittentError() throws VerificationException, IOException { // mock responses MockLowLevelHttpResponse response404 = new MockLowLevelHttpResponse() @@ -250,8 +240,7 @@ public void verifyPublicKeyStoreIntermittentError() throws VerificationException assertNotNull(tokenVerifier.verify(ES256_TOKEN)); } - @Test - public void verifyEs256Token() throws VerificationException, IOException { + @Test void verifyEs256Token() throws VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.gstatic.com/iap/verify/public_key-jwk", @@ -264,8 +253,7 @@ public void verifyEs256Token() throws VerificationException, IOException { assertNotNull(tokenVerifier.verify(ES256_TOKEN)); } - @Test - public void verifyRs256Token() throws VerificationException, IOException { + @Test void verifyRs256Token() throws VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.googleapis.com/oauth2/v3/certs", @@ -278,8 +266,7 @@ public void verifyRs256Token() throws VerificationException, IOException { assertNotNull(tokenVerifier.verify(FEDERATED_SIGNON_RS256_TOKEN)); } - @Test - public void verifyRs256TokenWithLegacyCertificateUrlFormat() + @Test void verifyRs256TokenWithLegacyCertificateUrlFormat() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( @@ -294,8 +281,7 @@ public void verifyRs256TokenWithLegacyCertificateUrlFormat() } @Test - @Ignore - public void verifyServiceAccountRs256Token() throws VerificationException { + @Disabled void verifyServiceAccountRs256Token() throws VerificationException { final Clock clock = new Clock() { @Override @@ -344,4 +330,4 @@ public LowLevelHttpResponse execute() throws IOException { } }; } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java index 4f2a8173e..577bcab20 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java @@ -31,16 +31,16 @@ package com.google.auth.oauth2; +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 static com.google.auth.TestUtils.WORKFORCE_IDENTITY_FEDERATION_AUTH_URI; import static com.google.auth.TestUtils.WORKFORCE_IDENTITY_FEDERATION_TOKEN_SERVER_URI; -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 com.google.auth.TestUtils; import com.google.auth.http.HttpTransportFactory; @@ -55,13 +55,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** 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"; @@ -84,8 +82,7 @@ public class UserAuthorizerTest { private static final URI BASE_URI = URI.create("http://example.com/foo"); private static final PKCEProvider pkce = new DefaultPKCEProvider(); - @Test - public void constructorMinimum() { + @Test void constructorMinimum() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -104,8 +101,7 @@ public void constructorMinimum() { authorizer.getClientAuthenticationType()); } - @Test - public void constructorCommon() { + @Test void constructorCommon() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -127,8 +123,7 @@ public void constructorCommon() { authorizer.getClientAuthenticationType()); } - @Test - public void constructorWithClientAuthenticationTypeNone() { + @Test void constructorWithClientAuthenticationTypeNone() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -148,18 +143,20 @@ public void constructorWithClientAuthenticationTypeNone() { UserAuthorizer.ClientAuthenticationType.NONE, authorizer.getClientAuthenticationType()); } - @Test(expected = NullPointerException.class) - public void constructorCommon_nullClientId_throws() { - UserAuthorizer.newBuilder().setScopes(DUMMY_SCOPES).setCallbackUri(CALLBACK_URI).build(); + @Test + void constructorCommon_nullClientId_throws() { + assertThrows( + NullPointerException.class, + () -> UserAuthorizer.newBuilder().setScopes(DUMMY_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() { + @Test void getCallbackUri_relativeToBase() { final URI callbackURI = URI.create("/bar"); final URI expectedCallbackURI = URI.create("http://example.com/bar"); UserAuthorizer authorizer = @@ -174,8 +171,7 @@ public void getCallbackUri_relativeToBase() { assertEquals(expectedCallbackURI, absoluteCallbackURI); } - @Test - public void getAuthorizationUrl() throws IOException { + @Test void getAuthorizationUrl() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -210,8 +206,7 @@ public void getAuthorizationUrl() throws IOException { assertEquals("consent", parameters.get("prompt")); } - @Test - public void getAuthorizationUrl_additionalParameters() throws IOException { + @Test void getAuthorizationUrl_additionalParameters() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -254,8 +249,7 @@ public void getAuthorizationUrl_additionalParameters() throws IOException { assertFalse(parameters.containsKey("param2")); } - @Test - public void getCredentials_noCredentials_returnsNull() throws IOException { + @Test void getCredentials_noCredentials_returnsNull() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -268,8 +262,7 @@ public void getCredentials_noCredentials_returnsNull() throws IOException { assertNull(credentials); } - @Test - public void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() throws IOException { + @Test void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode( @@ -296,8 +289,7 @@ public void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() thro assertEquals(GRANTED_SCOPES, response.getAccessToken().getScopes()); } - @Test - public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationClientAuthBasic() + @Test void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationClientAuthBasic() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -338,8 +330,7 @@ public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederation assertEquals(1, authHeader.size()); } - @Test - public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationNoClientAuth() + @Test void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationNoClientAuth() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -373,8 +364,7 @@ public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederation assertNull(headers.get("authorization")); } - @Test - public void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { + @Test void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { UserAuthorizer authorizer = UserAuthorizer.newBuilder().setClientId(CLIENT_ID).setScopes(DUMMY_SCOPES).build(); @@ -386,8 +376,7 @@ public void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { }); } - @Test - public void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() + @Test void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -419,8 +408,7 @@ public void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() .contains("Error reading result of Token API:Expected value access_token not found.")); } - @Test - public void getCredentials_storedCredentials_returnsStored() throws IOException { + @Test void getCredentials_storedCredentials_returnsStored() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserCredentials initialCredentials = @@ -447,8 +435,8 @@ public void getCredentials_storedCredentials_returnsStored() throws IOException assertEquals(GRANTED_SCOPES, credentials.getAccessToken().getScopes()); } - @Test(expected = NullPointerException.class) - public void getCredentials_nullUserId_throws() throws IOException { + @Test + void getCredentials_nullUserId_throws() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserAuthorizer authorizer = UserAuthorizer.newBuilder() @@ -457,11 +445,10 @@ 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 { + @Test void getCredentials_refreshedToken_stored() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; AccessToken accessToken1 = @@ -515,8 +502,7 @@ public void getCredentials_refreshedToken_stored() throws IOException { assertEquals(GRANTED_SCOPES, credentials2.getAccessToken().getScopes()); } - @Test - public void getCredentials_refreshedToken_different_granted_scopes() throws IOException { + @Test void getCredentials_refreshedToken_different_granted_scopes() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; final List grantedRefreshScopes = Arrays.asList("scope3"); @@ -570,8 +556,7 @@ public void getCredentials_refreshedToken_different_granted_scopes() throws IOEx assertEquals(grantedRefreshScopes, credentials2.getAccessToken().getScopes()); } - @Test - public void getCredentialsFromCode_convertsCodeToTokens() throws IOException { + @Test void getCredentialsFromCode_convertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode( @@ -592,8 +577,7 @@ public void getCredentialsFromCode_convertsCodeToTokens() throws IOException { assertEquals(GRANTED_SCOPES, credentials.getAccessToken().getScopes()); } - @Test - public void getCredentialsFromCode_additionalParameters() throws IOException { + @Test void getCredentialsFromCode_additionalParameters() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -638,8 +622,8 @@ public void getCredentialsFromCode_additionalParameters() throws IOException { assertEquals(GRANTED_SCOPES, credentials.getAccessToken().getScopes()); } - @Test(expected = NullPointerException.class) - public void getCredentialsFromCode_nullCode_throws() throws IOException { + @Test + void getCredentialsFromCode_nullCode_throws() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -647,11 +631,10 @@ 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 { + @Test void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -689,8 +672,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() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -698,11 +681,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) @@ -710,11 +695,12 @@ 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 { + @Test void revokeAuthorization_revokesAndClears() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -757,8 +743,8 @@ public void revokeAuthorization_revokesAndClears() throws IOException { assertNull(credentials2); } - @Test(expected = IllegalArgumentException.class) - public void nullCodeVerifierPKCEProvider() { + @Test + void nullCodeVerifierPKCEProvider() { PKCEProvider pkce = new PKCEProvider() { @Override @@ -777,17 +763,19 @@ public String getCodeChallenge() { } }; - UserAuthorizer authorizer = - UserAuthorizer.newBuilder() - .setClientId(CLIENT_ID) - .setScopes(DUMMY_SCOPES) - .setTokenStore(new MemoryTokensStorage()) - .setPKCEProvider(pkce) - .build(); + assertThrows( + IllegalArgumentException.class, + () -> + UserAuthorizer.newBuilder() + .setClientId(CLIENT_ID) + .setScopes(DUMMY_SCOPES) + .setTokenStore(new MemoryTokensStorage()) + .setPKCEProvider(pkce) + .build()); } - @Test(expected = IllegalArgumentException.class) - public void nullCodeChallengePKCEProvider() { + @Test + void nullCodeChallengePKCEProvider() { PKCEProvider pkce = new PKCEProvider() { @Override @@ -806,17 +794,19 @@ public String getCodeChallenge() { } }; - UserAuthorizer authorizer = - UserAuthorizer.newBuilder() - .setClientId(CLIENT_ID) - .setScopes(DUMMY_SCOPES) - .setTokenStore(new MemoryTokensStorage()) - .setPKCEProvider(pkce) - .build(); + assertThrows( + IllegalArgumentException.class, + () -> + UserAuthorizer.newBuilder() + .setClientId(CLIENT_ID) + .setScopes(DUMMY_SCOPES) + .setTokenStore(new MemoryTokensStorage()) + .setPKCEProvider(pkce) + .build()); } - @Test(expected = IllegalArgumentException.class) - public void nullCodeChallengeMethodPKCEProvider() { + @Test + void nullCodeChallengeMethodPKCEProvider() { PKCEProvider pkce = new PKCEProvider() { @Override @@ -835,16 +825,18 @@ public String getCodeChallenge() { } }; - UserAuthorizer.newBuilder() - .setClientId(CLIENT_ID) - .setScopes(DUMMY_SCOPES) - .setTokenStore(new MemoryTokensStorage()) - .setPKCEProvider(pkce) - .build(); + assertThrows( + IllegalArgumentException.class, + () -> + UserAuthorizer.newBuilder() + .setClientId(CLIENT_ID) + .setScopes(DUMMY_SCOPES) + .setTokenStore(new MemoryTokensStorage()) + .setPKCEProvider(pkce) + .build()); } - @Test - public void testTokenResponseWithConfig() { + @Test void testTokenResponseWithConfig() { String clientId = "testClientId"; String clientSecret = "testClientSecret"; String refreshToken = "testRefreshToken"; @@ -870,8 +862,7 @@ public void testTokenResponseWithConfig() { assertEquals(httpTransportFactory, tokenResponse.getHttpTransportFactory()); } - @Test - public void testTokenResponseWithConfig_noRefreshToken() { + @Test void testTokenResponseWithConfig_noRefreshToken() { String clientId = "testClientId"; String clientSecret = "testClientSecret"; AccessToken accessToken = new AccessToken("token", new Date()); @@ -894,4 +885,4 @@ public void testTokenResponseWithConfig_noRefreshToken() { assertEquals(httpTransportFactory, tokenResponse.getHttpTransportFactory()); assertNull(tokenResponse.getRefreshToken()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index f6ead0294..c9dcebfc1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -31,16 +31,15 @@ package com.google.auth.oauth2; -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.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.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.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Clock; @@ -64,13 +63,11 @@ 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 { static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -86,13 +83,14 @@ 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() { + @Test void constructor() { UserCredentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -106,8 +104,7 @@ public void constructor() { assertEquals(QUOTA_PROJECT, credentials.getQuotaProjectId()); } - @Test - public void createScoped_same() { + @Test void createScoped_same() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -117,8 +114,7 @@ public void createScoped_same() { assertSame(userCredentials, userCredentials.createScoped(SCOPES)); } - @Test - public void createScopedRequired_false() { + @Test void createScopedRequired_false() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -128,8 +124,7 @@ public void createScopedRequired_false() { assertFalse(userCredentials.createScopedRequired()); } - @Test - public void fromJson_hasAccessToken() throws IOException { + @Test void fromJson_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -141,8 +136,7 @@ public void fromJson_hasAccessToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void fromJson_hasTokenUri() throws IOException { + @Test void fromJson_hasTokenUri() throws IOException { String tokenUrl = "token.url.xyz"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -153,8 +147,7 @@ public void fromJson_hasTokenUri() throws IOException { assertEquals(URI.create(tokenUrl), credentials.toBuilder().getTokenServerUri()); } - @Test - public void fromJson_emptyTokenUri() throws IOException { + @Test void fromJson_emptyTokenUri() throws IOException { String tokenUrl = ""; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -165,8 +158,7 @@ public void fromJson_emptyTokenUri() throws IOException { assertEquals(OAuth2Utils.TOKEN_SERVER_URI, credentials.toBuilder().getTokenServerUri()); } - @Test - public void fromJson_hasQuotaProjectId() throws IOException { + @Test void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -181,8 +173,7 @@ public void fromJson_hasQuotaProjectId() throws IOException { Collections.singletonList(QUOTA_PROJECT)); } - @Test - public void getRequestMetadata_initialToken_hasAccessToken() throws IOException { + @Test void getRequestMetadata_initialToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -199,8 +190,7 @@ public void getRequestMetadata_initialToken_hasAccessToken() throws IOException TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { + @Test void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -220,8 +210,7 @@ public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException } } - @Test - public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { + @Test void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -238,8 +227,7 @@ public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOExcept TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + @Test 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); @@ -259,8 +247,7 @@ public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOExcep TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void equals_true() throws IOException { + @Test void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -288,8 +275,7 @@ public void equals_true() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test - public void equals_false_clientId() throws IOException { + @Test void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -315,8 +301,7 @@ public void equals_false_clientId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_clientSecret() throws IOException { + @Test void equals_false_clientSecret() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -342,8 +327,7 @@ public void equals_false_clientSecret() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_refreshToken() throws IOException { + @Test void equals_false_refreshToken() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -369,8 +353,7 @@ public void equals_false_refreshToken() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_accessToken() throws IOException { + @Test void equals_false_accessToken() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); AccessToken otherAccessToken = new AccessToken("otherAccessToken", null); @@ -398,8 +381,7 @@ public void equals_false_accessToken() throws IOException { assertNotEquals(credentials.hashCode(), otherAccessToken.hashCode()); } - @Test - public void equals_false_transportFactory() throws IOException { + @Test void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -426,8 +408,7 @@ public void equals_false_transportFactory() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_tokenServer() throws IOException { + @Test void equals_false_tokenServer() throws IOException { 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); @@ -454,8 +435,7 @@ public void equals_false_tokenServer() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void equals_false_quotaProjectId() throws IOException { + @Test void equals_false_quotaProjectId() throws IOException { final String quotaProject1 = "sample-id-1"; final String quotaProject2 = "sample-id-2"; AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -482,8 +462,7 @@ public void equals_false_quotaProjectId() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test - public void toString_containsFields() throws IOException { + @Test void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -514,8 +493,7 @@ public void toString_containsFields() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test - public void hashCode_equals() throws IOException { + @Test 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); @@ -542,8 +520,7 @@ public void hashCode_equals() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test - public void serialize() throws IOException, ClassNotFoundException { + @Test 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); @@ -563,8 +540,7 @@ public void serialize() throws IOException, ClassNotFoundException { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test - public void fromStream_nullTransport_throws() throws IOException { + @Test void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { UserCredentials.fromStream(stream, null); @@ -574,8 +550,7 @@ public void fromStream_nullTransport_throws() throws IOException { } } - @Test - public void fromStream_nullStream_throws() throws IOException { + @Test void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { UserCredentials.fromStream(null, transportFactory); @@ -585,8 +560,7 @@ public void fromStream_nullStream_throws() throws IOException { } } - @Test - public void fromStream_user_providesToken() throws IOException { + @Test void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -600,29 +574,25 @@ public void fromStream_user_providesToken() throws IOException { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test - public void fromStream_userNoClientId_throws() throws IOException { + @Test 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 { + @Test 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 { + @Test 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 { + @Test void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -636,8 +606,7 @@ public void saveUserCredentials_saved_throws() throws IOException { userCredentials.save(filePath); } - @Test - public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { + @Test void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -661,8 +630,7 @@ public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOExcep assertEquals(userCredentials.getRefreshToken(), restoredCredentials.getRefreshToken()); } - @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + @Test void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -683,8 +651,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { assertEquals("my-quota-project-id", headerValues.get(0)); } - @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + @Test void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -701,8 +668,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test - public void getRequestMetadataWithCallback() throws IOException { + @Test void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -733,11 +699,10 @@ 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 { + @Test void IdTokenCredentials_WithUserEmailScope_success() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -774,8 +739,7 @@ public void IdTokenCredentials_WithUserEmailScope_success() throws IOException { com.google.auth.oauth2.TestUtils.validateMetricsHeader(idTokenRequestHeader, "untracked", "u"); } - @Test - public void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { + @Test void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -815,8 +779,7 @@ public void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOExcepti } } - @Test - public void idTokenWithAudience_non2xxError() throws IOException { + @Test void idTokenWithAudience_non2xxError() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.setError(new IOException("404 Not Found")); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -830,8 +793,7 @@ public void idTokenWithAudience_non2xxError() throws IOException { assertThrows(GoogleAuthException.class, tokenCredential::refresh); } - @Test - public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + @Test void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -858,8 +820,7 @@ public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { } } - @Test - public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + @Test void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -885,8 +846,7 @@ public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { } } - @Test - public void userCredentials_toBuilder_copyEveryAttribute() { + @Test void userCredentials_toBuilder_copyEveryAttribute() { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); UserCredentials credentials = UserCredentials.newBuilder() @@ -948,4 +908,4 @@ private static void testFromStreamException(InputStream stream, String expectedM assertTrue(expected.getMessage().contains(expectedMessageContent)); } } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java index 3d88cff7a..a26066a08 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java @@ -31,11 +31,10 @@ package com.google.auth.oauth2.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - +import static org.junit.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 com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.auth.oauth2.AccessToken; @@ -45,14 +44,13 @@ import com.google.auth.oauth2.IdTokenCredentials; import com.google.auth.oauth2.IdTokenProvider; import com.google.auth.oauth2.OAuth2Utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public final class FTComputeEngineCredentialsTest { +final class FTComputeEngineCredentialsTest { private final String computeUrl = "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; - @Test - public void RefreshCredentials() throws Exception { + @Test void RefreshCredentials() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); AccessToken accessToken = credentials.refreshAccessToken(); @@ -61,8 +59,7 @@ public void RefreshCredentials() throws Exception { assertTrue(accessToken.getExpirationTime().getTime() > System.currentTimeMillis()); } - @Test - public void DefaultCredentials() throws Exception { + @Test void DefaultCredentials() throws Exception { final GoogleCredentials defaultCredential = GoogleCredentials.getApplicationDefault().createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE); @@ -71,8 +68,7 @@ public void DefaultCredentials() throws Exception { assertTrue(accessToken.getExpirationTime().getTime() > System.currentTimeMillis()); } - @Test - public void IdTokenFromMetadata() throws Exception { + @Test void IdTokenFromMetadata() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); IdToken idToken = credentials.idTokenWithAudience(computeUrl, null); assertNotNull(idToken); @@ -83,8 +79,7 @@ public void IdTokenFromMetadata() throws Exception { assertEquals("https://accounts.google.com", jws.getPayload().get("iss")); } - @Test - public void FetchIdToken() throws Exception { + @Test void FetchIdToken() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); IdTokenCredentials idTokenCredential = IdTokenCredentials.newBuilder() @@ -102,4 +97,4 @@ public void FetchIdToken() throws Exception { assertEquals(computeUrl, jws.getPayload().get("aud")); assertEquals("https://accounts.google.com", jws.getPayload().get("iss")); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java index 8449919e4..22ce72760 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java @@ -31,24 +31,21 @@ package com.google.auth.oauth2.functional; -import static org.junit.Assert.assertEquals; - +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public final class FTQuotaProjectId { - @Test - public void validate_quota_from_environment_used() throws IOException { + @Test void validate_quota_from_environment_used() throws IOException { GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); assertEquals("gcloud-devel", credentials.getQuotaProjectId()); } - @Test - public void validate_quota_from_environment_not_used() throws IOException { + @Test void validate_quota_from_environment_not_used() throws IOException { // Check the environment value for quota project assertEquals("gcloud-devel", System.getenv("GOOGLE_CLOUD_QUOTA_PROJECT")); @@ -63,4 +60,4 @@ public void validate_quota_from_environment_not_used() throws IOException { // Validate that the quota project from the json is used instead of environment value assertEquals("quota_from_file", credentials.getQuotaProjectId()); } -} +} \ No newline at end of file diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java index 82a38e3df..b567d2040 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java @@ -31,12 +31,11 @@ package com.google.auth.oauth2.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; @@ -52,9 +51,9 @@ import com.google.auth.oauth2.OAuth2Utils; import java.io.FileNotFoundException; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public final class FTServiceAccountCredentialsTest { +final class FTServiceAccountCredentialsTest { private final String cloudTasksUrl = "https://cloudtasks.googleapis.com/v2/projects/gcloud-devel/locations"; private final String storageUrl = @@ -64,28 +63,24 @@ public final class FTServiceAccountCredentialsTest { private final String computeUrl = "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; - @Test - public void NoScopeNoAudienceComputeTest() throws Exception { + @Test void NoScopeNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(computeUrl); assertEquals(200, response.getStatusCode()); } - @Test - public void NoScopeNoAudienceBigQueryTest() throws Exception { + @Test void NoScopeNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(bigQueryUrl); assertEquals(200, response.getStatusCode()); } - @Test - public void NoScopeNoAudienceOnePlatformTest() throws Exception { + @Test void NoScopeNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(cloudTasksUrl); assertEquals(200, response.getStatusCode()); } // TODO: add Storage case - @Test - public void AudienceSetNoScopeTest() throws Exception { + @Test void AudienceSetNoScopeTest() throws Exception { final GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); IdTokenCredentials tokenCredential = @@ -105,52 +100,44 @@ public void AudienceSetNoScopeTest() throws Exception { assertEquals("https://accounts.google.com", jws.getPayload().get("iss")); } - @Test - public void ScopeSetNoAudienceStorageTest() throws Exception { + @Test void ScopeSetNoAudienceStorageTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(storageUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test - public void ScopeSetNoAudienceComputeTest() throws Exception { + @Test void ScopeSetNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(computeUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test - public void ScopeSetNoAudienceBigQueryTest() throws Exception { + @Test void ScopeSetNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(bigQueryUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test - public void ScopeSetNoAudienceOnePlatformTest() throws Exception { + @Test void ScopeSetNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(cloudTasksUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test - public void WrongScopeComputeTest() throws Exception { + @Test void WrongScopeComputeTest() throws Exception { executeRequestWrongScope(computeUrl); } - @Test - public void WrongScopeStorageTest() throws Exception { + @Test void WrongScopeStorageTest() throws Exception { executeRequestWrongScope(storageUrl); } - @Test - public void WrongScopeBigQueryTest() throws Exception { + @Test void WrongScopeBigQueryTest() throws Exception { executeRequestWrongScope(bigQueryUrl); } - @Test - public void WrongScopeOnePlatformTest() throws Exception { + @Test void WrongScopeOnePlatformTest() throws Exception { executeRequestWrongScope(cloudTasksUrl); } @@ -188,4 +175,4 @@ private HttpResponse executeRequestWithCredentialsWithScope(String serviceUrl, S HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl); return request.execute(); } -} +} \ No newline at end of file diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index a09ff65ce..de9c62a42 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -41,13 +41,6 @@ sponge_log - - - org.apache.maven.surefire - surefire-junit47 - ${surefire.version} - - @@ -330,8 +323,8 @@ api-common - junit - junit + org.junit.jupiter + junit-jupiter test @@ -343,7 +336,11 @@ org.mockito mockito-core - 4.11.0 + test + + + org.mockito + mockito-junit-jupiter test diff --git a/pom.xml b/pom.xml index 22297dda7..77d5d94a1 100644 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ UTF-8 2.0.2 - 4.13.2 + 5.11.4 33.5.0-android 2.0.33 3.0.2 @@ -106,6 +106,18 @@ google-auth-library-cloudshell ${project.version} + + org.mockito + mockito-core + 4.11.0 + test + + + org.mockito + mockito-junit-jupiter + 4.11.0 + test + com.google.http-client google-http-client-bom @@ -139,8 +151,15 @@ ${project.findbugs.version} - junit - junit + org.junit + junit-bom + ${project.junit.version} + pom + import + + + org.junit.jupiter + junit-jupiter ${project.junit.version} test diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 5b7217972..14944baff 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -77,6 +77,12 @@ software.amazon.awssdk regions + + org.junit.jupiter + junit-jupiter + 5.11.4 + test + diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index ff4a66ae6..494364df0 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -27,30 +27,26 @@ import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class SnippetsIT { +class SnippetsIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String CREDENTIALS = System.getenv("GOOGLE_APPLICATION_CREDENTIALS"); private ByteArrayOutputStream stdOut; // Check if the required environment variables are set. - public static void requireEnvVar(String envVarName) { + static void requireEnvVar(String envVarName) { assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) .that(System.getenv(envVarName)) .isNotEmpty(); } - @BeforeClass - public static void setup() throws IOException { + @BeforeAll static void setup() throws IOException { final PrintStream out = System.out; ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); @@ -61,17 +57,14 @@ public static void setup() throws IOException { System.setOut(out); } - @AfterClass - public static void cleanup() {} + @AfterAll static void cleanup() {} - @Before - public void beforeEach() { + @BeforeEach void beforeEach() { stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); } - @After - public void afterEach() { + @AfterEach void afterEach() { stdOut = null; System.setOut(null); } @@ -93,35 +86,30 @@ private static String getIdTokenFromServiceAccount( return idToken.getTokenValue(); } - @Test - public void testIdTokenFromServiceAccount() throws IOException { + @Test void testIdTokenFromServiceAccount() throws IOException { IdTokenFromServiceAccount.getIdTokenFromServiceAccount(CREDENTIALS, "https://example.com"); assertThat(stdOut.toString()).contains("Generated ID token."); } - @Test - public void testVerifyGoogleIdToken() throws IOException { + @Test void testVerifyGoogleIdToken() throws IOException { String idToken = getIdTokenFromServiceAccount(CREDENTIALS, "https://example.com"); VerifyGoogleIdToken.verifyGoogleIdToken( idToken, "https://example.com", "https://www.googleapis.com/oauth2/v3/certs"); } - @Test - public void testIdTokenFromMetadataServer() throws GeneralSecurityException, IOException { + @Test void testIdTokenFromMetadataServer() throws GeneralSecurityException, IOException { IdTokenFromMetadataServer.getIdTokenFromMetadataServer("https://www.google.com"); assertThat(stdOut.toString()).contains("Generated ID token."); } - @Test - public void testAuthenticateImplicitWithAdc() throws IOException { + @Test void testAuthenticateImplicitWithAdc() throws IOException { AuthenticateImplicitWithAdc.authenticateImplicitWithAdc(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } - @Test - public void testAuthenticateExplicit() throws IOException { + @Test void testAuthenticateExplicit() throws IOException { AuthenticateExplicit.authenticateExplicit(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } -} +} \ No newline at end of file From e7510a85c9fba2f7f874194241cb16f21d4b4190 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Thu, 1 Jan 2026 19:51:46 -0500 Subject: [PATCH 02/19] fix: move @Test annotations to separate lines --- ...deCredentialAccessBoundaryFactoryTest.java | 87 ++++--- ...lientSideCredentialAccessBoundaryTest.java | 3 +- .../auth/http/HttpCredentialsAdapterTest.java | 12 +- .../auth/mtls/SecureConnectProviderTest.java | 15 +- .../WorkloadCertificateConfigurationTest.java | 15 +- .../google/auth/mtls/X509ProviderTest.java | 15 +- .../auth/oauth2/AppEngineCredentialsTest.java | 36 ++- .../auth/oauth2/AwsCredentialsTest.java | 108 +++++--- .../auth/oauth2/AwsRequestSignerTest.java | 42 ++-- ...eIdentityPoolSubjectTokenSupplierTest.java | 48 ++-- .../com/google/auth/oauth2/ClientIdTest.java | 24 +- .../oauth2/CloudShellCredentialsTest.java | 21 +- .../oauth2/ComputeEngineCredentialsTest.java | 159 ++++++++---- .../oauth2/CredentialAccessBoundaryTest.java | 51 ++-- .../DefaultCredentialsProviderTest.java | 114 ++++++--- .../auth/oauth2/DefaultPKCEProviderTest.java | 6 +- .../oauth2/DownscopedCredentialsTest.java | 30 ++- .../auth/oauth2/ExecutableResponseTest.java | 39 ++- ...lAccountAuthorizedUserCredentialsTest.java | 162 ++++++++---- .../ExternalAccountCredentialsTest.java | 150 +++++++---- .../ExternalAccountSupplierContextTest.java | 6 +- .../auth/oauth2/GdchCredentialsTest.java | 96 ++++--- .../auth/oauth2/GoogleAuthUtilsTest.java | 3 +- .../auth/oauth2/GoogleCredentialsTest.java | 153 +++++++---- .../google/auth/oauth2/ITDownscopingTest.java | 3 +- .../ITWorkloadIdentityFederationTest.java | 18 +- .../com/google/auth/oauth2/IamUtilsTest.java | 15 +- .../auth/oauth2/IdTokenCredentialsTest.java | 9 +- .../com/google/auth/oauth2/IdTokenTest.java | 21 +- .../IdentityPoolCredentialsSourceTest.java | 18 +- .../oauth2/IdentityPoolCredentialsTest.java | 117 ++++++--- .../oauth2/ImpersonatedCredentialsTest.java | 93 ++++--- ...nalAwsSecurityCredentialsSupplierTest.java | 18 +- .../com/google/auth/oauth2/JwtClaimsTest.java | 21 +- .../auth/oauth2/JwtCredentialsTest.java | 30 ++- .../com/google/auth/oauth2/LoggingTest.java | 18 +- .../google/auth/oauth2/LoggingUtilsTest.java | 6 +- .../google/auth/oauth2/MetricsUtilsTest.java | 6 +- .../auth/oauth2/OAuth2CredentialsTest.java | 66 +++-- .../OAuth2CredentialsWithRefreshTest.java | 27 +- .../google/auth/oauth2/OAuth2UtilsTest.java | 15 +- .../auth/oauth2/OAuthExceptionTest.java | 18 +- .../oauth2/PluggableAuthCredentialsTest.java | 54 ++-- .../oauth2/PluggableAuthExceptionTest.java | 6 +- .../auth/oauth2/PluggableAuthHandlerTest.java | 57 +++-- .../oauth2/SecureSessionAgentConfigTest.java | 6 +- .../auth/oauth2/SecureSessionAgentTest.java | 15 +- .../oauth2/ServiceAccountCredentialsTest.java | 237 ++++++++++++------ ...erviceAccountJwtAccessCredentialsTest.java | 144 +++++++---- .../auth/oauth2/Slf4jUtilsLogbackTest.java | 21 +- .../google/auth/oauth2/Slf4jUtilsTest.java | 15 +- .../auth/oauth2/StsRequestHandlerTest.java | 21 +- .../google/auth/oauth2/TokenVerifierTest.java | 27 +- .../auth/oauth2/UserAuthorizerTest.java | 63 +++-- .../auth/oauth2/UserCredentialsTest.java | 117 ++++++--- .../FTComputeEngineCredentialsTest.java | 12 +- .../oauth2/functional/FTQuotaProjectId.java | 6 +- .../FTServiceAccountCredentialsTest.java | 36 ++- .../snippets/src/test/java/SnippetsIT.java | 15 +- 59 files changed, 1844 insertions(+), 922 deletions(-) diff --git a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java index d44252324..6a77f67b7 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java @@ -114,7 +114,8 @@ public HttpTransport create() { "service-account@google.com", "accessToken"); } - @Test void fetchIntermediateCredentials() throws Exception { + @Test + void fetchIntermediateCredentials() throws Exception { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -142,7 +143,8 @@ public HttpTransport create() { intermediateCredentials.getIntermediateAccessToken().getTokenValue()); } - @Test void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { + @Test + void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { String universeDomain = "foobar"; GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() @@ -163,7 +165,8 @@ public HttpTransport create() { assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain)); } - @Test void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() + @Test + void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() throws Exception { // Simulate error when refreshing the source credential. mockTokenServerTransportFactory.transport.setError(new IOException()); @@ -181,7 +184,8 @@ public HttpTransport create() { assertEquals("Unable to refresh the provided source credential.", thrown.getMessage()); } - @Test void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() + @Test + void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() throws Exception { // Simulate STS not returning expires_in. mockStsTransportFactory.transport.setReturnExpiresIn(false); @@ -209,7 +213,8 @@ public HttpTransport create() { sourceAccessToken.getExpirationTime(), intermediateAccessToken.getExpirationTime()); } - @Test void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() + @Test + void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -228,7 +233,8 @@ public HttpTransport create() { assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); } - @Test void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { + @Test + void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.NONE); @@ -243,7 +249,8 @@ public HttpTransport create() { assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); } - @Test void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { + @Test + void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -264,7 +271,8 @@ public HttpTransport create() { assertEquals(1 + numRefresh, mockStsTransportFactory.transport.getRequestCount()); } - @Test void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { + @Test + void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -298,7 +306,8 @@ public HttpTransport create() { assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } - @Test void refreshCredentialsIfRequired_blockingMultiThread() + @Test + void refreshCredentialsIfRequired_blockingMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -318,7 +327,8 @@ public HttpTransport create() { assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } - @Test void refreshCredentialsIfRequired_asyncMultiThread() + @Test + void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -345,7 +355,8 @@ public HttpTransport create() { assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } - @Test void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOException() + @Test + void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOException() throws Exception { // Simulate error when refreshing the source credential. mockTokenServerTransportFactory.transport.setError(new IOException()); @@ -364,7 +375,8 @@ public HttpTransport create() { } // Tests related to the builder methods. - @Test void builder_noSourceCredential_throws() { + @Test + void builder_noSourceCredential_throws() { NullPointerException exception = assertThrows( NullPointerException.class, @@ -375,7 +387,8 @@ public HttpTransport create() { assertEquals("Source credential must not be null.", exception.getMessage()); } - @Test void builder_minimumTokenLifetime_negative_throws() throws IOException { + @Test + void builder_minimumTokenLifetime_negative_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -389,7 +402,8 @@ public HttpTransport create() { assertEquals("Minimum token lifetime must be greater than zero.", exception.getMessage()); } - @Test void builder_minimumTokenLifetime_zero_throws() throws IOException { + @Test + void builder_minimumTokenLifetime_zero_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -403,7 +417,8 @@ public HttpTransport create() { assertEquals("Minimum token lifetime must be greater than zero.", exception.getMessage()); } - @Test void builder_refreshMargin_negative_throws() throws IOException { + @Test + void builder_refreshMargin_negative_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -417,7 +432,8 @@ public HttpTransport create() { assertEquals("Refresh margin must be greater than zero.", exception.getMessage()); } - @Test void builder_refreshMargin_zero_throws() throws IOException { + @Test + void builder_refreshMargin_zero_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -431,7 +447,8 @@ public HttpTransport create() { assertEquals("Refresh margin must be greater than zero.", exception.getMessage()); } - @Test void builder_setsCorrectDefaultValues() throws IOException { + @Test + void builder_setsCorrectDefaultValues() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); ClientSideCredentialAccessBoundaryFactory factory = @@ -445,7 +462,8 @@ public HttpTransport create() { factory.getTokenExchangeEndpoint()); } - @Test void builder_universeDomainMismatch_throws() throws IOException { + @Test + void builder_universeDomainMismatch_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -462,7 +480,8 @@ public HttpTransport create() { exception.getMessage()); } - @Test void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { + @Test + void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -481,7 +500,8 @@ public HttpTransport create() { exception.getMessage()); } - @Test void builder_invalidRefreshMargin_throws() throws IOException { + @Test + void builder_invalidRefreshMargin_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -499,7 +519,8 @@ public HttpTransport create() { exception.getMessage()); } - @Test void builder_invalidMinimumTokenLifetime_throws() throws IOException { + @Test + void builder_invalidMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -517,7 +538,8 @@ public HttpTransport create() { exception.getMessage()); } - @Test void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException { + @Test + void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -532,7 +554,8 @@ public HttpTransport create() { factory.getMinimumTokenLifetime()); } - @Test void builder_refreshMarginNotSet_usesDefault() throws IOException { + @Test + void builder_refreshMarginNotSet_usesDefault() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -684,7 +707,8 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S return ClientSideAccessBoundary.parseFrom(rawRestrictions); } - @Test void generateToken_withAvailablityCondition_success() throws Exception { + @Test + void generateToken_withAvailablityCondition_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -743,7 +767,8 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S assertEquals("b", expr.getCallExpr().getArgs(1).getIdentExpr().getName()); } - @Test void generateToken_withoutAvailabilityCondition_success() throws Exception { + @Test + void generateToken_withoutAvailabilityCondition_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -794,7 +819,8 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S assertFalse(rule.hasCompiledAvailabilityCondition()); } - @Test void generateToken_withMultipleRules_success() throws Exception { + @Test + void generateToken_withMultipleRules_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -857,7 +883,8 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S assertFalse(rule2.hasCompiledAvailabilityCondition()); } - @Test void generateToken_withInvalidAvailabilityCondition_failure() throws Exception { + @Test + void generateToken_withInvalidAvailabilityCondition_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -893,7 +920,8 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S assertThrows(CelValidationException.class, () -> factory.generateToken(accessBoundary)); } - @Test void generateToken_withSessionKeyNotBase64Encoded_failure() throws Exception { + @Test + void generateToken_withSessionKeyNotBase64Encoded_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); transportFactory.transport.setAccessBoundarySessionKey("invalid_key"); @@ -929,7 +957,8 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S assertThrows(IllegalStateException.class, () -> factory.generateToken(accessBoundary)); } - @Test void generateToken_withMalformSessionKey_failure() throws Exception { + @Test + void generateToken_withMalformSessionKey_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); transportFactory.transport.setAccessBoundarySessionKey("aW52YWxpZF9rZXk="); diff --git a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java index 786eaff18..04a8a926d 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java @@ -96,7 +96,8 @@ final class ITClientSideCredentialAccessBoundaryTest { * downscoped token. 2. Validating that we do not have permission to retrieve a different object * in the same bucket. */ - @Test void clientSideCredentialAccessBoundary_serviceAccountSource() throws IOException { + @Test + void clientSideCredentialAccessBoundary_serviceAccountSource() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = () -> { ServiceAccountCredentials sourceCredentials = diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index a2e1ebe4b..45acbecac 100644 --- a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java +++ b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java @@ -57,7 +57,8 @@ class HttpCredentialsAdapterTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; - @Test void initialize_populatesOAuth2Credentials() throws IOException { + @Test + void initialize_populatesOAuth2Credentials() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -83,7 +84,8 @@ class HttpCredentialsAdapterTest { assertEquals(authorizationHeader, expectedAuthorization); } - @Test void initialize_populatesOAuth2Credentials_handle401() throws IOException { + @Test + void initialize_populatesOAuth2Credentials_handle401() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; @@ -120,7 +122,8 @@ class HttpCredentialsAdapterTest { assertEquals(MockTokenCheckingTransport.SUCCESS_CONTENT, response.parseAsString()); } - @Test void initialize_noURI() throws IOException { + @Test + void initialize_noURI() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory tokenServerTransportFactory = @@ -148,7 +151,8 @@ class HttpCredentialsAdapterTest { assertEquals(authorizationHeader, expectedAuthorization); } - @Test void getCredentials() { + @Test + void getCredentials() { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java index 498ae5072..2b8f3d562 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java @@ -99,7 +99,8 @@ public Process createProcess(InputStream metadata) throws IOException { } } - @Test void testGetKeyStoreNonZeroExitCode() + @Test + void testGetKeyStoreNonZeroExitCode() throws IOException, InterruptedException, GeneralSecurityException { InputStream metadata = this.getClass() @@ -116,7 +117,8 @@ public Process createProcess(InputStream metadata) throws IOException { "expected to fail with nonzero exit code"); } - @Test void testExtractCertificateProviderCommand() throws IOException { + @Test + void testExtractCertificateProviderCommand() throws IOException { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mtls_context_aware_metadata.json"); List command = SecureConnectProvider.extractCertificateProviderCommand(inputStream); @@ -125,13 +127,15 @@ public Process createProcess(InputStream metadata) throws IOException { assertEquals("some_argument", command.get(1)); } - @Test void testRunCertificateProviderCommandSuccess() throws IOException, InterruptedException { + @Test + void testRunCertificateProviderCommandSuccess() throws IOException, InterruptedException { Process certCommandProcess = new TestCertProviderCommandProcess(0, false); int exitValue = SecureConnectProvider.runCertificateProviderCommand(certCommandProcess, 100); assertEquals(0, exitValue); } - @Test void testRunCertificateProviderCommandTimeout() throws InterruptedException { + @Test + void testRunCertificateProviderCommandTimeout() throws InterruptedException { Process certCommandProcess = new TestCertProviderCommandProcess(0, true); IOException actual = assertThrows( @@ -140,7 +144,8 @@ public Process createProcess(InputStream metadata) throws IOException { assertTrue(actual.getMessage().contains("SecureConnect: Cert provider command timed out"), "expected to fail with timeout"); } - @Test void testGetKeyStore_FileNotFoundException() + @Test + void testGetKeyStore_FileNotFoundException() throws IOException, GeneralSecurityException, InterruptedException { SecureConnectProvider provider = new SecureConnectProvider(new TestProcessProvider(0), "/invalid/metadata/path.json"); diff --git a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java index c09802012..8490144ad 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java @@ -43,7 +43,8 @@ class WorkloadCertificateConfigurationTest { - @Test void workloadCertificateConfig_fromStream_Succeeds() throws IOException { + @Test + void workloadCertificateConfig_fromStream_Succeeds() throws IOException { String certPath = "cert.crt"; String privateKeyPath = "key.crt"; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); @@ -53,7 +54,8 @@ class WorkloadCertificateConfigurationTest { assertNotNull(config); } - @Test void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws IOException { + @Test + void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws IOException { String certPath = ""; String privateKeyPath = "key.crt"; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); @@ -70,7 +72,8 @@ class WorkloadCertificateConfigurationTest { "The cert_path field must be provided in the workload certificate configuration.")); } - @Test void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() throws IOException { + @Test + void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() throws IOException { String certPath = "cert.crt"; String privateKeyPath = ""; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); @@ -87,7 +90,8 @@ class WorkloadCertificateConfigurationTest { "The key_path field must be provided in the workload certificate configuration.")); } - @Test void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws IOException { + @Test + void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws IOException { GenericJson json = new GenericJson(); json.put("cert_configs", new GenericJson()); InputStream configStream = TestUtils.jsonToInputStream(json); @@ -104,7 +108,8 @@ class WorkloadCertificateConfigurationTest { "A workload certificate configuration must be provided in the cert_configs object.")); } - @Test void workloadCertificateConfig_fromStreamMissingCertConfig_Fails() throws IOException { + @Test + void workloadCertificateConfig_fromStreamMissingCertConfig_Fails() throws IOException { GenericJson json = new GenericJson(); InputStream configStream = TestUtils.jsonToInputStream(json); diff --git a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java index 7d62c4170..de684377b 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java @@ -86,7 +86,8 @@ class X509ProviderTest { + "VUV6b25kqrcu\n" + "-----END PRIVATE KEY-----"; - @Test void x509Provider_fileDoesntExist_throws() { + @Test + void x509Provider_fileDoesntExist_throws() { String certConfigPath = "badfile.txt"; X509Provider testProvider = new TestX509Provider(certConfigPath); String expectedErrorMessage = "File does not exist."; @@ -96,7 +97,8 @@ class X509ProviderTest { assertTrue(exception.getMessage().contains(expectedErrorMessage)); } - @Test void x509Provider_emptyFile_throws() { + @Test + void x509Provider_emptyFile_throws() { String certConfigPath = "certConfig.txt"; InputStream certConfigStream = new ByteArrayInputStream("".getBytes()); TestX509Provider testProvider = new TestX509Provider(certConfigPath); @@ -108,7 +110,8 @@ class X509ProviderTest { assertTrue(exception.getMessage().contains(expectedErrorMessage)); } - @Test void x509Provider_succeeds() throws IOException, KeyStoreException, CertificateException { + @Test + void x509Provider_succeeds() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; String keyPath = "key.crt"; @@ -131,7 +134,8 @@ class X509ProviderTest { assertNotNull(store.getCertificateAlias(expectedCert)); } - @Test void x509Provider_succeeds_withEnvVariable() + @Test + void x509Provider_succeeds_withEnvVariable() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; @@ -156,7 +160,8 @@ class X509ProviderTest { assertNotNull(store.getCertificateAlias(expectedCert)); } - @Test void x509Provider_succeeds_withWellKnownPath() + @Test + void x509Provider_succeeds_withWellKnownPath() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index e5582a3d7..43b575be7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -61,7 +61,8 @@ class AppEngineCredentialsTest extends BaseSerializationTest { private static final Collection DEFAULT_SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope3")); - @Test void constructor_usesAppIdentityService() throws IOException { + @Test + void constructor_usesAppIdentityService() throws IOException { Collection scopes = Collections.singleton("SomeScope"); TestAppEngineCredentials credentials = new TestAppEngineCredentials(scopes); List forNameArgs = credentials.getForNameArgs(); @@ -72,7 +73,8 @@ class AppEngineCredentialsTest extends BaseSerializationTest { assertEquals(AppEngineCredentials.SIGNING_RESULT_CLASS, forNameArgs.get(3)); } - @Test void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { + @Test + void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { try { new TestAppEngineCredentialsNoSdk(); fail("Credential expected to fail to load if credential class not present."); @@ -87,24 +89,28 @@ class AppEngineCredentialsTest extends BaseSerializationTest { } } - @Test void refreshAccessToken_sameAs() throws IOException { + @Test + void refreshAccessToken_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); } - @Test void getAccount_sameAs() throws IOException { + @Test + void getAccount_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(EXPECTED_ACCOUNT, credentials.getAccount()); } - @Test void sign_sameAs() throws IOException { + @Test + void sign_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertArrayEquals(EXPECTED_SIGNATURE, credentials.sign("Bytes to sign".getBytes())); } - @Test void createScoped_clonesWithScopes() throws IOException { + @Test + void createScoped_clonesWithScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); try { @@ -122,7 +128,8 @@ class AppEngineCredentialsTest extends BaseSerializationTest { assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); } - @Test void createScoped_defaultScopes() throws IOException { + @Test + void createScoped_defaultScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); @@ -140,7 +147,8 @@ class AppEngineCredentialsTest extends BaseSerializationTest { assertEquals(EXPECTED_EXPIRATION_DATE, accessToken.getExpirationTime()); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { GoogleCredentials credentials = new TestAppEngineCredentials(SCOPES); GoogleCredentials otherCredentials = new TestAppEngineCredentials(SCOPES); assertTrue(credentials.equals(credentials)); @@ -148,7 +156,8 @@ class AppEngineCredentialsTest extends BaseSerializationTest { assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_scopes() throws IOException { + @Test + void equals_false_scopes() throws IOException { final Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(emptyScopes); @@ -157,7 +166,8 @@ class AppEngineCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { String expectedToString = String.format( "TestAppEngineCredentials{scopes=[%s], scopesRequired=%b}", "SomeScope", false); @@ -166,12 +176,14 @@ class AppEngineCredentialsTest extends BaseSerializationTest { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { AppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(credentials.hashCode(), credentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(scopes); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java index a6e793150..fd25e5c2a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -109,7 +109,8 @@ class AwsCredentialsTest extends BaseSerializationTest { private static final ExternalAccountSupplierContext emptyContext = ExternalAccountSupplierContext.newBuilder().setAudience("").setSubjectTokenType("").build(); - @Test void test_awsCredentialSource() { + @Test + void test_awsCredentialSource() { String keys[] = {"region_url", "url", "imdsv2_session_token_url"}; for (String key : keys) { Map credentialSourceWithInvalidUrl = buildAwsIpv6CredentialSourceMap(); @@ -120,7 +121,8 @@ class AwsCredentialsTest extends BaseSerializationTest { } } - @Test void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -141,7 +143,8 @@ class AwsCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "aws", false, false); } - @Test void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -170,7 +173,8 @@ class AwsCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "aws", true, false); } - @Test void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + @Test + void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -209,7 +213,8 @@ class AwsCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "aws", true, true); } - @Test void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() + @Test + void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -236,7 +241,8 @@ class AwsCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "programmatic", false, false); } - @Test void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() + @Test + void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -377,7 +383,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(4), AWS_CREDENTIALS_URL_WITH_ROLE, sessionTokenHeader); } - @Test void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() + @Test + void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -422,7 +429,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals(0, requests.size()); } - @Test void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() + @Test + void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -467,7 +475,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals(0, requests.size()); } - @Test void retrieveSubjectToken_noRegion_expectThrows() { + @Test + void retrieveSubjectToken_noRegion_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -494,7 +503,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS); } - @Test void retrieveSubjectToken_noRole_expectThrows() { + @Test + void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -525,7 +535,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL, EMPTY_STRING_HEADERS); } - @Test void retrieveSubjectToken_noCredentials_expectThrows() { + @Test + void retrieveSubjectToken_noCredentials_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -559,7 +570,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(2), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS); } - @Test void retrieveSubjectToken_noRegionUrlProvided() { + @Test + void retrieveSubjectToken_noRegionUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -588,7 +600,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertTrue(requests.isEmpty()); } - @Test void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { + @Test + void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -626,7 +639,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertNotNull(headers.get("Authorization")); } - @Test void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IOException { + @Test + void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -668,7 +682,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertNotNull(headers.get("Authorization")); } - @Test void retrieveSubjectToken_passesContext() throws IOException { + @Test + void retrieveSubjectToken_passesContext() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -697,7 +712,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { awsCredential.retrieveSubjectToken(); } - @Test void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOException { + @Test + void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -723,7 +739,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } } - @Test void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { + @Test + void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -742,7 +759,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertNull(credentials.getSessionToken()); } - @Test void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { + @Test + void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -774,7 +792,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals("awsSessionToken", credentials.getSessionToken()); } - @Test void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerCall() + @Test + void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerCall() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider @@ -795,7 +814,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals("awsSessionToken", credentials.getSessionToken()); } - @Test void getAwsSecurityCredentials_fromMetadataServer() throws IOException { + @Test + void getAwsSecurityCredentials_fromMetadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -822,7 +842,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS); } - @Test void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { + @Test + void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -850,7 +871,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertTrue(requests.isEmpty()); } - @Test void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { + @Test + void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_REGION", "region"); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -875,7 +897,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertTrue(requests.isEmpty()); } - @Test void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { + @Test + void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -899,7 +922,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertTrue(requests.isEmpty()); } - @Test void getAwsRegion_metadataServer() throws IOException { + @Test + void getAwsRegion_metadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredentials = @@ -925,7 +949,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS); } - @Test void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + @Test + void createdScoped_clonedCredentialWithAddedScopes() throws IOException { AwsCredentials credentials = AwsCredentials.newBuilder(AWS_CREDENTIAL) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -955,7 +980,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals("universeDomain", newCredentials.getUniverseDomain()); } - @Test void credentialSource_invalidAwsEnvironmentId() { + @Test + void credentialSource_invalidAwsEnvironmentId() { Map credentialSource = new HashMap<>(); credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "azure1"); @@ -968,7 +994,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } } - @Test void credentialSource_invalidAwsEnvironmentVersion() { + @Test + void credentialSource_invalidAwsEnvironmentVersion() { Map credentialSource = new HashMap<>(); int environmentVersion = 2; credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); @@ -985,7 +1012,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } } - @Test void credentialSource_missingRegionalCredVerificationUrl() { + @Test + void credentialSource_missingRegionalCredVerificationUrl() { try { new AwsCredentialSource(new HashMap()); fail("Exception should be thrown."); @@ -996,7 +1024,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } } - @Test void builder_allFields() throws IOException { + @Test + void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1031,7 +1060,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals("universeDomain", credentials.getUniverseDomain()); } - @Test void builder_missingUniverseDomain_defaults() throws IOException { + @Test + void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1067,7 +1097,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void newBuilder_allFields() throws IOException { + @Test + void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1104,7 +1135,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals(credentials.getUniverseDomain(), newBuilderCreds.getUniverseDomain()); } - @Test void newBuilder_noUniverseDomain_defaults() throws IOException { + @Test + void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1140,7 +1172,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { assertEquals(GOOGLE_DEFAULT_UNIVERSE, newBuilderCreds.getUniverseDomain()); } - @Test void builder_defaultRegionalCredentialVerificationUrlOverride() throws IOException { + @Test + void builder_defaultRegionalCredentialVerificationUrlOverride() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsSecurityCredentialsSupplier supplier = @@ -1167,7 +1200,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { credentials.getRegionalCredentialVerificationUrl()); } - @Test void builder_supplierAndCredSourceThrows() throws IOException { + @Test + void builder_supplierAndCredSourceThrows() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsSecurityCredentialsSupplier supplier = @@ -1197,7 +1231,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } } - @Test void builder_noSupplieOrCredSourceThrows() throws IOException { + @Test + void builder_noSupplieOrCredSourceThrows() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); Supplier testSupplier = () -> null; @@ -1225,7 +1260,8 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials testCredentials = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java index dacd30014..0161d2983 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java @@ -70,7 +70,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.sreq - @Test void sign_getHost() { + @Test + void sign_getHost() { String url = "https://host.foo.com"; Map headers = new HashMap<>(); @@ -100,7 +101,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.sreq - @Test void sign_getHostRelativePath() { + @Test + void sign_getHostRelativePath() { String url = "https://host.foo.com/foo/bar/../.."; Map headers = new HashMap<>(); @@ -130,7 +132,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.sreq - @Test void sign_getHostInvalidPath() { + @Test + void sign_getHostInvalidPath() { String url = "https://host.foo.com/./"; Map headers = new HashMap<>(); @@ -160,7 +163,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.sreq - @Test void sign_getHostDotPath() { + @Test + void sign_getHostDotPath() { String url = "https://host.foo.com/./foo"; Map headers = new HashMap<>(); @@ -190,7 +194,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.sreq - @Test void sign_getHostUtf8Path() { + @Test + void sign_getHostUtf8Path() { String url = "https://host.foo.com/%E1%88%B4"; Map headers = new HashMap<>(); @@ -220,7 +225,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.sreq - @Test void sign_getHostDuplicateQueryParam() { + @Test + void sign_getHostDuplicateQueryParam() { String url = "https://host.foo.com/?foo=Zoo&foo=aha"; Map headers = new HashMap<>(); @@ -250,7 +256,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.sreq - @Test void sign_postWithUpperCaseHeaderKey() { + @Test + void sign_postWithUpperCaseHeaderKey() { String url = "https://host.foo.com/"; String headerKey = "ZOO"; String headerValue = "zoobar"; @@ -284,7 +291,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.sreq - @Test void sign_postWithUpperCaseHeaderValue() { + @Test + void sign_postWithUpperCaseHeaderValue() { String url = "https://host.foo.com/"; String headerKey = "zoo"; String headerValue = "ZOOBAR"; @@ -318,7 +326,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.sreq - @Test void sign_postWithHeader() { + @Test + void sign_postWithHeader() { String url = "https://host.foo.com/"; String headerKey = "p"; String headerValue = "phfft"; @@ -352,7 +361,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.sreq - @Test void sign_postWithBodyNoCustomHeaders() { + @Test + void sign_postWithBodyNoCustomHeaders() { String url = "https://host.foo.com/"; String headerKey = "Content-Type"; String headerValue = "application/x-www-form-urlencoded"; @@ -387,7 +397,8 @@ class AwsRequestSignerTest { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.sreq - @Test void sign_postWithQueryString() { + @Test + void sign_postWithQueryString() { String url = "https://host.foo.com/?foo=bar"; Map headers = new HashMap<>(); @@ -415,7 +426,8 @@ class AwsRequestSignerTest { assertEquals(URI.create(url).normalize().toString(), signature.getUrl()); } - @Test void sign_getDescribeRegions() { + @Test + void sign_getDescribeRegions() { String url = "https://ec2.us-east-2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15"; Map additionalHeaders = new HashMap<>(); @@ -445,7 +457,8 @@ class AwsRequestSignerTest { assertEquals(URI.create(url).normalize().toString(), signature.getUrl()); } - @Test void sign_postGetCallerIdentity() { + @Test + void sign_postGetCallerIdentity() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; Map additionalHeaders = new HashMap<>(); @@ -475,7 +488,8 @@ class AwsRequestSignerTest { assertEquals(URI.create(url).normalize().toString(), signature.getUrl()); } - @Test void sign_postGetCallerIdentityNoToken() { + @Test + void sign_postGetCallerIdentityNoToken() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; AwsSecurityCredentials awsSecurityCredentialsWithoutToken = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java index c8e2c28ea..9c7e551b7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java @@ -104,13 +104,15 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { intermediateCertBytesFromFile = Files.readAllBytes(Paths.get(intermediateCertUrl.toURI())); } - @Test void parseCertificate_validData_returnsCertificate() throws Exception { + @Test + void parseCertificate_validData_returnsCertificate() throws Exception { X509Certificate cert = CertificateIdentityPoolSubjectTokenSupplier.parseCertificate(testCertBytesFromFile); assertNotNull(cert); } - @Test void parseCertificate_emptyData_throwsIllegalArgumentException() { + @Test + void parseCertificate_emptyData_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -119,7 +121,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { "Invalid certificate data: Certificate file is empty or null.", exception.getMessage()); } - @Test void parseCertificate_nullData_throwsIllegalArgumentException() { + @Test + void parseCertificate_nullData_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -128,7 +131,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { "Invalid certificate data: Certificate file is empty or null.", exception.getMessage()); } - @Test void parseCertificate_invalidData_throwsCertificateException() { + @Test + void parseCertificate_invalidData_throwsCertificateException() { CertificateException exception = assertThrows( CertificateException.class, @@ -136,7 +140,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals("Failed to parse X.509 certificate data.", exception.getMessage()); } - @Test void getSubjectToken_withoutTrustChain_success() throws Exception { + @Test + void getSubjectToken_withoutTrustChain_success() throws Exception { // Calculate expected result based on the file content. CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate expectedCert = @@ -152,7 +157,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals(expectedSubjectToken, actualSubjectToken); } - @Test void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { + @Test + void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { // Configure mock to return the path to the trust chain file with leaf. ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("trust_chain_with_leaf.pem"); @@ -185,7 +191,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals(expectedSubjectToken, actualSubjectToken); } - @Test void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { + @Test + void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { // Configure mock to return the path to the trust chain file WITHOUT leaf. ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("trust_chain_without_leaf.pem"); @@ -223,7 +230,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { // when the trust chain file is provided and contains the leaf certificate, // but the leaf certificate is not the *first* certificate in that file. // For example, an intermediate certificate appears before the leaf certificate. - @Test void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException() { + @Test + void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException() { ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("trust_chain_wrong_order.pem"); assertNotNull(trustChainUrl, "Test trust chain file (wrong order) not found!"); @@ -247,7 +255,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals(expectedRootErrorMessage, cause.getMessage()); } - @Test void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { + @Test + void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { // Configure mock to use the leaf certificate file itself as the trust chain file, // simulating a scenario where the trust chain file contains only the leaf. ClassLoader classLoader = getClass().getClassLoader(); @@ -274,7 +283,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals(expectedSubjectToken, actualSubjectToken); } - @Test void getSubjectToken_trustChainFileNotFound_throwsIOException() { + @Test + void getSubjectToken_trustChainFileNotFound_throwsIOException() { // Configure mock to return a non-existent path for the trust chain. String nonExistentPath = "/path/to/non/existent/trust_chain.pem"; when(mockCertificateConfig.getTrustChainPath()).thenReturn(nonExistentPath); @@ -290,7 +300,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals("Trust chain file not found: " + nonExistentPath, exception.getMessage()); } - @Test void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws Exception { + @Test + void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws Exception { // Create a temporary file with invalid cert data for the trust chain. File invalidTrustChainFile = File.createTempFile("invalid_trust_chain", ".pem"); invalidTrustChainFile.deleteOnExit(); @@ -322,7 +333,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { "Error loading PEM certificates from the trust chain file: " + invalidPath)); } - @Test void getSubjectToken_leafCertFileNotFound_throwsIOException() { + @Test + void getSubjectToken_leafCertFileNotFound_throwsIOException() { // Configure mock to return a non-existent path for the leaf certificate. String nonExistentPath = "/path/to/non/existent/leaf.pem"; when(mockCredentialSource.getCredentialLocation()).thenReturn(nonExistentPath); @@ -346,7 +358,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals(expectedCausePath, actualCausePath); } - @Test void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exception { + @Test + void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exception { // Create a temporary file with invalid cert data. File invalidLeafFile = File.createTempFile("invalid_leaf", ".pem"); invalidLeafFile.deleteOnExit(); @@ -373,7 +386,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { exception.getMessage()); } - @Test void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertificateException() + @Test + void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertificateException() throws IOException { // Create a temporary file with content that does not match PEM certificate blocks. File trustChainFile = File.createTempFile("non_pem_content_trust_chain", ".txt"); @@ -394,13 +408,15 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertEquals(expectedMessage, exception.getMessage()); } - @Test void readTrustChain_nullPath_returnsEmptyList() throws Exception { + @Test + void readTrustChain_nullPath_returnsEmptyList() throws Exception { List certs = CertificateIdentityPoolSubjectTokenSupplier.readTrustChain(null); assertNotNull(certs); assertTrue(certs.isEmpty()); } - @Test void readTrustChain_emptyFile_returnsEmptyList() throws IOException, CertificateException { + @Test + void readTrustChain_emptyFile_returnsEmptyList() throws IOException, CertificateException { // Create an empty temporary file. File emptyFile = File.createTempFile("empty_trust_chain", ".pem"); emptyFile.deleteOnExit(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java index c3da45974..f7cdbb305 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java @@ -46,7 +46,8 @@ class ClientIdTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; - @Test void constructor() { + @Test + void constructor() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); @@ -60,13 +61,15 @@ void constructor_nullClientId_throws() { NullPointerException.class, () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); } - @Test void constructor_nullClientSecret() { + @Test + void constructor_nullClientSecret() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).build(); assertEquals(CLIENT_ID, clientId.getClientId()); assertNull(clientId.getClientSecret()); } - @Test void fromJson_web() throws IOException { + @Test + void fromJson_web() throws IOException { GenericJson json = writeClientIdJson("web", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -75,7 +78,8 @@ void constructor_nullClientId_throws() { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test void fromJson_installed() throws IOException { + @Test + void fromJson_installed() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -84,7 +88,8 @@ void constructor_nullClientId_throws() { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test void fromJson_installedNoSecret() throws IOException { + @Test + void fromJson_installedNoSecret() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, null); ClientId clientId = ClientId.fromJson(json); @@ -114,7 +119,8 @@ void fromJson_zeroLengthClientId_throws() throws IOException { assertThrows(IOException.class, () -> ClientId.fromJson(json)); } - @Test void fromResource() throws IOException { + @Test + void fromResource() throws IOException { ClientId clientId = ClientId.fromResource(ClientIdTest.class, "/client_secret.json"); assertEquals(CLIENT_ID, clientId.getClientId()); @@ -127,7 +133,8 @@ void fromResource_badResource() throws IOException { NullPointerException.class, () -> ClientId.fromResource(ClientIdTest.class, "invalid.json")); } - @Test void fromStream() throws IOException { + @Test + void fromStream() throws IOException { String text = "{" + "\"web\": {" @@ -147,7 +154,8 @@ void fromResource_badResource() throws IOException { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test void fromStream_invalidJson_doesNotThrow() throws IOException { + @Test + void fromStream_invalidJson_doesNotThrow() throws IOException { String invalidJson = "{" + "\"web\": {" diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java index 5ec50d8a2..fdd60474e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java @@ -48,7 +48,8 @@ class CloudShellCredentialsTest extends BaseSerializationTest { - @Test void refreshAccessToken() throws IOException { + @Test + void refreshAccessToken() throws IOException { final ServerSocket authSocket = new ServerSocket(0); try { Runnable serverTask = @@ -81,33 +82,38 @@ public void run() { } } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertTrue(credentials.equals(otherCredentials)); assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_authPort() throws IOException { + @Test + void equals_false_authPort() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(43).build(); assertFalse(credentials.equals(otherCredentials)); assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { String expectedToString = String.format("CloudShellCredentials{authPort=%d}", 42); GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); assertEquals(credentials, deserializedCredentials); @@ -116,7 +122,8 @@ public void run() { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test void toBuilder() { + @Test + void toBuilder() { CloudShellCredentials credentials = CloudShellCredentials.newBuilder() .setAuthPort(42) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java index c8702a87b..16dd48543 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -126,7 +126,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { }) .collect(Collectors.toMap(data -> data[0], data -> data[1])); - @Test void buildTokenUrlWithScopes_null_scopes() { + @Test + void buildTokenUrlWithScopes_null_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); Collection scopes = credentials.getScopes(); @@ -136,7 +137,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertTrue(scopes.isEmpty()); } - @Test void buildTokenUrlWithScopes_empty_scopes() { + @Test + void buildTokenUrlWithScopes_empty_scopes() { ComputeEngineCredentials.Builder builder = ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); ComputeEngineCredentials credentials = builder.build(); @@ -148,7 +150,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertTrue(builder.getScopes().isEmpty()); } - @Test void buildTokenUrlWithScopes_single_scope() { + @Test + void buildTokenUrlWithScopes_single_scope() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(Arrays.asList("foo")).build(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -159,7 +162,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals("foo", scopes.toArray()[0]); } - @Test void buildTokenUrlWithScopes_multiple_scopes() { + @Test + void buildTokenUrlWithScopes_multiple_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(Arrays.asList(null, "foo", "", "bar")) @@ -173,7 +177,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals("bar", scopes.toArray()[1]); } - @Test void buildTokenUrlWithScopes_defaultScopes() { + @Test + void buildTokenUrlWithScopes_defaultScopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().build(); credentials = (ComputeEngineCredentials) @@ -187,7 +192,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals("bar", scopes.toArray()[1]); } - @Test void buildTokenUrl_nullTransport() { + @Test + void buildTokenUrl_nullTransport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(null) @@ -198,7 +204,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?binding-enforcement=on", tokenUrl); } - @Test void buildTokenUrl_nullBindingEnforcement() { + @Test + void buildTokenUrl_nullBindingEnforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -209,7 +216,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?transport=mtls", tokenUrl); } - @Test void buildTokenUrl_nullTransport_nullBindingEnforcement() { + @Test + void buildTokenUrl_nullTransport_nullBindingEnforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(null) @@ -220,7 +228,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL, softBoundTokenUrl); } - @Test void buildTokenUrl_mtls_transport() { + @Test + void buildTokenUrl_mtls_transport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -230,7 +239,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?transport=mtls", tokenUrl); } - @Test void buildTokenUrl_iam_enforcement() { + @Test + void buildTokenUrl_iam_enforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setBindingEnforcement(ComputeEngineCredentials.BindingEnforcement.IAM_POLICY) @@ -240,7 +250,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?binding-enforcement=iam-policy", tokenUrl); } - @Test void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { + @Test + void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -251,7 +262,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?transport=mtls&binding-enforcement=iam-policy", softBoundTokenUrl); } - @Test void buildTokenUrl_always_enforced() { + @Test + void buildTokenUrl_always_enforced() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setBindingEnforcement(ComputeEngineCredentials.BindingEnforcement.ON) @@ -261,7 +273,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?binding-enforcement=on", tokenUrl); } - @Test void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { + @Test + void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -272,7 +285,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?transport=mtls&binding-enforcement=on", hardBoundTokenUrl); } - @Test void buildTokenUrlHardDirectPathBound_alts_transport() { + @Test + void buildTokenUrlHardDirectPathBound_alts_transport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.ALTS) @@ -282,7 +296,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_URL + "?transport=alts", hardBoundTokenUrl); } - @Test void buildScoped_scopesPresent() throws IOException { + @Test + void buildScoped_scopesPresent() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials scopedCredentials = @@ -293,7 +308,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals("foo", scopes.toArray()[0]); } - @Test void buildScoped_correctMargins() throws IOException { + @Test + void buildScoped_correctMargins() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials scopedCredentials = @@ -306,7 +322,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { ComputeEngineCredentials.COMPUTE_REFRESH_MARGIN, scopedCredentials.getRefreshMargin()); } - @Test void buildScoped_explicitUniverse() throws IOException { + @Test + void buildScoped_explicitUniverse() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -319,7 +336,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertTrue(scopedCredentials.isExplicitUniverseDomain()); } - @Test void createScoped_defaultScopes() { + @Test + void createScoped_defaultScopes() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); Collection scopes = ((ComputeEngineCredentials) credentials).getScopes(); @@ -328,7 +346,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals("foo", scopes.toArray()[0]); } - @Test void buildScoped_quotaProjectId() throws IOException { + @Test + void buildScoped_quotaProjectId() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -340,7 +359,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals("some-project-id", scopedCredentials.getQuotaProjectId()); } - @Test void buildDefaultScoped_explicitUniverse() throws IOException { + @Test + void buildDefaultScoped_explicitUniverse() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -353,7 +373,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertTrue(scopedCredentials.isExplicitUniverseDomain()); } - @Test void create_scoped_correctMargins() { + @Test + void create_scoped_correctMargins() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); @@ -362,7 +383,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(ComputeEngineCredentials.COMPUTE_REFRESH_MARGIN, credentials.getRefreshMargin()); } - @Test void getRequestMetadata_hasAccessToken() throws IOException { + @Test + void getRequestMetadata_hasAccessToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); ComputeEngineCredentials credentials = @@ -377,7 +399,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertTrue(requestHeaders.get("metadata-flavor").contains("Google")); } - @Test void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTokenFromRefresh() + @Test + void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTokenFromRefresh() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -397,7 +420,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { TestUtils.assertNotContainsBearerToken(metadataForCopiedCredentials, ACCESS_TOKEN); } - @Test void getRequestMetadata_missingServiceAccount_throws() { + @Test + void getRequestMetadata_missingServiceAccount_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -414,7 +438,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { } } - @Test void getRequestMetadata_serverError_throws() { + @Test + void getRequestMetadata_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -430,7 +455,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { } } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials explicitUniverseCredentials = ComputeEngineCredentials.newBuilder() @@ -451,7 +477,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertTrue(otherExplicitUniverseCredentials.equals(explicitUniverseCredentials)); } - @Test void equals_false_transportFactory() throws IOException { + @Test + void equals_false_transportFactory() throws IOException { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); @@ -465,7 +492,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_explicit_containsFields() throws IOException { + @Test + void toString_explicit_containsFields() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); String expectedToString = @@ -486,7 +514,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -500,7 +529,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void toBuilder() { + @Test + void toBuilder() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setHttpTransportFactory(new MockMetadataServerTransportFactory()) @@ -512,7 +542,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertEquals(credentials, secondCredentials); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -532,7 +563,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test void getAccount_sameAs() throws IOException { + @Test + void getAccount_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -547,7 +579,8 @@ class ComputeEngineCredentialsTest extends BaseSerializationTest { assertFalse(headers.containsKey(MetricsUtils.API_CLIENT_HEADER)); } - @Test void getAccount_missing_throws() { + @Test + void getAccount_missing_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -582,7 +615,8 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test void getAccount_emptyContent_throws() { + @Test + void getAccount_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -616,7 +650,8 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test void sign_sameAs() { + @Test + void sign_sameAs() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -629,7 +664,8 @@ public LowLevelHttpResponse execute() throws IOException { assertArrayEquals(expectedSignature, credentials.sign(expectedSignature)); } - @Test void sign_getUniverseException() { + @Test + void sign_getUniverseException() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -646,7 +682,8 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals("Failed to sign: Error obtaining universe domain", signingException.getMessage()); } - @Test void sign_getAccountFails() { + @Test + void sign_getAccountFails() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -660,7 +697,8 @@ public LowLevelHttpResponse execute() throws IOException { assertNotNull(exception.getCause()); } - @Test void sign_accessDenied_throws() { + @Test + void sign_accessDenied_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -697,7 +735,8 @@ public LowLevelHttpResponse execute() throws IOException { assertTrue(exception.getCause().getMessage().contains("403")); } - @Test void sign_serverError_throws() { + @Test + void sign_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -734,7 +773,8 @@ public LowLevelHttpResponse execute() throws IOException { assertTrue(exception.getCause().getMessage().contains("500")); } - @Test void refresh_503_retryable_throws() { + @Test + void refresh_503_retryable_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -762,7 +802,8 @@ public LowLevelHttpResponse execute() throws IOException { assertTrue(((GoogleAuthException) exception).isRetryable()); } - @Test void refresh_non503_ioexception_throws() { + @Test + void refresh_non503_ioexception_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final Queue responseSequence = new ArrayDeque<>(); IntStream.rangeClosed(400, 600).forEach(i -> responseSequence.add(i)); @@ -797,7 +838,8 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test void getUniverseDomain_fromMetadata() throws IOException { + @Test + void getUniverseDomain_fromMetadata() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -823,7 +865,8 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test void getUniverseDomain_fromMetadata_emptyBecomesDefault() throws IOException { + @Test + void getUniverseDomain_fromMetadata_emptyBecomesDefault() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -849,7 +892,8 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test void getUniverseDomain_fromMetadata_404_default() throws IOException { + @Test + void getUniverseDomain_fromMetadata_404_default() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -875,7 +919,8 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { + @Test + void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); @@ -891,7 +936,8 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(0, transportFactory.transport.getRequestCount()); } - @Test void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { + @Test + void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); @@ -907,7 +953,8 @@ public LowLevelHttpResponse execute() throws IOException { assertEquals(0, transportFactory.transport.getRequestCount()); } - @Test void getUniverseDomain_fromMetadata_non404error_throws() throws IOException { + @Test + void getUniverseDomain_fromMetadata_non404error_throws() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); MockMetadataServerTransport transport = transportFactory.transport; @@ -929,7 +976,8 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test void sign_emptyContent_throws() { + @Test + void sign_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -965,7 +1013,8 @@ public LowLevelHttpResponse execute() throws IOException { assertTrue(exception.getCause().getMessage().contains("Empty content")); } - @Test void idTokenWithAudience_sameAs() throws IOException { + @Test + void idTokenWithAudience_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(STANDARD_ID_TOKEN); ComputeEngineCredentials credentials = @@ -985,7 +1034,8 @@ public LowLevelHttpResponse execute() throws IOException { (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test void idTokenWithAudience_standard() throws IOException { + @Test + void idTokenWithAudience_standard() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -1055,7 +1105,8 @@ void idTokenWithAudience_licenses() throws IOException { assertTrue(computeEngineClaim.containsKey("license_id")); } - @Test void idTokenWithAudience_404StatusCode() { + @Test + void idTokenWithAudience_404StatusCode() { int statusCode = HttpStatusCodes.STATUS_CODE_NOT_FOUND; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); @@ -1072,7 +1123,8 @@ void idTokenWithAudience_licenses() throws IOException { exception.getMessage()); } - @Test void idTokenWithAudience_emptyContent() { + @Test + void idTokenWithAudience_emptyContent() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setEmptyContent(true); ComputeEngineCredentials credentials = @@ -1082,7 +1134,8 @@ void idTokenWithAudience_licenses() throws IOException { assertEquals(METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE, exception.getMessage()); } - @Test void idTokenWithAudience_503StatusCode() { + @Test + void idTokenWithAudience_503StatusCode() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE); ComputeEngineCredentials credentials = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java index 19381be15..d6af084ee 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java @@ -45,7 +45,8 @@ class CredentialAccessBoundaryTest { - @Test void credentialAccessBoundary() { + @Test + void credentialAccessBoundary() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -87,7 +88,8 @@ class CredentialAccessBoundaryTest { assertNull(second.getAvailabilityCondition()); } - @Test void credentialAccessBoundary_nullRules_throws() { + @Test + void credentialAccessBoundary_nullRules_throws() { try { CredentialAccessBoundary.newBuilder().build(); fail("Should fail."); @@ -96,7 +98,8 @@ class CredentialAccessBoundaryTest { } } - @Test void credentialAccessBoundary_withoutRules_throws() { + @Test + void credentialAccessBoundary_withoutRules_throws() { try { CredentialAccessBoundary.newBuilder().setRules(new ArrayList()).build(); fail("Should fail."); @@ -105,7 +108,8 @@ class CredentialAccessBoundaryTest { } } - @Test void credentialAccessBoundary_ruleCountExceeded_throws() { + @Test + void credentialAccessBoundary_ruleCountExceeded_throws() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -125,7 +129,8 @@ class CredentialAccessBoundaryTest { } } - @Test void credentialAccessBoundary_toJson() { + @Test + void credentialAccessBoundary_toJson() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -163,7 +168,8 @@ class CredentialAccessBoundaryTest { assertEquals(expectedJson, credentialAccessBoundary.toJson()); } - @Test void accessBoundaryRule_allFields() { + @Test + void accessBoundaryRule_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -182,7 +188,8 @@ class CredentialAccessBoundaryTest { assertEquals(availabilityCondition, rule.getAvailabilityCondition()); } - @Test void accessBoundaryRule_requiredFields() { + @Test + void accessBoundaryRule_requiredFields() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -195,7 +202,8 @@ class CredentialAccessBoundaryTest { assertNull(rule.getAvailabilityCondition()); } - @Test void accessBoundaryRule_withEmptyAvailableResource_throws() { + @Test + void accessBoundaryRule_withEmptyAvailableResource_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("") @@ -207,7 +215,8 @@ class CredentialAccessBoundaryTest { } } - @Test void accessBoundaryRule_withoutAvailableResource_throws() { + @Test + void accessBoundaryRule_withoutAvailableResource_throws() { try { AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(); fail("Should fail."); @@ -216,7 +225,8 @@ class CredentialAccessBoundaryTest { } } - @Test void accessBoundaryRule_withoutAvailablePermissions_throws() { + @Test + void accessBoundaryRule_withoutAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(); fail("Should fail."); @@ -225,7 +235,8 @@ class CredentialAccessBoundaryTest { } } - @Test void accessBoundaryRule_withEmptyAvailablePermissions_throws() { + @Test + void accessBoundaryRule_withEmptyAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -237,7 +248,8 @@ class CredentialAccessBoundaryTest { } } - @Test void accessBoundaryRule_withNullAvailablePermissions_throws() { + @Test + void accessBoundaryRule_withNullAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -249,7 +261,8 @@ class CredentialAccessBoundaryTest { } } - @Test void accessBoundaryRule_withEmptyAvailablePermission_throws() { + @Test + void accessBoundaryRule_withEmptyAvailablePermission_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -261,7 +274,8 @@ class CredentialAccessBoundaryTest { } } - @Test void availabilityCondition_allFields() { + @Test + void availabilityCondition_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -274,7 +288,8 @@ class CredentialAccessBoundaryTest { assertEquals("description", availabilityCondition.getDescription()); } - @Test void availabilityCondition_expressionOnly() { + @Test + void availabilityCondition_expressionOnly() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -283,7 +298,8 @@ class CredentialAccessBoundaryTest { assertNull(availabilityCondition.getDescription()); } - @Test void availabilityCondition_nullExpression_throws() { + @Test + void availabilityCondition_nullExpression_throws() { try { AvailabilityCondition.newBuilder().setExpression(null).build(); fail("Should fail."); @@ -292,7 +308,8 @@ class CredentialAccessBoundaryTest { } } - @Test void availabilityCondition_emptyExpression_throws() { + @Test + void availabilityCondition_emptyExpression_throws() { try { AvailabilityCondition.newBuilder().setExpression("").build(); fail("Should fail."); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java index 6d8a99407..ceef91329 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java @@ -102,7 +102,8 @@ class DefaultCredentialsProviderTest { private static final String QUOTA_PROJECT_EXPLICIT = "explicit-quota-project-id"; private static final String SMBIOS_PATH_LINUX = "/sys/class/dmi/id/product_name"; - @Test void getDefaultCredentials_noCredentials_throws() { + @Test + void getDefaultCredentials_noCredentials_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -115,7 +116,8 @@ class DefaultCredentialsProviderTest { } } - @Test void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { + @Test + void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setFileSandbox(true); @@ -129,7 +131,8 @@ class DefaultCredentialsProviderTest { } } - @Test void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { + @Test + void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -149,7 +152,8 @@ class DefaultCredentialsProviderTest { } } - @Test void getDefaultCredentials_noCredentials_singleGceTestRequest() { + @Test + void getDefaultCredentials_noCredentials_singleGceTestRequest() { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -175,7 +179,8 @@ class DefaultCredentialsProviderTest { ComputeEngineCredentials.MAX_COMPUTE_PING_TRIES); } - @Test void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException { + @Test + void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "Linux"); String productFilePath = SMBIOS_PATH_LINUX; @@ -185,7 +190,8 @@ class DefaultCredentialsProviderTest { assertFalse(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test void getDefaultCredentials_static_linux() throws IOException { + @Test + void getDefaultCredentials_static_linux() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "Linux"); String productFilePath = SMBIOS_PATH_LINUX; @@ -196,7 +202,8 @@ class DefaultCredentialsProviderTest { assertTrue(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test void getDefaultCredentials_static_windows_configuredAsLinux_notGce() throws IOException { + @Test + void getDefaultCredentials_static_windows_configuredAsLinux_notGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "windows"); String productFilePath = SMBIOS_PATH_LINUX; @@ -206,7 +213,8 @@ class DefaultCredentialsProviderTest { assertFalse(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOException { + @Test + void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "macos"); String productFilePath = SMBIOS_PATH_LINUX; @@ -216,7 +224,8 @@ class DefaultCredentialsProviderTest { assertFalse(ComputeEngineCredentials.checkStaticGceDetection(testProvider)); } - @Test void checkGcpLinuxPlatformData() throws Exception { + @Test + void checkGcpLinuxPlatformData() throws Exception { BufferedReader reader; reader = new BufferedReader(new StringReader("HP Z440 Workstation")); assertFalse(ComputeEngineCredentials.checkProductNameOnLinux(reader)); @@ -228,7 +237,8 @@ class DefaultCredentialsProviderTest { assertTrue(ComputeEngineCredentials.checkProductNameOnLinux(reader)); } - @Test void getDefaultCredentials_caches() throws IOException { + @Test + void getDefaultCredentials_caches() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -239,7 +249,8 @@ class DefaultCredentialsProviderTest { assertSame(firstCall, secondCall); } - @Test void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { + @Test + void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -255,7 +266,8 @@ class DefaultCredentialsProviderTest { } } - @Test void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { + @Test + void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -272,7 +284,8 @@ class DefaultCredentialsProviderTest { } } - @Test void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() + @Test + void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -286,7 +299,8 @@ class DefaultCredentialsProviderTest { assertTrue(credentials instanceof CloudShellCredentials); } - @Test void getDefaultCredentials_compute_providesToken() throws IOException { + @Test + void getDefaultCredentials_compute_providesToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -298,7 +312,8 @@ class DefaultCredentialsProviderTest { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void getDefaultCredentials_cloudshell() throws IOException { + @Test + void getDefaultCredentials_cloudshell() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -309,7 +324,8 @@ class DefaultCredentialsProviderTest { assertEquals(((CloudShellCredentials) defaultCredentials).getAuthPort(), 4); } - @Test void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { + @Test + void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -320,7 +336,8 @@ class DefaultCredentialsProviderTest { assertEquals(((CloudShellCredentials) defaultCredentials).getAuthPort(), 4); } - @Test void getDefaultCredentials_envMissingFile_throws() { + @Test + void getDefaultCredentials_envMissingFile_throws() { final String invalidPath = "/invalid/path"; MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -336,7 +353,8 @@ class DefaultCredentialsProviderTest { } } - @Test void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { + @Test + void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -355,7 +373,8 @@ class DefaultCredentialsProviderTest { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void getDefaultCredentials_envUser_providesToken() throws IOException { + @Test + void getDefaultCredentials_envUser_providesToken() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -367,7 +386,8 @@ class DefaultCredentialsProviderTest { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test void getDefaultCredentials_GdchServiceAccount() throws IOException { + @Test + void getDefaultCredentials_GdchServiceAccount() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( @@ -435,7 +455,8 @@ void getDefaultCredentials_quota_project() throws IOException { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test void getDefaultCredentials_compute_quotaProject() throws IOException { + @Test + void getDefaultCredentials_compute_quotaProject() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv( @@ -452,7 +473,8 @@ void getDefaultCredentials_quota_project() throws IOException { assertEquals("Google", headers.get("metadata-flavor").get(0)); } - @Test void getDefaultCredentials_cloudshell_quotaProject() throws IOException { + @Test + void getDefaultCredentials_cloudshell_quotaProject() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -465,7 +487,8 @@ void getDefaultCredentials_quota_project() throws IOException { assertEquals(QUOTA_PROJECT_FROM_ENVIRONMENT, defaultCredentials.getQuotaProjectId()); } - @Test void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { + @Test + void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -480,7 +503,8 @@ void getDefaultCredentials_quota_project() throws IOException { assertEquals(transportFactory.transport.getRequestCount(), 0); } - @Test void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOException { + @Test + void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -499,14 +523,16 @@ void getDefaultCredentials_quota_project() throws IOException { assertEquals(transportFactory.transport.getRequestCount(), 0); } - @Test void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { + @Test + void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); assertEquals(ComputeEngineCredentials.getMetadataServerUrl(testProvider), "http://" + testUrl); } - @Test void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { + @Test + void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -515,7 +541,8 @@ void getDefaultCredentials_quota_project() throws IOException { "http://" + testUrl + "/computeMetadata/v1/instance/service-accounts/default/token"); } - @Test void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { + @Test + void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -529,7 +556,8 @@ void getDefaultCredentials_quota_project() throws IOException { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { + @Test + void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File configDir = new File(homeDir, ".config"); File cloudConfigDir = new File(configDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); @@ -546,7 +574,8 @@ void getDefaultCredentials_quota_project() throws IOException { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { + @Test + void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File cloudConfigDir = new File(homeDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); InputStream userStream = @@ -562,7 +591,8 @@ void getDefaultCredentials_quota_project() throws IOException { testUserProvidesToken(testProvider, USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN); } - @Test void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { + @Test + void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { final String refreshTokenEnv = "2/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; final String accessTokenEnv = "2/MkSJoj1xsli0AccessToken_NKPY2"; final String refreshTokenWkf = "3/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @@ -619,7 +649,8 @@ public void close() {} public void flush() {} } - @Test void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { + @Test + void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false, true); assertNotNull(message); assertEquals(Level.WARNING, message.getLevel()); @@ -627,12 +658,14 @@ public void flush() {} message.getMessage().equals(DefaultCredentialsProvider.CLOUDSDK_CREDENTIALS_WARNING)); } - @Test void getDefaultCredentials_wellKnownFile_noGcloudWarning() throws IOException { + @Test + void getDefaultCredentials_wellKnownFile_noGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false, false); assertNull(message); } - @Test void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { + @Test + void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(true, true); assertNull(message); } @@ -707,7 +740,8 @@ public AccessToken refreshAccessToken() throws IOException { } } - @Test void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredentialInfo() + @Test + void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredentialInfo() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); @@ -733,7 +767,8 @@ public AccessToken refreshAccessToken() throws IOException { assertEquals(SA_CLIENT_EMAIL, credentialInfo.get("Principal")); } - @Test void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo() + @Test + void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( @@ -758,7 +793,8 @@ public AccessToken refreshAccessToken() throws IOException { assertNull(credentialInfo.get("Principal")); } - @Test void getDefaultCredentials_wellKnownFile_userCredential_correctCredentialInfo() + @Test + void getDefaultCredentials_wellKnownFile_userCredential_correctCredentialInfo() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = @@ -784,7 +820,8 @@ public AccessToken refreshAccessToken() throws IOException { assertNull(credentialInfo.get("Principal")); } - @Test void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correctCredentialInfo() + @Test + void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correctCredentialInfo() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -803,7 +840,8 @@ public AccessToken refreshAccessToken() throws IOException { assertNull(credentialInfo.get("Principal")); } - @Test void getDefaultCredentials_computeEngineCredentials_customMDSUrl_correctCredentialInfo() + @Test + void getDefaultCredentials_computeEngineCredentials_customMDSUrl_correctCredentialInfo() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java index 95ccf5295..4a5027194 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java @@ -39,7 +39,8 @@ import org.junit.jupiter.api.Test; final class DefaultPKCEProviderTest { - @Test void testPkceExpected() throws NoSuchAlgorithmException { + @Test + void testPkceExpected() throws NoSuchAlgorithmException { PKCEProvider pkce = new DefaultPKCEProvider(); byte[] bytes = pkce.getCodeVerifier().getBytes(); @@ -55,7 +56,8 @@ final class DefaultPKCEProviderTest { assertEquals(pkce.getCodeChallengeMethod(), expectedCodeChallengeMethod); } - @Test void testNoBase64Padding() throws NoSuchAlgorithmException { + @Test + void testNoBase64Padding() throws NoSuchAlgorithmException { PKCEProvider pkce = new DefaultPKCEProvider(); assertFalse(pkce.getCodeChallenge().endsWith("=")); assertFalse(pkce.getCodeChallenge().contains("=")); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index e50460d84..2319ba37c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -82,7 +82,8 @@ public HttpTransport create() { } } - @Test void refreshAccessToken() throws IOException { + @Test + void refreshAccessToken() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -112,7 +113,8 @@ public HttpTransport create() { assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, GOOGLE_DEFAULT_UNIVERSE)); } - @Test void refreshAccessToken_withCustomUniverseDomain() throws IOException { + @Test + void refreshAccessToken_withCustomUniverseDomain() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); String universeDomain = "foobar"; GoogleCredentials sourceCredentials = @@ -145,7 +147,8 @@ public HttpTransport create() { assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain)); } - @Test void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { + @Test + void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { // STS only returns expires_in if the source access token belongs to a service account. // For other source credential types, we can copy the source credentials expiration as // the generated downscoped token will always have the same expiration time as the source @@ -172,7 +175,8 @@ public HttpTransport create() { sourceCredentials.getAccessToken().getExpirationTime(), accessToken.getExpirationTime()); } - @Test void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { + @Test + void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -193,7 +197,8 @@ public HttpTransport create() { } } - @Test void builder_noSourceCredential_throws() { + @Test + void builder_noSourceCredential_throws() { try { DownscopedCredentials.newBuilder() .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) @@ -205,7 +210,8 @@ public HttpTransport create() { } } - @Test void builder_noCredentialAccessBoundary_throws() throws IOException { + @Test + void builder_noCredentialAccessBoundary_throws() throws IOException { try { DownscopedCredentials.newBuilder() .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) @@ -217,7 +223,8 @@ public HttpTransport create() { } } - @Test void builder_noTransport_defaults() throws IOException { + @Test + void builder_noTransport_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = @@ -233,7 +240,8 @@ public HttpTransport create() { assertEquals(OAuth2Utils.HTTP_TRANSPORT_FACTORY, credentials.getTransportFactory()); } - @Test void builder_noUniverseDomain_defaults() throws IOException { + @Test + void builder_noUniverseDomain_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = @@ -251,7 +259,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void builder_universeDomainMismatch_throws() throws IOException { + @Test + void builder_universeDomainMismatch_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); @@ -270,7 +279,8 @@ public HttpTransport create() { } } - @Test void builder_sourceUniverseDomainUnavailable_throws() throws IOException { + @Test + void builder_sourceUniverseDomainUnavailable_throws() throws IOException { GoogleCredentials sourceCredentials = new MockSourceCredentialWithoutUniverseDomain(); try { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java index 86af78f0e..3a745f92c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java @@ -53,7 +53,8 @@ class ExecutableResponseTest { private static final int EXECUTABLE_SUPPORTED_MAX_VERSION = 1; private static final int EXPIRATION_DURATION = 3600; - @Test void constructor_successOidcResponse() throws IOException { + @Test + void constructor_successOidcResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildOidcResponse()); assertTrue(response.isSuccessful()); @@ -65,7 +66,8 @@ class ExecutableResponseTest { Instant.now().getEpochSecond() + EXPIRATION_DURATION, (long) response.getExpirationTime()); } - @Test void constructor_successOidcResponseMissingExpirationTimeField_notExpired() + @Test + void constructor_successOidcResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("expiration_time"); @@ -81,7 +83,8 @@ class ExecutableResponseTest { assertNull(response.getExpirationTime()); } - @Test void constructor_successSamlResponse() throws IOException { + @Test + void constructor_successSamlResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildSamlResponse()); assertTrue(response.isSuccessful()); @@ -93,7 +96,8 @@ class ExecutableResponseTest { Instant.now().getEpochSecond() + EXPIRATION_DURATION, (long) response.getExpirationTime()); } - @Test void constructor_successSamlResponseMissingExpirationTimeField_notExpired() + @Test + void constructor_successSamlResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildSamlResponse(); jsonResponse.remove("expiration_time"); @@ -109,7 +113,8 @@ class ExecutableResponseTest { assertNull(response.getExpirationTime()); } - @Test void constructor_validErrorResponse() throws IOException { + @Test + void constructor_validErrorResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildErrorResponse()); assertFalse(response.isSuccessful()); @@ -123,7 +128,8 @@ class ExecutableResponseTest { assertEquals("Caller not authorized.", response.getErrorMessage()); } - @Test void constructor_errorResponseMissingCode_throws() throws IOException { + @Test + void constructor_errorResponseMissingCode_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; @@ -141,7 +147,8 @@ class ExecutableResponseTest { } } - @Test void constructor_errorResponseMissingMessage_throws() throws IOException { + @Test + void constructor_errorResponseMissingMessage_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; @@ -160,7 +167,8 @@ class ExecutableResponseTest { } } - @Test void constructor_successResponseMissingVersionField_throws() throws IOException { + @Test + void constructor_successResponseMissingVersionField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("version"); @@ -175,7 +183,8 @@ class ExecutableResponseTest { } } - @Test void constructor_successResponseMissingSuccessField_throws() throws Exception { + @Test + void constructor_successResponseMissingSuccessField_throws() throws Exception { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("success"); @@ -190,7 +199,8 @@ class ExecutableResponseTest { } } - @Test void constructor_successResponseMissingTokenTypeField_throws() throws IOException { + @Test + void constructor_successResponseMissingTokenTypeField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("token_type"); @@ -205,7 +215,8 @@ class ExecutableResponseTest { } } - @Test void constructor_samlResponseMissingSubjectToken_throws() throws IOException { + @Test + void constructor_samlResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildSamlResponse(); Object[] values = new Object[] {null, ""}; @@ -224,7 +235,8 @@ class ExecutableResponseTest { } } - @Test void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { + @Test + void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); Object[] values = new Object[] {null, ""}; @@ -243,7 +255,8 @@ class ExecutableResponseTest { } } - @Test void isExpired() throws IOException { + @Test + void isExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); BigDecimal[] values = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java index b3549b6e0..a489d5294 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java @@ -130,7 +130,8 @@ public HttpTransport create() { transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); } - @Test void builder_allFields() throws IOException { + @Test + void builder_allFields() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -157,7 +158,8 @@ public HttpTransport create() { assertEquals(UNIVERSE_DOMAIN, credentials.getUniverseDomain()); } - @Test void builder_minimumRequiredFieldsForRefresh() { + @Test + void builder_minimumRequiredFieldsForRefresh() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -177,7 +179,8 @@ public HttpTransport create() { assertNull(credentials.getQuotaProjectId()); } - @Test void builder_accessTokenOnly() { + @Test + void builder_accessTokenOnly() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAccessToken(AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build()) @@ -194,7 +197,8 @@ public HttpTransport create() { assertNull(credentials.getQuotaProjectId()); } - @Test void builder_credentialConstructor() { + @Test + void builder_credentialConstructor() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -219,7 +223,8 @@ public HttpTransport create() { assertEquals(QUOTA_PROJECT, otherCredentials.getQuotaProjectId()); } - @Test void builder_accessTokenWithMissingRefreshFields() { + @Test + void builder_accessTokenWithMissingRefreshFields() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAccessToken(AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build()) @@ -239,7 +244,8 @@ public HttpTransport create() { assertNull(credentials.getQuotaProjectId()); } - @Test void builder_accessAndRefreshTokenNull_throws() { + @Test + void builder_accessAndRefreshTokenNull_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder().build(); fail("Should not be able to continue without exception."); @@ -252,7 +258,8 @@ public HttpTransport create() { } } - @Test void builder_missingTokenUrl_throws() { + @Test + void builder_missingTokenUrl_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -269,7 +276,8 @@ public HttpTransport create() { } } - @Test void builder_missingClientId_throws() { + @Test + void builder_missingClientId_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -286,7 +294,8 @@ public HttpTransport create() { } } - @Test void builder_missingClientSecret_throws() { + @Test + void builder_missingClientSecret_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -303,7 +312,8 @@ public HttpTransport create() { } } - @Test void builder_missingUniverseDomain_defaults() throws IOException { + @Test + void builder_missingUniverseDomain_defaults() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -329,7 +339,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void toBuilder_allFields() { + @Test + void toBuilder_allFields() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -349,7 +360,8 @@ public HttpTransport create() { assertEquals(credentials, secondCredentials); } - @Test void toBuilder_missingUniverseDomain_defaults() throws IOException { + @Test + void toBuilder_missingUniverseDomain_defaults() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -369,7 +381,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, secondCredentials.getUniverseDomain()); } - @Test void fromJson_allFields() throws IOException { + @Test + void fromJson_allFields() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson( buildJsonCredentials(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -385,7 +398,8 @@ public HttpTransport create() { assertEquals(UNIVERSE_DOMAIN, credentials.getUniverseDomain()); } - @Test void fromJson_minimumRequiredFieldsForRefresh() throws IOException { + @Test + void fromJson_minimumRequiredFieldsForRefresh() throws IOException { GenericJson json = new GenericJson(); json.put("client_id", CLIENT_ID); json.put("client_secret", CLIENT_SECRET); @@ -406,7 +420,8 @@ public HttpTransport create() { assertNull(credentials.getQuotaProjectId()); } - @Test void fromJson_accessTokenOnly_notSupported() throws IOException { + @Test + void fromJson_accessTokenOnly_notSupported() throws IOException { GenericJson json = new GenericJson(); json.put("access_token", ACCESS_TOKEN); @@ -422,7 +437,8 @@ public HttpTransport create() { } } - @Test void fromJson_missingRefreshToken_throws() throws IOException { + @Test + void fromJson_missingRefreshToken_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("refresh_token"); @@ -437,7 +453,8 @@ public HttpTransport create() { } } - @Test void fromJson_missingTokenUrl_throws() throws IOException { + @Test + void fromJson_missingTokenUrl_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("token_url"); @@ -452,7 +469,8 @@ public HttpTransport create() { } } - @Test void fromJson_missingClientId_throws() throws IOException { + @Test + void fromJson_missingClientId_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_id"); @@ -467,7 +485,8 @@ public HttpTransport create() { } } - @Test void fromJson_missingClientSecret_throws() throws IOException { + @Test + void fromJson_missingClientSecret_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_secret"); @@ -482,7 +501,8 @@ public HttpTransport create() { } } - @Test void fromJson_missingUniverseDomain_defaults() throws IOException { + @Test + void fromJson_missingUniverseDomain_defaults() throws IOException { GenericJson json = buildJsonCredentials(); json.remove("universe_domain"); @@ -500,7 +520,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_allFields() throws IOException { + @Test + void fromStream_allFields() throws IOException { GenericJson json = buildJsonCredentials(); ExternalAccountAuthorizedUserCredentials credentials = @@ -516,7 +537,8 @@ public HttpTransport create() { assertEquals(QUOTA_PROJECT, credentials.getQuotaProjectId()); } - @Test void fromStream_minimumRequiredFieldsForRefresh() throws IOException { + @Test + void fromStream_minimumRequiredFieldsForRefresh() throws IOException { GenericJson json = new GenericJson(); json.put( "type", GoogleCredentialsInfo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_CREDENTIALS.getFileType()); @@ -539,7 +561,8 @@ public HttpTransport create() { assertNull(credentials.getQuotaProjectId()); } - @Test void fromStream_accessTokenOnly_notSupported() throws IOException { + @Test + void fromStream_accessTokenOnly_notSupported() throws IOException { GenericJson json = new GenericJson(); json.put("access_token", ACCESS_TOKEN); json.put( @@ -556,7 +579,8 @@ public HttpTransport create() { } } - @Test void fromStream_missingRefreshToken_throws() throws IOException { + @Test + void fromStream_missingRefreshToken_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("refresh_token"); @@ -571,7 +595,8 @@ public HttpTransport create() { } } - @Test void fromStream_missingTokenUrl_throws() throws IOException { + @Test + void fromStream_missingTokenUrl_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("token_url"); @@ -586,7 +611,8 @@ public HttpTransport create() { } } - @Test void fromStream_missingClientId_throws() throws IOException { + @Test + void fromStream_missingClientId_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_id"); @@ -601,7 +627,8 @@ public HttpTransport create() { } } - @Test void fromStream_missingClientSecret_throws() throws IOException { + @Test + void fromStream_missingClientSecret_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_secret"); @@ -616,7 +643,8 @@ public HttpTransport create() { } } - @Test void fromStream_missingUniverseDomain_defaults() throws IOException { + @Test + void fromStream_missingUniverseDomain_defaults() throws IOException { GenericJson json = buildJsonCredentials(); json.remove("universe_domain"); @@ -634,7 +662,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_invalidInputStream_throws() throws IOException { + @Test + void fromStream_invalidInputStream_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.put("audience", new HashMap<>()); @@ -645,7 +674,8 @@ public HttpTransport create() { } } - @Test void createScoped_noChange() { + @Test + void createScoped_noChange() { ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setTokenUrl(TOKEN_URL) @@ -658,7 +688,8 @@ public HttpTransport create() { externalAccountAuthorizedUserCredentials.createScoped(SCOPES)); } - @Test void createScopedRequired_false() { + @Test + void createScopedRequired_false() { ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setTokenUrl(TOKEN_URL) @@ -669,7 +700,8 @@ public HttpTransport create() { assertFalse(externalAccountAuthorizedUserCredentials.createScopedRequired()); } - @Test void getRequestMetadata() throws IOException { + @Test + void getRequestMetadata() throws IOException { GoogleCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -679,7 +711,8 @@ public HttpTransport create() { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test void getRequestMetadata_withQuotaProjectId() throws IOException { + @Test + void getRequestMetadata_withQuotaProjectId() throws IOException { GoogleCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -693,7 +726,8 @@ public HttpTransport create() { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test void getRequestMetadata_withAccessToken() throws IOException { + @Test + void getRequestMetadata_withAccessToken() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setHttpTransportFactory(transportFactory) @@ -705,7 +739,8 @@ public HttpTransport create() { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void refreshAccessToken() throws IOException { + @Test + void refreshAccessToken() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -715,7 +750,8 @@ public HttpTransport create() { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test void refreshAccessToken_withRefreshTokenRotation() throws IOException { + @Test + void refreshAccessToken_withRefreshTokenRotation() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -730,7 +766,8 @@ public HttpTransport create() { validateAuthHeader(transportFactory.transport.getRequest()); } - @Test void refreshAccessToken_genericAuthError_throws() throws IOException { + @Test + void refreshAccessToken_genericAuthError_throws() throws IOException { transportFactory.transport.addResponseErrorSequence( TestUtils.buildHttpResponseException( "invalid_request", "Invalid request.", /* errorUri= */ null)); @@ -771,7 +808,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertThrows(IllegalStateException.class, () -> credentials.refreshAccessToken()); } - @Test void hashCode_sameCredentials() { + @Test + void hashCode_sameCredentials() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -803,7 +841,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void hashCode_differentCredentials() { + @Test + void hashCode_differentCredentials() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -834,7 +873,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void hashCode_differentCredentialsWithCredentialsFile() throws IOException { + @Test + void hashCode_differentCredentialsWithCredentialsFile() throws IOException { // Optional fields that can be specified in the credentials file. List fields = Arrays.asList("audience", "revoke_url", "quota_project_id"); @@ -855,7 +895,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { } } - @Test void equals_differentCredentials() throws IOException { + @Test + void equals_differentCredentials() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -873,7 +914,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials, userCredentials); } - @Test void equals_differentAudience() { + @Test + void equals_differentAudience() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -896,7 +938,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentClientId() { + @Test + void equals_differentClientId() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -919,7 +962,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentClientSecret() { + @Test + void equals_differentClientSecret() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -942,7 +986,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentRefreshToken() { + @Test + void equals_differentRefreshToken() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -965,7 +1010,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentTokenUrl() { + @Test + void equals_differentTokenUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -988,7 +1034,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentTokenInfoUrl() { + @Test + void equals_differentTokenInfoUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1011,7 +1058,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentRevokeUrl() { + @Test + void equals_differentRevokeUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1034,7 +1082,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentAccessToken() { + @Test + void equals_differentAccessToken() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1057,7 +1106,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentQuotaProjectId() { + @Test + void equals_differentQuotaProjectId() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1080,7 +1130,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentTransportFactory() { + @Test + void equals_differentTransportFactory() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1103,7 +1154,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void equals_differentUniverseDomain() { + @Test + void equals_differentUniverseDomain() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1127,7 +1179,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertNotEquals(credentials.hashCode(), secondCredentials.hashCode()); } - @Test void toString_expectedFormat() { + @Test + void toString_expectedFormat() { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, new Date()); ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() @@ -1165,7 +1218,8 @@ void refreshAccessToken_missingRefreshFields_throws() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java index ce7affc88..6e38a84cc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -90,7 +90,8 @@ public HttpTransport create() { transportFactory = new MockExternalAccountCredentialsTransportFactory(); } - @Test void fromStream_identityPoolCredentials() throws IOException { + @Test + void fromStream_identityPoolCredentials() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); ExternalAccountCredentials credential = @@ -99,7 +100,8 @@ public HttpTransport create() { assertTrue(credential instanceof IdentityPoolCredentials); } - @Test void fromStream_awsCredentials() throws IOException { + @Test + void fromStream_awsCredentials() throws IOException { GenericJson json = buildJsonAwsCredential(); ExternalAccountCredentials credential = @@ -108,7 +110,8 @@ public HttpTransport create() { assertTrue(credential instanceof AwsCredentials); } - @Test void fromStream_pluggableAuthCredentials() throws IOException { + @Test + void fromStream_pluggableAuthCredentials() throws IOException { GenericJson json = buildJsonPluggableAuthCredential(); ExternalAccountCredentials credential = @@ -117,7 +120,8 @@ public HttpTransport create() { assertTrue(credential instanceof PluggableAuthCredentials); } - @Test void fromStream_invalidStream_throws() throws IOException { + @Test + void fromStream_invalidStream_throws() throws IOException { GenericJson json = buildJsonAwsCredential(); json.put("audience", new HashMap<>()); @@ -130,7 +134,8 @@ public HttpTransport create() { } } - @Test void fromStream_nullTransport_throws() throws IOException { + @Test + void fromStream_nullTransport_throws() throws IOException { try { ExternalAccountCredentials.fromStream( new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); @@ -140,7 +145,8 @@ public HttpTransport create() { } } - @Test void fromStream_nullOptionalField() throws IOException { + @Test + void fromStream_nullOptionalField() throws IOException { ExternalAccountCredentials credentials = ExternalAccountCredentials.fromStream( new ByteArrayInputStream( @@ -157,7 +163,8 @@ public HttpTransport create() { assertNull(credentials.getServiceAccountImpersonationUrl()); } - @Test void fromStream_nullStream_throws() throws IOException { + @Test + void fromStream_nullStream_throws() throws IOException { try { ExternalAccountCredentials.fromStream( /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -167,7 +174,8 @@ public HttpTransport create() { } } - @Test void fromStream_invalidWorkloadAudience_throws() throws IOException { + @Test + void fromStream_invalidWorkloadAudience_throws() throws IOException { try { GenericJson json = buildJsonIdentityPoolWorkforceCredential(); json.put("audience", "invalidAudience"); @@ -179,7 +187,8 @@ public HttpTransport create() { } } - @Test void fromJson_identityPoolCredentialsWorkload() throws IOException { + @Test + void fromJson_identityPoolCredentialsWorkload() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -195,7 +204,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_identityPoolCredentialsWorkforce() throws IOException { + @Test + void fromJson_identityPoolCredentialsWorkforce() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -212,7 +222,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() + @Test + void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set( @@ -234,7 +245,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOException { + @Test + void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set("universe_domain", "universeDomain"); @@ -253,7 +265,8 @@ public HttpTransport create() { assertEquals("universeDomain", credential.getUniverseDomain()); } - @Test void fromJson_awsCredentials() throws IOException { + @Test + void fromJson_awsCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonAwsCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -267,7 +280,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() throws IOException { + @Test + void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson awsCredentialJson = buildJsonAwsCredential(); awsCredentialJson.set( "service_account_impersonation", buildServiceAccountImpersonationOptions(2800)); @@ -285,7 +299,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_awsCredentialsWithUniverseDomain() throws IOException { + @Test + void fromJson_awsCredentialsWithUniverseDomain() throws IOException { GenericJson awsCredentialJson = buildJsonAwsCredential(); awsCredentialJson.set("universe_domain", "universeDomain"); @@ -301,7 +316,8 @@ public HttpTransport create() { assertNotNull(credential.getCredentialSource()); } - @Test void fromJson_pluggableAuthCredentials() throws IOException { + @Test + void fromJson_pluggableAuthCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -321,7 +337,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { + @Test + void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -374,7 +391,8 @@ void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() throws IOExcept assertEquals(GOOGLE_DEFAULT_UNIVERSE, credential.getUniverseDomain()); } - @Test void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOptions() + @Test + void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson pluggableAuthCredentialJson = buildJsonPluggableAuthCredential(); pluggableAuthCredentialJson.set( @@ -431,7 +449,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals("universeDomain", credential.getUniverseDomain()); } - @Test void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOException { + @Test + void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOException { GenericJson pluggableAuthCredentialJson = buildJsonPluggableAuthCredential(); pluggableAuthCredentialJson.set("universe_domain", "universeDomain"); @@ -454,7 +473,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertNull(source.getOutputFilePath()); } - @Test void fromJson_nullJson_throws() throws IOException { + @Test + void fromJson_nullJson_throws() throws IOException { try { ExternalAccountCredentials.fromJson(/* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); fail("Exception should be thrown."); @@ -463,7 +483,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void fromJson_nullTransport_throws() throws IOException { + @Test + void fromJson_nullTransport_throws() throws IOException { try { ExternalAccountCredentials.fromJson( new HashMap(), /* transportFactory= */ null); @@ -473,7 +494,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void fromJson_invalidWorkforceAudiences_throws() throws IOException { + @Test + void fromJson_invalidWorkforceAudiences_throws() throws IOException { List invalidAudiences = Arrays.asList( "//iam.googleapis.com/locations/global/workloadIdentityPools/pool/providers/provider", @@ -501,7 +523,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void constructor_builder() throws IOException { + @Test + void constructor_builder() throws IOException { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -540,7 +563,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertNotNull(credentials.getCredentialSource()); } - @Test void constructor_builder_defaultTokenUrl() { + @Test + void constructor_builder_defaultTokenUrl() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -556,7 +580,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(STS_URL, credentials.getTokenUrl()); } - @Test void constructor_builder_defaultTokenUrlwithUniverseDomain() { + @Test + void constructor_builder_defaultTokenUrlwithUniverseDomain() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -573,7 +598,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals("https://sts.testdomain.org/v1/token", credentials.getTokenUrl()); } - @Test void constructor_builder_subjectTokenTypeEnum() { + @Test + void constructor_builder_subjectTokenTypeEnum() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -590,7 +616,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(SubjectTokenTypes.SAML2.value, credentials.getSubjectTokenType()); } - @Test void constructor_builder_invalidTokenUrl() { + @Test + void constructor_builder_invalidTokenUrl() { try { ExternalAccountCredentials.Builder builder = TestExternalAccountCredentials.newBuilder() @@ -606,7 +633,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void constructor_builder_invalidServiceAccountImpersonationUrl() { + @Test + void constructor_builder_invalidServiceAccountImpersonationUrl() { try { ExternalAccountCredentials.Builder builder = TestExternalAccountCredentials.newBuilder() @@ -623,7 +651,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void constructor_builderWithInvalidWorkforceAudiences_throws() { + @Test + void constructor_builderWithInvalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -657,7 +686,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { + @Test + void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); // No exception should be thrown. @@ -671,7 +701,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { .build(); } - @Test void constructor_builder_invalidTokenLifetime_throws() { + @Test + void constructor_builder_invalidTokenLifetime_throws() { Map invalidOptionsMap = new HashMap(); invalidOptionsMap.put("token_lifetime_seconds", "thisIsAString"); @@ -702,7 +733,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void constructor_builder_stringTokenLifetime() { + @Test + void constructor_builder_stringTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", "2800"); @@ -728,7 +760,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(2800, credentials.getServiceAccountImpersonationOptions().getLifetime()); } - @Test void constructor_builder_bigDecimalTokenLifetime() { + @Test + void constructor_builder_bigDecimalTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", new BigDecimal("2800")); @@ -754,7 +787,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(2800, credentials.getServiceAccountImpersonationOptions().getLifetime()); } - @Test void constructor_builder_integerTokenLifetime() { + @Test + void constructor_builder_integerTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", Integer.valueOf(2800)); @@ -780,7 +814,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(2800, credentials.getServiceAccountImpersonationOptions().getLifetime()); } - @Test void constructor_builder_lowTokenLifetime_throws() { + @Test + void constructor_builder_lowTokenLifetime_throws() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", 599); @@ -809,7 +844,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void constructor_builder_highTokenLifetime_throws() { + @Test + void constructor_builder_highTokenLifetime_throws() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", 43201); @@ -838,7 +874,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void exchangeExternalCredentialForAccessToken() throws IOException { + @Test + void exchangeExternalCredentialForAccessToken() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -861,7 +898,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { validateMetricsHeader(headers, "file", false, false); } - @Test void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { + @Test + void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -885,7 +923,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(internalOptions.toString(), query.get("options")); } - @Test void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() + @Test + void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() throws IOException { ExternalAccountCredentials identityPoolCredential = ExternalAccountCredentials.fromJson( @@ -918,7 +957,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void + @Test + void exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() throws IOException { ExternalAccountCredentials credential = @@ -944,7 +984,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals(internalOptions.toString(), query.get("options")); } - @Test void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() + @Test + void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -980,7 +1021,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { validateMetricsHeader(headers, "url", true, false); } - @Test void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOptions() + @Test + void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOptions() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -1015,7 +1057,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals("2800s", query.get("lifetime")); } - @Test void exchangeExternalCredentialForAccessToken_throws() throws IOException { + @Test + void exchangeExternalCredentialForAccessToken_throws() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -1038,7 +1081,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredentialsThrows() + @Test + void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredentialsThrows() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); json.put("service_account_impersonation_url", "https://iamcredentials.googleapis.com"); @@ -1058,7 +1102,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void getRequestMetadata_withQuotaProjectId() throws IOException { + @Test + void getRequestMetadata_withQuotaProjectId() throws IOException { TestExternalAccountCredentials testCredentials = (TestExternalAccountCredentials) TestExternalAccountCredentials.newBuilder() @@ -1076,7 +1121,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { assertEquals("quotaProjectId", requestMetadata.get("x-goog-user-project").get(0)); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { Map impersonationOpts = new HashMap() { { @@ -1109,7 +1155,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { deserializedCredentials.toBuilder().getHttpTransportFactory().getClass()); } - @Test void validateTokenUrl_validUrls() { + @Test + void validateTokenUrl_validUrls() { List validUrls = Arrays.asList( "https://sts.googleapis.com", @@ -1130,7 +1177,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void validateTokenUrl_invalidUrls() { + @Test + void validateTokenUrl_invalidUrls() { List invalidUrls = Arrays.asList( "sts.googleapis.com", @@ -1152,7 +1200,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void validateServiceAccountImpersonationUrls_validUrls() { + @Test + void validateServiceAccountImpersonationUrls_validUrls() { List validUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -1174,7 +1223,8 @@ void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOException { } } - @Test void validateServiceAccountImpersonationUrls_invalidUrls() { + @Test + void validateServiceAccountImpersonationUrls_invalidUrls() { List invalidUrls = Arrays.asList( "iamcredentials.googleapis.com", diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java index 07268e219..67b9c17ba 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java @@ -37,7 +37,8 @@ class ExternalAccountSupplierContextTest { - @Test void constructor_builder() { + @Test + void constructor_builder() { String expectedAudience = "//iam.googleapis.com/locations/global/workloadPools/pool/providers/provider"; String expectedTokenType = SubjectTokenTypes.JWT.value; @@ -51,7 +52,8 @@ class ExternalAccountSupplierContextTest { assertEquals(expectedTokenType, context.getSubjectTokenType()); } - @Test void constructor_builder_subjectTokenEnum() { + @Test + void constructor_builder_subjectTokenEnum() { String expectedAudience = "//iam.googleapis.com/locations/global/workloadPools/pool/providers/provider"; SubjectTokenTypes expectedTokenType = SubjectTokenTypes.JWT; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java index 1695c16d0..11632d211 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java @@ -84,7 +84,8 @@ class GdchCredentialsTest extends BaseSerializationTest { private static final URI API_AUDIENCE = URI.create("https://gdch-api-audience"); private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); - @Test void fromJSON_getProjectId() throws IOException { + @Test + void fromJSON_getProjectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -99,7 +100,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(PROJECT_ID, credentials.getProjectId()); } - @Test void fromJSON_getServiceIdentityName() throws IOException { + @Test + void fromJSON_getServiceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -114,7 +116,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(SERVICE_IDENTITY_NAME, credentials.getServiceIdentityName()); } - @Test void fromJSON_getCaCertPath() throws IOException { + @Test + void fromJSON_getCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -129,7 +132,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(CA_CERT_PATH, credentials.getCaCertPath()); } - @Test void fromJSON_getTokenServerUri() throws IOException { + @Test + void fromJSON_getTokenServerUri() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -144,7 +148,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(TOKEN_SERVER_URI, credentials.getTokenServerUri()); } - @Test void fromJSON_nullFormatVersion() throws IOException { + @Test + void fromJSON_nullFormatVersion() throws IOException { GenericJson json = writeGdchServiceAccountJson( null, @@ -169,7 +174,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_nullProjectId() throws IOException { + @Test + void fromJSON_nullProjectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -194,7 +200,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_nullPrivateKeyId() throws IOException { + @Test + void fromJSON_nullPrivateKeyId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -219,7 +226,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_nullPrivateKey() throws IOException { + @Test + void fromJSON_nullPrivateKey() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -244,7 +252,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_nullServiceIdentityName() throws IOException { + @Test + void fromJSON_nullServiceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -269,7 +278,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_nullCaCertPath() throws IOException { + @Test + void fromJSON_nullCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -283,7 +293,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertNull(credentials.getCaCertPath()); } - @Test void fromJSON_nullTokenServerUri() throws IOException { + @Test + void fromJSON_nullTokenServerUri() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -308,7 +319,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_invalidFormatVersion() throws IOException { + @Test + void fromJSON_invalidFormatVersion() throws IOException { GenericJson json = writeGdchServiceAccountJson( "100", @@ -329,7 +341,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_invalidCaCertPath() throws IOException { + @Test + void fromJSON_invalidCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -348,7 +361,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void fromJSON_emptyCaCertPath() throws IOException { + @Test + void fromJSON_emptyCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -362,7 +376,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals("", credentials.getCaCertPath()); } - @Test void fromJSON_transportFactoryForGdch() throws IOException { + @Test + void fromJSON_transportFactoryForGdch() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -378,7 +393,8 @@ class GdchCredentialsTest extends BaseSerializationTest { credentials.getTransportFactory().getClass()); } - @Test void fromJSON_hasAccessToken() throws IOException { + @Test + void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = writeGdchServiceAccountJson( @@ -398,7 +414,8 @@ class GdchCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void createWithGdchAudience_correct() throws IOException { + @Test + void createWithGdchAudience_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -425,7 +442,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(API_AUDIENCE, gdchWithAudience.getApiAudience()); } - @Test void createWithGdchAudience_nullApiAudience() throws IOException { + @Test + void createWithGdchAudience_nullApiAudience() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -445,7 +463,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void createAssertion_correct() throws IOException { + @Test + void createAssertion_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -472,7 +491,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); } - @Test void refreshAccessToken_correct() throws IOException { + @Test + void refreshAccessToken_correct() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = @@ -508,7 +528,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); } - @Test void refreshAccessToken_nullApiAudience() throws IOException { + @Test + void refreshAccessToken_nullApiAudience() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = @@ -539,7 +560,8 @@ class GdchCredentialsTest extends BaseSerializationTest { } } - @Test void getIssuerSubjectValue_correct() throws IOException { + @Test + void getIssuerSubjectValue_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -557,7 +579,8 @@ class GdchCredentialsTest extends BaseSerializationTest { GdchCredentials.getIssuerSubjectValue(PROJECT_ID, SERVICE_IDENTITY_NAME)); } - @Test void equals_same() throws IOException { + @Test + void equals_same() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -587,7 +610,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_projectId() throws IOException { + @Test + void equals_false_projectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -617,7 +641,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_keyId() throws IOException { + @Test + void equals_false_keyId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -647,7 +672,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_serviceIdentityName() throws IOException { + @Test + void equals_false_serviceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -677,7 +703,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_caCertPath() throws IOException { + @Test + void equals_false_caCertPath() throws IOException { File tmpDirectory = Files.createTempDirectory("tmpDirectory").toFile(); File testCaCertFile = File.createTempFile("testCert", ".pem", tmpDirectory); GenericJson json = @@ -711,7 +738,8 @@ class GdchCredentialsTest extends BaseSerializationTest { testCaCertFile.delete(); } - @Test void equals_false_tokenServer() throws IOException { + @Test + void equals_false_tokenServer() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -741,7 +769,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_apiAudience() throws IOException { + @Test + void equals_false_apiAudience() throws IOException { URI otherApiAudience = URI.create("https://foo1.com/bar"); GenericJson json = @@ -772,7 +801,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -798,7 +828,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -826,7 +857,8 @@ class GdchCredentialsTest extends BaseSerializationTest { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize_correct() throws IOException, ClassNotFoundException { + @Test + void serialize_correct() throws IOException, ClassNotFoundException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = writeGdchServiceAccountJson( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java index ec367d54b..56a6c9667 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java @@ -38,7 +38,8 @@ class GoogleAuthUtilsTest { - @Test void getWellKnownCredentialsPath_correct() { + @Test + void getWellKnownCredentialsPath_correct() { DefaultCredentialsProvider provider = new DefaultCredentialsProviderTest.TestDefaultCredentialsProvider(); // since the TestDefaultCredentialsProvider properties and envs are not set, diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java index c00810718..dfe51741f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -99,7 +99,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com"; private static final String TPC_UNIVERSE = "foo.bar"; - @Test void getApplicationDefault_nullTransport_throws() throws IOException { + @Test + void getApplicationDefault_nullTransport_throws() throws IOException { try { GoogleCredentials.getApplicationDefault(null); fail(); @@ -108,7 +109,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { } } - @Test void fromStream_unknownType_throws() throws IOException { + @Test + void fromStream_unknownType_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); GenericJson json = new GenericJson(); json.put("type", "unsupported_credential"); @@ -126,7 +128,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { } } - @Test void fromStream_nullTransport_throws() throws IOException { + @Test + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { GoogleCredentials.fromStream(stream, null); @@ -136,7 +139,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { } } - @Test void fromStream_noType_throws() throws IOException { + @Test + void fromStream_noType_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); GenericJson json = ServiceAccountCredentialsTest.writeServiceAccountJson( @@ -152,12 +156,14 @@ class GoogleCredentialsTest extends BaseSerializationTest { } } - @Test void fromStream_nullStream_throws() { + @Test + void fromStream_nullStream_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); assertThrows(NullPointerException.class, () -> GoogleCredentials.parseJsonInputStream(null)); } - @Test void fromStream_serviceAccount_noUniverse_providesToken() throws IOException { + @Test + void fromStream_serviceAccount_noUniverse_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -179,7 +185,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void fromStream_serviceAccount_Universe_noToken() throws IOException { + @Test + void fromStream_serviceAccount_Universe_noToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -197,7 +204,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertNotNull(((ServiceAccountCredentials) credentials).getSelfSignedJwtCredentialsWithScope()); } - @Test void fromStream_serviceAccountNoClientId_throws() throws IOException { + @Test + void fromStream_serviceAccountNoClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -205,7 +213,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "client_id"); } - @Test void fromStream_serviceAccountNoClientEmail_throws() throws IOException { + @Test + void fromStream_serviceAccountNoClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -213,7 +222,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "client_email"); } - @Test void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { + @Test + void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -221,7 +231,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "private_key"); } - @Test void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { + @Test + void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -229,7 +240,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "private_key_id"); } - @Test void fromStream_gdchServiceAccount_correct() throws IOException { + @Test + void fromStream_gdchServiceAccount_correct() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( @@ -264,7 +276,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertNotNull(((GdchCredentials) credentials).getApiAudience()); } - @Test void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( null, @@ -278,7 +291,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(gdchServiceAccountStream, "format_version"); } - @Test void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -292,7 +306,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(gdchServiceAccountStream, "project"); } - @Test void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -306,7 +321,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(gdchServiceAccountStream, "private_key_id"); } - @Test void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -320,7 +336,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(gdchServiceAccountStream, "private_key"); } - @Test void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -334,7 +351,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(gdchServiceAccountStream, "name"); } - @Test void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -348,7 +366,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(gdchServiceAccountStream, "token_uri"); } - @Test void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( "100", @@ -364,7 +383,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { String.format("Only format version %s is supported", GDCH_SA_FORMAT_VERSION)); } - @Test void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOException { + @Test + void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -380,7 +400,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { String.format("Error reading certificate file from CA cert path")); } - @Test void fromStream_userCredentials_providesToken() throws IOException { + @Test + void fromStream_userCredentials_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(USER_CLIENT_ID, USER_CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -395,7 +416,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void fromStream_userCredentials_defaultUniverse() throws IOException { + @Test + void fromStream_userCredentials_defaultUniverse() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -406,21 +428,24 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_userCredentials_NoClientId_throws() throws IOException { + @Test + void fromStream_userCredentials_NoClientId_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(null, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_id"); } - @Test void fromStream_userCredentials_NoClientSecret_throws() throws IOException { + @Test + void fromStream_userCredentials_NoClientSecret_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(USER_CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_secret"); } - @Test void fromStream_userCredentials_NoRefreshToken_throws() throws IOException { + @Test + void fromStream_userCredentials_NoRefreshToken_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, null, QUOTA_PROJECT); @@ -428,7 +453,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { testFromStreamException(userStream, "refresh_token"); } - @Test void fromStream_identityPoolCredentials_providesToken() throws IOException { + @Test + void fromStream_identityPoolCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -447,7 +473,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test void fromStream_identityPoolCredentials_defaultUniverse() throws IOException { + @Test + void fromStream_identityPoolCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -463,7 +490,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_awsCredentials_providesToken() throws IOException { + @Test + void fromStream_awsCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -482,7 +510,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test void fromStream_awsCredentials_defaultUniverse() throws IOException { + @Test + void fromStream_awsCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -498,7 +527,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_pluggableAuthCredentials_providesToken() throws IOException { + @Test + void fromStream_pluggableAuthCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -520,7 +550,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { + @Test + void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -532,7 +563,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_externalAccountAuthorizedUserCredentials_providesToken() + @Test + void fromStream_externalAccountAuthorizedUserCredentials_providesToken() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); @@ -546,7 +578,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { TestUtils.assertContainsBearerToken(metadata, transportFactory.transport.getAccessToken()); } - @Test void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() + @Test + void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); @@ -560,7 +593,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { + @Test + void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -601,7 +635,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(ImpersonatedCredentialsTest.QUOTA_PROJECT_ID, headerValues.get(0)); } - @Test void fromStream_Impersonation_defaultUniverse() throws IOException { + @Test + void fromStream_Impersonation_defaultUniverse() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -625,7 +660,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { + @Test + void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -663,7 +699,8 @@ class GoogleCredentialsTest extends BaseSerializationTest { assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test void createScoped_overloadCallsImplementation() { + @Test + void createScoped_overloadCallsImplementation() { final AtomicReference> called = new AtomicReference<>(); final GoogleCredentials expectedScopedCredentials = new GoogleCredentials(); @@ -682,7 +719,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(ImmutableList.of("foo", "bar"), called.get()); } - @Test void create_withoutUniverse() throws IOException { + @Test + void create_withoutUniverse() throws IOException { AccessToken token = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); GoogleCredentials credentials = GoogleCredentials.create(token); @@ -690,7 +728,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(false, credentials.isExplicitUniverseDomain()); } - @Test void create_withUniverse() throws IOException { + @Test + void create_withUniverse() throws IOException { AccessToken token = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); GoogleCredentials credentials = GoogleCredentials.create("some-universe", token); @@ -698,7 +737,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(true, credentials.isExplicitUniverseDomain()); } - @Test void buildWithQuotaProject() { + @Test + void buildWithQuotaProject() { final GoogleCredentials googleCredentials = new GoogleCredentials.Builder().setQuotaProjectId("old_quota").build(); GoogleCredentials withUpdatedQuota = googleCredentials.createWithQuotaProject("new_quota"); @@ -713,7 +753,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(null, sameCredentials.getQuotaProjectId()); } - @Test void buildWithUniverseDomain() throws IOException { + @Test + void buildWithUniverseDomain() throws IOException { final GoogleCredentials original = new GoogleCredentials.Builder().setUniverseDomain("universe1").build(); GoogleCredentials updated = original.toBuilder().setUniverseDomain("universe2").build(); @@ -732,7 +773,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(false, withNull.isExplicitUniverseDomain()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { final GoogleCredentials testCredentials = new GoogleCredentials.Builder().build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(testCredentials); assertEquals(testCredentials, deserializedCredentials); @@ -741,7 +783,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { String expectedToString = String.format( "GoogleCredentials{quotaProjectId=%s, universeDomain=%s, isExplicitUniverseDomain=%s}", @@ -751,7 +794,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { GoogleCredentials credentials = GoogleCredentials.newBuilder().setUniverseDomain("some-domain").build(); GoogleCredentials otherCredentials = @@ -759,7 +803,8 @@ public GoogleCredentials createScoped(Collection scopes) { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { GoogleCredentials credentials = GoogleCredentials.newBuilder().setUniverseDomain("some-domain").build(); GoogleCredentials otherCredentials = @@ -779,7 +824,8 @@ private static void testFromStreamException(InputStream stream, String expectedM } } - @Test void getCredentialInfo_serviceAccountCredentials() throws IOException { + @Test + void getCredentialInfo_serviceAccountCredentials() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -792,7 +838,8 @@ private static void testFromStreamException(InputStream stream, String expectedM assertEquals(SA_CLIENT_EMAIL, credentialInfo.get("Principal")); } - @Test void getCredentialInfo_userCredentials() throws IOException { + @Test + void getCredentialInfo_userCredentials() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, null); @@ -805,7 +852,8 @@ private static void testFromStreamException(InputStream stream, String expectedM assertNull(credentialInfo.get("Principal")); } - @Test void getCredentialInfo_gdchCredentials() throws IOException { + @Test + void getCredentialInfo_gdchCredentials() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -824,7 +872,8 @@ private static void testFromStreamException(InputStream stream, String expectedM assertNull(credentialInfo.get("Principal")); } - @Test void getCredentialInfo_externalAccount() throws IOException { + @Test + void getCredentialInfo_externalAccount() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -843,7 +892,8 @@ private static void testFromStreamException(InputStream stream, String expectedM assertNull(credentialInfo.get("Principal")); } - @Test void getCredentialInfo_externalAccountUserCredentials() throws IOException { + @Test + void getCredentialInfo_externalAccountUserCredentials() throws IOException { InputStream externalAccountUserCredentialStream = ExternalAccountAuthorizedUserCredentialsTest.writeExternalAccountUserCredentialStream( USER_CLIENT_ID, @@ -862,7 +912,8 @@ private static void testFromStreamException(InputStream stream, String expectedM assertNull(credentialInfo.get("Principal")); } - @Test void getCredentialInfo_impersonatedServiceAccount() throws IOException { + @Test + void getCredentialInfo_impersonatedServiceAccount() throws IOException { InputStream impersonationCredentialsStream = ImpersonatedCredentialsTest.writeImpersonationCredentialsStream( ImpersonatedCredentialsTest.IMPERSONATION_OVERRIDE_URL, diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java index 1949b1608..c1d285fac 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java @@ -91,7 +91,8 @@ final class ITDownscopingTest { * downscoped token. 2. Validating that we do not have permission to retrieve a different object * in the same bucket. */ - @Test void downscoping_serviceAccountSourceWithRefresh() throws IOException { + @Test + void downscoping_serviceAccountSourceWithRefresh() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index 90ba2e972..019dcb076 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java @@ -90,7 +90,8 @@ final class ITWorkloadIdentityFederationTest { * exchanged for a GCP access token via GCP STS endpoint and then to impersonate the original * service account key. Retrieves the OIDC token from a file. */ - @Test void identityPoolCredentials() throws IOException { + @Test + void identityPoolCredentials() throws IOException { IdentityPoolCredentials identityPoolCredentials = (IdentityPoolCredentials) ExternalAccountCredentials.fromJson( @@ -108,7 +109,8 @@ final class ITWorkloadIdentityFederationTest { * exchanged for a GCP access token via GCP STS endpoint and then to impersonate the original * service account key. */ - @Test void awsCredentials() throws Exception { + @Test + void awsCredentials() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -158,7 +160,8 @@ final class ITWorkloadIdentityFederationTest { * the external subject token to be exchanged for a GCP access token via GCP STS endpoint and then * to impersonate the original service account key. */ - @Test void awsCredentials_withProgrammaticAuth() throws Exception { + @Test + void awsCredentials_withProgrammaticAuth() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -208,7 +211,8 @@ final class ITWorkloadIdentityFederationTest { * exchanged for a GCP access token via GCP STS endpoint and then to impersonate the original * service account key. Runs an executable to get the OIDC token. */ - @Test void pluggableAuthCredentials() throws IOException { + @Test + void pluggableAuthCredentials() throws IOException { PluggableAuthCredentials pluggableAuthCredentials = (PluggableAuthCredentials) ExternalAccountCredentials.fromJson( @@ -221,7 +225,8 @@ final class ITWorkloadIdentityFederationTest { * Sets the service account impersonation object in configuration JSON with a non-default value * for token_lifetime_seconds and validates that the lifetime is used for the access token. */ - @Test void identityPoolCredentials_withServiceAccountImpersonationOptions() throws IOException { + @Test + void identityPoolCredentials_withServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialConfig = buildIdentityPoolCredentialConfig(); Map map = new HashMap(); map.put("token_lifetime_seconds", 2800); @@ -247,7 +252,8 @@ final class ITWorkloadIdentityFederationTest { * service account key. Retrieves the OIDC token from a Supplier that returns the subject token * when get() is called. */ - @Test void identityPoolCredentials_withProgrammaticAuth() throws IOException { + @Test + void identityPoolCredentials_withProgrammaticAuth() throws IOException { IdentityPoolSubjectTokenSupplier tokenSupplier = (ExternalAccountSupplierContext context) -> { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index c8338fcc2..fabb5de5d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -60,7 +60,8 @@ class IamUtilsTest { Mockito.when(credentials.getUniverseDomain()).thenReturn("googleapis.com"); } - @Test void sign_success_noRetry() { + @Test + void sign_success_noRetry() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -85,7 +86,8 @@ class IamUtilsTest { // The SignBlob RPC will retry up to three times before it gives up. This test will return two // 5xx status codes before returning a success. This test covers the cases where the number of // retry attempts is below the configured retry attempt count bounds (3 attempts). - @Test void sign_retryTwoTimes_success() { + @Test + void sign_retryTwoTimes_success() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -118,7 +120,8 @@ class IamUtilsTest { // The rpc will retry up to three times before it gives up. This test will enqueue three failed // status codes + messages before returning a success. After the third retry attempt, the request // will try one last time and the result will be reported back to the user. - @Test void sign_retryThreeTimes_success() { + @Test + void sign_retryThreeTimes_success() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -154,7 +157,8 @@ class IamUtilsTest { // The rpc will retry up to three times before it gives up. This test will enqueue four failed // status codes + messages before returning a success. After the third retry attempt, the request // will try one last time and the result will be reported back to the user. - @Test void sign_retryThreeTimes_exception() { + @Test + void sign_retryThreeTimes_exception() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -198,7 +202,8 @@ class IamUtilsTest { assertEquals(4, transportFactory.getTransport().getNumRequests()); } - @Test void sign_4xxError_noRetry_exception() { + @Test + void sign_4xxError_noRetry_exception() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java index 170c0d9ce..856877fce 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java @@ -39,7 +39,8 @@ class IdTokenCredentialsTest extends BaseSerializationTest { - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -64,7 +65,8 @@ class IdTokenCredentialsTest extends BaseSerializationTest { assertEquals(tokenCredential.hashCode(), otherCredential.hashCode()); } - @Test void toString_equals() throws IOException { + @Test + void toString_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -89,7 +91,8 @@ class IdTokenCredentialsTest extends BaseSerializationTest { assertEquals(tokenCredential.toString(), otherCredential.toString()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java index 00cf72b3b..cccc570a1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java @@ -50,27 +50,31 @@ class IdTokenTest extends BaseSerializationTest { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2NjAxNjMxNjAsImV4cCI6MTY5MTY5OTE2MCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6ImFibTHag3M0x20ifQ.foo"; private static final Date EXPIRATION_DATE = new Date((long) 1565391138 * 1000); - @Test void constructor() throws IOException { + @Test + void constructor() throws IOException { IdToken idToken = IdToken.create(TOKEN_1); assertEquals(TOKEN_1, idToken.getTokenValue()); assertEquals(EXPIRATION_DATE, idToken.getExpirationTime()); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertTrue(accessToken.equals(otherAccessToken)); assertTrue(otherAccessToken.equals(accessToken)); } - @Test void equals_false_token() throws IOException { + @Test + void equals_false_token() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_2); assertFalse(accessToken.equals(otherAccessToken)); assertFalse(otherAccessToken.equals(accessToken)); } - @Test void toString_test() throws IOException { + @Test + void toString_test() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); String expectedToString = String.format( @@ -79,13 +83,15 @@ class IdTokenTest extends BaseSerializationTest { assertEquals(expectedToString, accessToken.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); @@ -93,7 +99,8 @@ class IdTokenTest extends BaseSerializationTest { assertEquals(accessToken.toString(), deserializedAccessToken.toString()); } - @Test void token_with_0x20() throws IOException { + @Test + void token_with_0x20() throws IOException { IdToken accessToken = IdToken.create(TOKEN_WITH_0x20); assertEquals(TOKEN_WITH_0x20, accessToken.getTokenValue()); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java index 465324e65..f05c33f6d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java @@ -45,7 +45,8 @@ class IdentityPoolCredentialsSourceTest { - @Test void constructor_certificateConfig() { + @Test + void constructor_certificateConfig() { Map certificateMap = new HashMap<>(); certificateMap.put("certificate_config_location", "/path/to/certificate"); @@ -63,7 +64,8 @@ class IdentityPoolCredentialsSourceTest { credentialSource.getCertificateConfig().getCertificateConfigLocation()); } - @Test void constructor_certificateConfig_useDefault() { + @Test + void constructor_certificateConfig_useDefault() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); @@ -78,7 +80,8 @@ class IdentityPoolCredentialsSourceTest { assertTrue(credentialSource.getCertificateConfig().useDefaultCertificateConfig()); } - @Test void constructor_certificateConfig_missingRequiredFields_throws() { + @Test + void constructor_certificateConfig_missingRequiredFields_throws() { Map certificateMap = new HashMap<>(); // Missing both use_default_certificate_config and certificate_config_location. certificateMap.put("trust_chain_path", "path/to/trust/chain"); @@ -95,7 +98,8 @@ class IdentityPoolCredentialsSourceTest { exception.getMessage()); } - @Test void constructor_certificateConfig_bothFieldsSet_throws() { + @Test + void constructor_certificateConfig_bothFieldsSet_throws() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); certificateMap.put("certificate_config_location", "/path/to/certificate"); @@ -113,7 +117,8 @@ class IdentityPoolCredentialsSourceTest { exception.getMessage()); } - @Test void constructor_certificateConfig_trustChainPath() { + @Test + void constructor_certificateConfig_trustChainPath() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); certificateMap.put("trust_chain_path", "path/to/trust/chain"); @@ -130,7 +135,8 @@ class IdentityPoolCredentialsSourceTest { "path/to/trust/chain", credentialSource.getCertificateConfig().getTrustChainPath()); } - @Test void constructor_certificateConfig_invalidType_throws() { + @Test + void constructor_certificateConfig_invalidType_throws() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", "invalid-type"); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java index 7993a9c58..2ad2d3dd8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java @@ -79,7 +79,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { private static final IdentityPoolSubjectTokenSupplier testProvider = (ExternalAccountSupplierContext context) -> "testSubjectToken"; - @Test void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + @Test + void createdScoped_clonedCredentialWithAddedScopes() throws IOException { IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder(createBaseFileSourcedCredentials()) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -109,7 +110,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals("universeDomain", newCredentials.getUniverseDomain()); } - @Test void retrieveSubjectToken_fileSourced() throws IOException { + @Test + void retrieveSubjectToken_fileSourced() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -134,7 +136,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(credential, subjectToken); } - @Test void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { + @Test + void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -174,7 +177,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals("subjectToken", subjectToken); } - @Test void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { + @Test + void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -194,7 +198,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void retrieveSubjectToken_noFile_throws() { + @Test + void retrieveSubjectToken_noFile_throws() { Map credentialSourceMap = new HashMap<>(); String path = "badPath"; credentialSourceMap.put("file", path); @@ -216,7 +221,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void retrieveSubjectToken_urlSourced() throws IOException { + @Test + void retrieveSubjectToken_urlSourced() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -232,7 +238,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(transportFactory.transport.getSubjectToken(), subjectToken); } - @Test void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { + @Test + void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -256,7 +263,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(transportFactory.transport.getSubjectToken(), subjectToken); } - @Test void retrieveSubjectToken_urlSourcedCredential_throws() { + @Test + void retrieveSubjectToken_urlSourcedCredential_throws() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -281,7 +289,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void retrieveSubjectToken_provider() throws IOException { + @Test + void retrieveSubjectToken_provider() throws IOException { ExternalAccountSupplierContext emptyContext = ExternalAccountSupplierContext.newBuilder().setAudience("").setSubjectTokenType("").build(); IdentityPoolCredentials credentials = @@ -295,7 +304,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(testProvider.getSubjectToken(emptyContext), subjectToken); } - @Test void retrieveSubjectToken_providerThrowsError() throws IOException { + @Test + void retrieveSubjectToken_providerThrowsError() throws IOException { IOException testException = new IOException("test"); IdentityPoolSubjectTokenSupplier errorProvider = @@ -316,7 +326,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void retrieveSubjectToken_supplierPassesContext() throws IOException { + @Test + void retrieveSubjectToken_supplierPassesContext() throws IOException { ExternalAccountSupplierContext expectedContext = ExternalAccountSupplierContext.newBuilder() .setAudience(createBaseFileSourcedCredentials().getAudience()) @@ -338,7 +349,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { credentials.retrieveSubjectToken(); } - @Test void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -365,7 +377,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "url", false, false); } - @Test void refreshAccessToken_internalOptionsSet() throws IOException { + @Test + void refreshAccessToken_internalOptionsSet() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -397,7 +410,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(expectedInternalOptions.toString(), query.get("options")); } - @Test void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -427,7 +441,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "url", true, false); } - @Test void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + @Test + void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -467,7 +482,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "url", true, true); } - @Test void refreshAccessToken_Provider() throws IOException { + @Test + void refreshAccessToken_Provider() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -493,7 +509,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "programmatic", false, false); } - @Test void refreshAccessToken_providerWithServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_providerWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -522,7 +539,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "programmatic", true, false); } - @Test void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -556,7 +574,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(expectedInternalOptions.toString(), query.get("options")); } - @Test void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() + @Test + void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -591,7 +610,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals("2800s", query.get("lifetime")); } - @Test void identityPoolCredentialSource_validFormats() { + @Test + void identityPoolCredentialSource_validFormats() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -633,7 +653,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void identityPoolCredentialSource_caseInsensitive() { + @Test + void identityPoolCredentialSource_caseInsensitive() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -675,7 +696,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void identityPoolCredentialSource_invalidSourceType() { + @Test + void identityPoolCredentialSource_invalidSourceType() { try { new IdentityPoolCredentialSource(new HashMap<>()); fail("Should not be able to continue without exception."); @@ -686,7 +708,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void identityPoolCredentialSource_invalidFormatType() { + @Test + void identityPoolCredentialSource_invalidFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -702,7 +725,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void identityPoolCredentialSource_nullFormatType() { + @Test + void identityPoolCredentialSource_nullFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -718,7 +742,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void identityPoolCredentialSource_subjectTokenFieldNameUnset() { + @Test + void identityPoolCredentialSource_subjectTokenFieldNameUnset() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -736,7 +761,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void builder_allFields() throws IOException { + @Test + void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentialSource credentialSource = createFileCredentialSource(); @@ -771,7 +797,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals("universeDomain", credentials.getUniverseDomain()); } - @Test void builder_subjectTokenSupplier() { + @Test + void builder_subjectTokenSupplier() { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -792,7 +819,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(testProvider, credentials.getIdentityPoolSubjectTokenSupplier()); } - @Test void builder_invalidWorkforceAudiences_throws() { + @Test + void builder_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -826,7 +854,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void builder_emptyWorkforceUserProjectWithWorkforceAudience() { + @Test + void builder_emptyWorkforceUserProjectWithWorkforceAudience() { // No exception should be thrown. IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder() @@ -844,7 +873,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertTrue(credentials.isWorkforcePoolConfiguration()); } - @Test void builder_supplierAndCredSourceThrows() { + @Test + void builder_supplierAndCredSourceThrows() { try { IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder() @@ -863,7 +893,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void builder_noSupplierOrCredSourceThrows() throws IOException { + @Test + void builder_noSupplierOrCredSourceThrows() throws IOException { try { IdentityPoolCredentials credentials = @@ -880,7 +911,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { } } - @Test void builder_missingUniverseDomain_defaults() throws IOException { + @Test + void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentialSource credentialSource = createFileCredentialSource(); @@ -914,7 +946,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void newBuilder_allFields() throws IOException { + @Test + void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -955,7 +988,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(credentials.getUniverseDomain(), newBuilderCreds.getUniverseDomain()); } - @Test void newBuilder_noUniverseDomain_defaults() throws IOException { + @Test + void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -995,7 +1029,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertEquals(GOOGLE_DEFAULT_UNIVERSE, newBuilderCreds.getUniverseDomain()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { IdentityPoolCredentials testCredentials = IdentityPoolCredentials.newBuilder(createBaseFileSourcedCredentials()) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -1012,7 +1047,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { assertSame(Clock.SYSTEM, deserializedCredentials.clock); } - @Test void build_withCertificateSourceAndCustomX509Provider_success() + @Test + void build_withCertificateSourceAndCustomX509Provider_success() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Create an empty KeyStore and a spy on a custom X509Provider. KeyStore keyStore = KeyStore.getInstance("JKS"); @@ -1056,7 +1092,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { verify(x509Provider).getCertificatePath(); } - @Test void build_withDefaultCertificate_throwsOnTransportInitFailure() { + @Test + void build_withDefaultCertificate_throwsOnTransportInitFailure() { // Setup credential source to use default certificate config. Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", false); @@ -1081,7 +1118,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { exception.getMessage()); } - @Test void build_withCustomProvider_throwsOnGetKeyStore() + @Test + void build_withCustomProvider_throwsOnGetKeyStore() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Simulate a scenario where the X509Provider fails to load the KeyStore, typically due to an // IOException when reading the certificate or private key files. @@ -1110,7 +1148,8 @@ class IdentityPoolCredentialsTest extends BaseSerializationTest { exception.getMessage()); } - @Test void build_withCustomProvider_throwsOnGetCertificatePath() + @Test + void build_withCustomProvider_throwsOnGetCertificatePath() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Simulate a scenario where the X509Provider cannot access or read the certificate // configuration file needed to determine the certificate path, resulting in an IOException. diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java index f8a593652..264d4e493 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java @@ -294,7 +294,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertFalse(targetCredentials.createScopedRequired()); } - @Test void createScoped() { + @Test + void createScoped() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -316,7 +317,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(Arrays.asList("scope1", "scope2"), scoped_credentials.getScopes()); } - @Test void createScoped_existingAccessTokenInvalidated() throws IOException { + @Test + void createScoped_existingAccessTokenInvalidated() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -340,7 +342,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertNull(scoped_credentials.getAccessToken()); } - @Test void createScopedWithImmutableScopes() { + @Test + void createScopedWithImmutableScopes() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -362,7 +365,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(Arrays.asList("scope1", "scope2"), scoped_credentials.getScopes()); } - @Test void createScopedWithIamEndpointOverride() { + @Test + void createScopedWithIamEndpointOverride() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -380,7 +384,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { targetCredentials.getIamEndpointOverride(), scoped_credentials.getIamEndpointOverride()); } - @Test void refreshAccessToken_unauthorized() throws IOException { + @Test + void refreshAccessToken_unauthorized() throws IOException { String expectedMessage = "The caller does not have permission"; mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory @@ -549,7 +554,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(NONGDU_IMPERSONATION_URL, transportFactory.getTransport().getRequest().getUrl()); } - @Test void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { + @Test + void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -630,7 +636,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(ACCESS_TOKEN, targetCredentials.refreshAccessToken().getTokenValue()); } - @Test void refreshAccessToken_GMT_dateParsedCorrectly() + @Test + void refreshAccessToken_GMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -656,7 +663,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { == targetCredentials.refreshAccessToken().getExpirationTimeMillis()); } - @Test void refreshAccessToken_nonGMT_dateParsedCorrectly() + @Test + void refreshAccessToken_nonGMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -682,7 +690,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { == targetCredentials.refreshAccessToken().getExpirationTimeMillis()); } - @Test void refreshAccessToken_invalidDate() throws IllegalStateException { + @Test + void refreshAccessToken_invalidDate() throws IllegalStateException { String expectedMessage = "Unparseable date"; mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken("foo"); @@ -705,7 +714,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { } } - @Test void getAccount_sameAs() { + @Test + void getAccount_sameAs() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -721,7 +731,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(IMPERSONATED_CLIENT_EMAIL, targetCredentials.getAccount()); } - @Test void sign_sameAs() { + @Test + void sign_sameAs() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -743,7 +754,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertArrayEquals(expectedSignature, targetCredentials.sign(expectedSignature)); } - @Test void sign_requestIncludesDelegates() throws IOException { + @Test + void sign_requestIncludesDelegates() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -774,7 +786,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(delegates, body.get("delegates")); } - @Test void sign_usesSourceCredentials() { + @Test + void sign_usesSourceCredentials() { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date expiry = c.getTime(); @@ -807,7 +820,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals("Bearer source-token", request.getFirstHeaderValue("Authorization")); } - @Test void sign_accessDenied_throws() { + @Test + void sign_accessDenied_throws() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -839,7 +853,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { } } - @Test void sign_serverError_throws() { + @Test + void sign_serverError_throws() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -871,7 +886,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { } } - @Test void sign_sameAs_nonGDU() { + @Test + void sign_sameAs_nonGDU() { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory("test.com"); @@ -902,7 +918,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertArrayEquals(expectedSignature, targetCredentials.sign(expectedSignature)); } - @Test void sign_universeDomainException() throws IOException { + @Test + void sign_universeDomainException() throws IOException { // Currently, no credentials allowed as source credentials throws exception for // getUniverseDomain(), mock this behavior for test only. ServiceAccountCredentials // should not throw for getUniverseDomain() calls. @@ -927,7 +944,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals("Failed to sign: Error obtaining universe domain", exception.getMessage()); } - @Test void idTokenWithAudience_sameAs() throws IOException { + @Test + void idTokenWithAudience_sameAs() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -958,7 +976,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test void idTokenWithAudience_withEmail() throws IOException { + @Test + void idTokenWithAudience_withEmail() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -994,7 +1013,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(requestHeader.containsKey("authorization")); } - @Test void idTokenWithAudience_sameAs_nonGDU() throws IOException { + @Test + void idTokenWithAudience_sameAs_nonGDU() throws IOException { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory("test.com"); transportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -1032,7 +1052,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { (String) tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test void idToken_withServerError() { + @Test + void idToken_withServerError() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1065,7 +1086,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { } } - @Test void idToken_withOtherError() { + @Test + void idToken_withOtherError() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1098,7 +1120,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { } } - @Test void universeDomain_defaultUniverse() throws IOException { + @Test + void universeDomain_defaultUniverse() throws IOException { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -1111,7 +1134,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(impersonatedCredentials.isDefaultUniverseDomain()); } - @Test void universeDomain_getFromSourceCredentials() throws IOException { + @Test + void universeDomain_getFromSourceCredentials() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); ImpersonatedCredentials impersonatedCredentials = @@ -1129,7 +1153,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertFalse(impersonatedCredentials.isExplicitUniverseDomain()); } - @Test void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws IOException { + @Test + void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); IllegalStateException illegalStateException = @@ -1151,7 +1176,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { illegalStateException.getMessage()); } - @Test void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOException { + @Test + void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); ImpersonatedCredentials impersonatedCredentials = @@ -1171,14 +1197,16 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(impersonatedCredentials.isExplicitUniverseDomain()); } - @Test void scopes_userConfigured() { + @Test + void scopes_userConfigured() { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.newBuilder().setScopes(IMMUTABLE_SCOPES_LIST).build(); assertArrayEquals( IMMUTABLE_SCOPES_LIST.toArray(), impersonatedCredentials.getScopes().toArray()); } - @Test void scopes_fromJson() throws IOException { + @Test + void scopes_fromJson() throws IOException { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.fromJson( buildImpersonationCredentialsJson( @@ -1191,7 +1219,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { // Tests that user configured scopes has precedence over the one in the json. // From the ADC flow, the json is parsed and the credential is returned back // to the user - @Test void scopes_userConfiguredAndFromJson() throws IOException { + @Test + void scopes_userConfiguredAndFromJson() throws IOException { List userConfiguredScopes = ImmutableList.of("nonsense-scopes"); ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.fromJson( @@ -1204,7 +1233,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { userConfiguredScopes.toArray(), newImpersonatedCredentials.getScopes().toArray()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1230,7 +1260,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java index 169f83885..cc21cb3fa 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java @@ -43,7 +43,8 @@ /** Tests for {@link InternalAwsSecurityCredentialsSupplier}. */ class InternalAwsSecurityCredentialsSupplierTest { - @Test void shouldUseMetadataServer_withRequiredEnvironmentVariables() { + @Test + void shouldUseMetadataServer_withRequiredEnvironmentVariables() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -65,7 +66,8 @@ class InternalAwsSecurityCredentialsSupplierTest { } } - @Test void shouldUseMetadataServer_missingRegion() { + @Test + void shouldUseMetadataServer_missingRegion() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -81,7 +83,8 @@ class InternalAwsSecurityCredentialsSupplierTest { assertTrue(supplier.shouldUseMetadataServer()); } - @Test void shouldUseMetadataServer_missingAwsAccessKeyId() { + @Test + void shouldUseMetadataServer_missingAwsAccessKeyId() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -102,7 +105,8 @@ class InternalAwsSecurityCredentialsSupplierTest { } } - @Test void shouldUseMetadataServer_missingAwsSecretAccessKey() { + @Test + void shouldUseMetadataServer_missingAwsSecretAccessKey() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -123,7 +127,8 @@ class InternalAwsSecurityCredentialsSupplierTest { } } - @Test void shouldUseMetadataServer_missingAwsSecurityCreds() { + @Test + void shouldUseMetadataServer_missingAwsSecurityCreds() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -143,7 +148,8 @@ class InternalAwsSecurityCredentialsSupplierTest { } } - @Test void shouldUseMetadataServer_noEnvironmentVars() { + @Test + void shouldUseMetadataServer_noEnvironmentVars() { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java index 1bba79bef..433cec68e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java @@ -41,7 +41,8 @@ class JwtClaimsTest { - @Test void testMergeOverwritesFields() { + @Test + void testMergeOverwritesFields() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -61,7 +62,8 @@ class JwtClaimsTest { assertEquals("subject-2", merged.getSubject()); } - @Test void testMergeDefaultValues() { + @Test + void testMergeDefaultValues() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -76,7 +78,8 @@ class JwtClaimsTest { assertEquals("subject-1", merged.getSubject()); } - @Test void testMergeNull() { + @Test + void testMergeNull() { JwtClaims claims1 = JwtClaims.newBuilder().build(); JwtClaims claims2 = JwtClaims.newBuilder().build(); JwtClaims merged = claims1.merge(claims2); @@ -88,7 +91,8 @@ class JwtClaimsTest { assertTrue(merged.getAdditionalClaims().isEmpty()); } - @Test void testEquals() { + @Test + void testEquals() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -105,13 +109,15 @@ class JwtClaimsTest { assertEquals(claims1, claims2); } - @Test void testAdditionalClaimsDefaults() { + @Test + void testAdditionalClaimsDefaults() { JwtClaims claims = JwtClaims.newBuilder().build(); assertNotNull(claims.getAdditionalClaims()); assertTrue(claims.getAdditionalClaims().isEmpty()); } - @Test void testMergeAdditionalClaims() { + @Test + void testMergeAdditionalClaims() { JwtClaims claims1 = JwtClaims.newBuilder().setAdditionalClaims(Collections.singletonMap("foo", "bar")).build(); JwtClaims claims2 = @@ -130,7 +136,8 @@ class JwtClaimsTest { assertEquals("qwer", mergedAdditionalClaims.get("asdf")); } - @Test void testIsComplete() { + @Test + 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 6c654f659..480bf48d8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java @@ -75,7 +75,8 @@ static PrivateKey getPrivateKey() { } } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -96,7 +97,8 @@ static PrivateKey getPrivateKey() { assertSame(deserializedCredentials.getClock(), Clock.SYSTEM); } - @Test void builder_requiresPrivateKey() { + @Test + void builder_requiresPrivateKey() { try { JwtClaims claims = JwtClaims.newBuilder() @@ -111,7 +113,8 @@ static PrivateKey getPrivateKey() { } } - @Test void builder_requiresClaims() { + @Test + void builder_requiresClaims() { try { JwtCredentials.newBuilder() .setPrivateKeyId(PRIVATE_KEY_ID) @@ -123,7 +126,8 @@ static PrivateKey getPrivateKey() { } } - @Test void builder_requiresCompleteClaims() { + @Test + void builder_requiresCompleteClaims() { try { JwtClaims claims = JwtClaims.newBuilder().build(); JwtCredentials.newBuilder() @@ -137,7 +141,8 @@ static PrivateKey getPrivateKey() { } } - @Test void jwtWithClaims_overwritesClaims() throws IOException { + @Test + void jwtWithClaims_overwritesClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -161,7 +166,8 @@ static PrivateKey getPrivateKey() { verifyJwtAccess(metadata, "some-audience2", "some-issuer2", "some-subject2", PRIVATE_KEY_ID); } - @Test void jwtWithClaims_defaultsClaims() throws IOException { + @Test + void jwtWithClaims_defaultsClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -180,7 +186,8 @@ static PrivateKey getPrivateKey() { verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", PRIVATE_KEY_ID); } - @Test void getRequestMetadata_hasJwtAccess() throws IOException { + @Test + void getRequestMetadata_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -198,7 +205,8 @@ static PrivateKey getPrivateKey() { verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", PRIVATE_KEY_ID); } - @Test void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { + @Test + void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -223,7 +231,8 @@ static PrivateKey getPrivateKey() { Collections.singletonMap("foo", "bar")); } - @Test void privateKeyIdNull() throws IOException { + @Test + void privateKeyIdNull() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -241,7 +250,8 @@ static PrivateKey getPrivateKey() { verifyJwtAccess(metadata, "some-audience", "some-issuer", "some-subject", null); } - @Test void privateKeyIdNotSpecified() throws IOException { + @Test + void privateKeyIdNotSpecified() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java index a3aba5ad1..8138cbaa9 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java @@ -90,7 +90,8 @@ private TestAppender setupTestLogger(Class clazz) { LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); } - @Test void userCredentials_getRequestMetadata_fromRefreshToken_hasAccessToken() + @Test + void userCredentials_getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(UserCredentials.class); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -152,7 +153,8 @@ boolean isValidJson(String jsonString) { } } - @Test void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws IOException { + @Test + void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(ServiceAccountCredentials.class); GoogleCredentials credentials = ServiceAccountCredentialsTest.createDefaultBuilderWithToken(ACCESS_TOKEN) @@ -197,7 +199,8 @@ boolean isValidJson(String jsonString) { testAppender.stop(); } - @Test void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() + @Test + void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { TestAppender testAppender = setupTestLogger(ServiceAccountCredentials.class); String nonGDU = "test.com"; @@ -307,7 +310,8 @@ boolean isValidJson(String jsonString) { testAppender.stop(); } - @Test void idTokenWithAudience_withEmail() throws IOException { + @Test + void idTokenWithAudience_withEmail() throws IOException { TestAppender testAppender = setupTestLogger(IamUtils.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); @@ -367,7 +371,8 @@ boolean isValidJson(String jsonString) { testAppender.stop(); } - @Test void sign_sameAs() throws IOException { + @Test + void sign_sameAs() throws IOException { TestAppender testAppender = setupTestLogger(IamUtils.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); @@ -423,7 +428,8 @@ boolean isValidJson(String jsonString) { testAppender.stop(); } - @Test void getRequestMetadata_hasAccessToken() throws IOException { + @Test + void getRequestMetadata_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(ComputeEngineCredentials.class); MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java index 81d0d8ad1..bb95cd4aa 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java @@ -44,7 +44,8 @@ class LoggingUtilsTest { testEnvironmentProvider = new TestEnvironmentProvider(); } - @Test void testIsLoggingEnabled_true() { + @Test + void testIsLoggingEnabled_true() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); assertTrue(LoggingUtils.isLoggingEnabled()); @@ -56,7 +57,8 @@ class LoggingUtilsTest { assertTrue(LoggingUtils.isLoggingEnabled()); } - @Test void testIsLoggingEnabled_defaultToFalse() { + @Test + void testIsLoggingEnabled_defaultToFalse() { LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); assertFalse(LoggingUtils.isLoggingEnabled()); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java index 65d0ae791..fa2db6545 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java @@ -55,12 +55,14 @@ private static void assertPatterns(String contentToTest, String patternString) { assertTrue(pattern.matcher(contentToTest).matches()); } - @Test void getLanguageAndAuthLibraryVersionsTest() { + @Test + void getLanguageAndAuthLibraryVersionsTest() { String version = MetricsUtils.getLanguageAndAuthLibraryVersions(); assertPatterns(version, VERSION_PATTERN); } - @Test void getGoogleCredentialsMetricsHeaderTest() { + @Test + void getGoogleCredentialsMetricsHeaderTest() { String metricsStringNoRequestType = MetricsUtils.getGoogleCredentialsMetricsHeader( RequestType.UNTRACKED, CredentialTypeForMetrics.USER_CREDENTIALS); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java index 7e50d9577..25ce4bf5c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java @@ -96,13 +96,15 @@ class OAuth2CredentialsTest extends BaseSerializationTest { realExecutor.shutdown(); } - @Test void constructor_storesAccessToken() { + @Test + void constructor_storesAccessToken() { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); } - @Test void constructor_overrideMargin() throws Throwable { + @Test + void constructor_overrideMargin() throws Throwable { Duration staleMargin = Duration.ofMinutes(3); Duration expirationMargin = Duration.ofMinutes(2); @@ -182,7 +184,8 @@ public AccessToken refreshAccessToken() throws IOException { lastMetadata = credentials.getRequestMetadata(); } - @Test void getAuthenticationType_returnsOAuth2() { + @Test + void getAuthenticationType_returnsOAuth2() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -192,7 +195,8 @@ public AccessToken refreshAccessToken() throws IOException { assertEquals(credentials.getAuthenticationType(), "OAuth2"); } - @Test void hasRequestMetadata_returnsTrue() { + @Test + void hasRequestMetadata_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -202,7 +206,8 @@ public AccessToken refreshAccessToken() throws IOException { assertTrue(credentials.hasRequestMetadata()); } - @Test void hasRequestMetadataOnly_returnsTrue() { + @Test + void hasRequestMetadataOnly_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -212,7 +217,8 @@ public AccessToken refreshAccessToken() throws IOException { assertTrue(credentials.hasRequestMetadata()); } - @Test void addChangeListener_notifiesOnRefresh() throws IOException { + @Test + void addChangeListener_notifiesOnRefresh() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -249,7 +255,8 @@ public AccessToken refreshAccessToken() throws IOException { assertEquals(2, listener.callCount); } - @Test void removeChangeListener_unregisters_observer() throws IOException { + @Test + void removeChangeListener_unregisters_observer() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -285,7 +292,8 @@ public AccessToken refreshAccessToken() throws IOException { assertEquals(2, listener.callCount); } - @Test void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { + @Test + void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -338,7 +346,8 @@ public AccessToken refreshAccessToken() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test void getRequestMetadata_async() throws IOException { + @Test + void getRequestMetadata_async() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -407,7 +416,8 @@ public AccessToken refreshAccessToken() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test void getRequestMetadata_async_refreshRace() + @Test + void getRequestMetadata_async_refreshRace() throws ExecutionException, InterruptedException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -465,7 +475,8 @@ public Map> call() throws Exception { assertEquals(metadata, callback.metadata); } - @Test void getRequestMetadata_temporaryToken_hasToken() throws IOException { + @Test + void getRequestMetadata_temporaryToken_hasToken() throws IOException { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); @@ -474,7 +485,8 @@ public Map> call() throws Exception { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { + @Test + void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); @@ -543,7 +555,8 @@ public AccessToken refreshAccessToken() { } } - @Test void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { + @Test + 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); @@ -611,7 +624,8 @@ public AccessToken refreshAccessToken() { } } - @Test void getRequestMetadata_singleFlightErrorSharing() { + @Test + void getRequestMetadata_singleFlightErrorSharing() { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -669,7 +683,8 @@ public Map> call() throws Exception { assertEquals(error, actualAsyncError); } - @Test void getRequestMetadata_syncErrorsIncludeCallingStackframe() { + @Test + void getRequestMetadata_syncErrorsIncludeCallingStackframe() { final OAuth2Credentials creds = new OAuth2Credentials() { @Override @@ -699,7 +714,8 @@ public AccessToken refreshAccessToken() { assertEquals(expectedStacktrace, actualStacktrace); } - @Test void refresh_refreshesToken() throws IOException { + @Test + void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -734,7 +750,8 @@ public AccessToken refreshAccessToken() { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test void refreshIfExpired_refreshesToken() throws IOException { + @Test + void refreshIfExpired_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -784,7 +801,8 @@ void refresh_temporaryToken_throws() throws IOException { assertThrows(IllegalStateException.class, () -> credentials.refresh()); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken1, null)).build(); @@ -794,7 +812,8 @@ void refresh_temporaryToken_throws() throws IOException { assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_accessToken() throws IOException { + @Test + void equals_false_accessToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = @@ -805,7 +824,8 @@ void refresh_temporaryToken_throws() throws IOException { assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken("1/MkSJoj1xsli0AccessToken_NKPY2", null); OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); @@ -819,7 +839,8 @@ void refresh_temporaryToken_throws() throws IOException { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -828,7 +849,8 @@ void refresh_temporaryToken_throws() throws IOException { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + 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 523c4d6a6..782499c24 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -51,7 +51,8 @@ class OAuth2CredentialsWithRefreshTest { private static final AccessToken ACCESS_TOKEN = new AccessToken("accessToken", new Date()); - @Test void builder() { + @Test + void builder() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -69,7 +70,8 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test void builder_withRefreshAndExpirationMargins() { + @Test + void builder_withRefreshAndExpirationMargins() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -96,7 +98,8 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test void builder_onlyRefreshMarginSet() { + @Test + void builder_onlyRefreshMarginSet() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -121,7 +124,8 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test void builder_onlyExpirationMarginSet() { + @Test + void builder_onlyExpirationMarginSet() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -145,7 +149,8 @@ public AccessToken refreshAccessToken() { assertEquals(refreshHandler, credential.getRefreshHandler()); } - @Test void builder_noAccessToken() { + @Test + void builder_noAccessToken() { OAuth2CredentialsWithRefresh.newBuilder() .setRefreshHandler( new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @@ -157,7 +162,8 @@ public AccessToken refreshAccessToken() { .build(); } - @Test void builder_noRefreshHandler_throws() { + @Test + void builder_noRefreshHandler_throws() { try { OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(); fail("Should fail as a refresh handler must be provided."); @@ -166,7 +172,8 @@ public AccessToken refreshAccessToken() { } } - @Test void builder_noExpirationTimeInAccessToken_throws() { + @Test + void builder_noExpirationTimeInAccessToken_throws() { try { OAuth2CredentialsWithRefresh.newBuilder() .setAccessToken(new AccessToken("accessToken", null)) @@ -177,7 +184,8 @@ public AccessToken refreshAccessToken() { } } - @Test void refreshAccessToken_delegateToRefreshHandler() throws IOException { + @Test + void refreshAccessToken_delegateToRefreshHandler() throws IOException { final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = OAuth2CredentialsWithRefresh.newBuilder() @@ -196,7 +204,8 @@ public AccessToken refreshAccessToken() { assertEquals(refreshedToken, accessToken); } - @Test void getRequestMetadata() throws IOException { + @Test + void getRequestMetadata() throws IOException { URI uri = URI.create("http://googleapis.com/testapi/v1/foo"); final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java index d82999c68..f1b65b3cd 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java @@ -40,7 +40,8 @@ /** Tests for {@link OAuth2Utils}. */ class OAuth2UtilsTest { - @Test void testValidCredentials() { + @Test + void testValidCredentials() { String username = "testUser"; String password = "testPassword"; String expectedHeader = "Basic dGVzdFVzZXI6dGVzdFBhc3N3b3Jk"; @@ -50,7 +51,8 @@ class OAuth2UtilsTest { assertEquals(expectedHeader, actualHeader); } - @Test void testEmptyUsername_throws() { + @Test + void testEmptyUsername_throws() { String username = ""; String password = "testPassword"; @@ -61,7 +63,8 @@ class OAuth2UtilsTest { }); } - @Test void testEmptyPassword_throws() { + @Test + void testEmptyPassword_throws() { String username = "testUser"; String password = ""; @@ -72,7 +75,8 @@ class OAuth2UtilsTest { }); } - @Test void testNullUsername_throws() { + @Test + void testNullUsername_throws() { String username = null; String password = "testPassword"; @@ -83,7 +87,8 @@ class OAuth2UtilsTest { }); } - @Test void testNullPassword_throws() { + @Test + void testNullPassword_throws() { String username = "testUser"; String password = null; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java index 3ccef3bd8..d5f0f3b89 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java @@ -45,7 +45,8 @@ final class OAuthExceptionTest { private static final String ERROR_DESCRIPTION_FORMAT = "Error code %s: %s"; private static final String BASE_MESSAGE_FORMAT = "Error code %s"; - @Test void getMessage_fullFormat() { + @Test + void getMessage_fullFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", "errorUri"); assertEquals("errorCode", e.getErrorCode()); @@ -57,7 +58,8 @@ final class OAuthExceptionTest { assertEquals(expectedMessage, e.getMessage()); } - @Test void getMessage_descriptionFormat() { + @Test + void getMessage_descriptionFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", /* errorUri= */ null); assertEquals("errorCode", e.getErrorCode()); @@ -69,7 +71,8 @@ final class OAuthExceptionTest { assertEquals(expectedMessage, e.getMessage()); } - @Test void getMessage_baseFormat() { + @Test + void getMessage_baseFormat() { OAuthException e = new OAuthException("errorCode", /* errorDescription= */ null, /* errorUri= */ null); @@ -81,7 +84,8 @@ final class OAuthExceptionTest { assertEquals(expectedMessage, e.getMessage()); } - @Test void createFromHttpResponseException() throws IOException { + @Test + void createFromHttpResponseException() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException("errorCode", "errorDescription", "errorUri")); @@ -95,7 +99,8 @@ final class OAuthExceptionTest { assertEquals(expectedMessage, e.getMessage()); } - @Test void createFromHttpResponseException_descriptionFormat() throws IOException { + @Test + void createFromHttpResponseException_descriptionFormat() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException( @@ -110,7 +115,8 @@ final class OAuthExceptionTest { assertEquals(expectedMessage, e.getMessage()); } - @Test void createFromHttpResponseException_baseFormat() throws IOException { + @Test + void createFromHttpResponseException_baseFormat() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java index 6433053c6..a830987de 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java @@ -87,7 +87,8 @@ public HttpTransport create() { } } - @Test void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { + @Test + void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { PluggableAuthCredentials credential = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -96,7 +97,8 @@ public HttpTransport create() { assertEquals(subjectToken, "pluggableAuthToken"); } - @Test void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { + @Test + void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { String command = "/path/to/executable"; String timeout = "5000"; String outputFile = "/path/to/output/file"; @@ -137,7 +139,8 @@ public HttpTransport create() { assertEquals(envMap.get("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE"), outputFile); } - @Test void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { + @Test + void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { String command = "/path/to/executable"; final ExecutableOptions[] providedOptions = {null}; @@ -174,7 +177,8 @@ public HttpTransport create() { assertNull(envMap.get("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE")); } - @Test void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -202,7 +206,8 @@ public HttpTransport create() { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "executable", false, false); } - @Test void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + @Test + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -242,7 +247,8 @@ public HttpTransport create() { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "executable", true, false); } - @Test void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + @Test + void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -287,7 +293,8 @@ public HttpTransport create() { ExternalAccountCredentialsTest.validateMetricsHeader(headers, "executable", true, true); } - @Test void pluggableAuthCredentialSource_allFields() { + @Test + void pluggableAuthCredentialSource_allFields() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -302,7 +309,8 @@ public HttpTransport create() { assertEquals(credentialSource.getOutputFilePath(), "/path/to/output/file"); } - @Test void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { + @Test + void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -314,7 +322,8 @@ public HttpTransport create() { assertNull(credentialSource.getOutputFilePath()); } - @Test void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { + @Test + void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -339,7 +348,8 @@ public HttpTransport create() { } } - @Test void pluggableAuthCredentialSource_validTimeoutProvided() { + @Test + void pluggableAuthCredentialSource_validTimeoutProvided() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -358,7 +368,8 @@ public HttpTransport create() { } } - @Test void pluggableAuthCredentialSource_missingExecutableField_throws() { + @Test + void pluggableAuthCredentialSource_missingExecutableField_throws() { try { new PluggableAuthCredentialSource(new HashMap<>()); fail("Should not be able to continue without exception."); @@ -368,7 +379,8 @@ public HttpTransport create() { } } - @Test void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { + @Test + void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -383,7 +395,8 @@ public HttpTransport create() { } } - @Test void builder_allFields() throws IOException { + @Test + void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -422,7 +435,8 @@ public HttpTransport create() { assertEquals("universeDomain", credentials.getUniverseDomain()); } - @Test void builder_missingUniverseDomain_defaults() throws IOException { + @Test + void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -460,7 +474,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void newBuilder_allFields() throws IOException { + @Test + void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -501,7 +516,8 @@ public HttpTransport create() { assertEquals(credentials.getUniverseDomain(), newBuilderCreds.getUniverseDomain()); } - @Test void newBuilder_noUniverseDomain_defaults() throws IOException { + @Test + void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -541,7 +557,8 @@ public HttpTransport create() { assertEquals(GOOGLE_DEFAULT_UNIVERSE, newBuilderCreds.getUniverseDomain()); } - @Test void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + @Test + void createdScoped_clonedCredentialWithAddedScopes() throws IOException { PluggableAuthCredentials credentials = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -573,7 +590,8 @@ public HttpTransport create() { assertEquals("universeDomain", newCredentials.getUniverseDomain()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { PluggableAuthCredentials testCredentials = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java index d5537840b..4cf42d86d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java @@ -40,7 +40,8 @@ class PluggableAuthExceptionTest { private static final String MESSAGE_FORMAT = "Error code %s: %s"; - @Test void constructor() { + @Test + void constructor() { PluggableAuthException e = new PluggableAuthException("errorCode", "errorDescription"); assertEquals("errorCode", e.getErrorCode()); assertEquals("errorDescription", e.getErrorDescription()); @@ -60,7 +61,8 @@ void constructor_nullErrorDescription_throws() { () -> new PluggableAuthException("errorCode", /* errorDescription= */ null)); } - @Test void getMessage() { + @Test + void getMessage() { PluggableAuthException e = new PluggableAuthException("errorCode", "errorDescription"); String expectedMessage = String.format("Error code %s: %s", "errorCode", "errorDescription"); assertEquals(expectedMessage, e.getMessage()); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java index 2babb0569..9ac4e40f4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java @@ -100,7 +100,8 @@ public String getOutputFilePath() { } }; - @Test void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { + @Test + void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -143,7 +144,8 @@ public String getOutputFilePath() { assertEquals(expectedMap, currentEnv); } - @Test void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { + @Test + void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -187,7 +189,8 @@ public String getOutputFilePath() { assertEquals(expectedMap, currentEnv); } - @Test void retrieveTokenFromExecutable_errorResponse_throws() + @Test + void retrieveTokenFromExecutable_errorResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -219,7 +222,8 @@ public String getOutputFilePath() { } } - @Test void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() + @Test + void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -276,7 +280,8 @@ public String getOutputFilePath() { } } - @Test void + @Test + void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFieldWithOutputFileSpecified_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -350,7 +355,8 @@ public String getOutputFilePath() { } } - @Test void + @Test + void retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -425,7 +431,8 @@ public String getOutputFilePath() { } } - @Test void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() + @Test + void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -480,7 +487,8 @@ public String getOutputFilePath() { assertEquals(ID_TOKEN, token); } - @Test void retrieveTokenFromExecutable_withInvalidOutputFile_throws() + @Test + void retrieveTokenFromExecutable_withInvalidOutputFile_throws() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -533,7 +541,8 @@ public String getOutputFilePath() { } } - @Test void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() + @Test + void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -599,7 +608,8 @@ public String getOutputFilePath() { assertEquals(ID_TOKEN, token); } - @Test void retrieveTokenFromExecutable_expiredResponse_throws() + @Test + void retrieveTokenFromExecutable_expiredResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -631,7 +641,8 @@ public String getOutputFilePath() { } } - @Test void retrieveTokenFromExecutable_invalidVersion_throws() + @Test + void retrieveTokenFromExecutable_invalidVersion_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -669,7 +680,8 @@ public String getOutputFilePath() { } } - @Test void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws IOException { + @Test + void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws IOException { // In order to use Pluggable Auth, GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES must be set to 1. // If set to 0, a runtime exception should be thrown. TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -689,7 +701,8 @@ public String getOutputFilePath() { } } - @Test void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { + @Test + void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -740,7 +753,8 @@ public String getOutputFilePath() { assertEquals(expectedMap, currentEnv); } - @Test void getExecutableResponse_samlResponse() throws IOException, InterruptedException { + @Test + void getExecutableResponse_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -793,7 +807,8 @@ public String getOutputFilePath() { verify(mockProcess, times(1)).destroy(); } - @Test void getExecutableResponse_errorResponse() throws IOException, InterruptedException { + @Test + void getExecutableResponse_errorResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -840,7 +855,8 @@ public String getOutputFilePath() { assertEquals(expectedMap, currentEnv); } - @Test void getExecutableResponse_timeoutExceeded_throws() + @Test + void getExecutableResponse_timeoutExceeded_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -870,7 +886,8 @@ public String getOutputFilePath() { verify(mockProcess, times(1)).destroy(); } - @Test void getExecutableResponse_nonZeroExitCode_throws() + @Test + void getExecutableResponse_nonZeroExitCode_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -903,7 +920,8 @@ public String getOutputFilePath() { verify(mockProcess, times(1)).destroy(); } - @Test void getExecutableResponse_processInterrupted_throws() + @Test + void getExecutableResponse_processInterrupted_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -935,7 +953,8 @@ public String getOutputFilePath() { verify(mockProcess, times(1)).destroy(); } - @Test void getExecutableResponse_invalidResponse_throws() + @Test + void getExecutableResponse_invalidResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java index e76a72557..4da447f1b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java @@ -40,7 +40,8 @@ class SecureSessionAgentConfigTest { private static final String S2A_PLAINTEXT_ADDRESS = "plaintext"; private static final String S2A_MTLS_ADDRESS = "mtls"; - @Test void createS2AConfig_success() { + @Test + void createS2AConfig_success() { SecureSessionAgentConfig config = SecureSessionAgentConfig.createBuilder() .setPlaintextAddress(S2A_PLAINTEXT_ADDRESS) @@ -50,7 +51,8 @@ class SecureSessionAgentConfigTest { assertEquals(S2A_MTLS_ADDRESS, config.getMtlsAddress()); } - @Test void createEmptyS2AConfig_success() { + @Test + void createEmptyS2AConfig_success() { SecureSessionAgentConfig config = SecureSessionAgentConfig.createBuilder().build(); assertTrue(config.getPlaintextAddress().isEmpty()); assertTrue(config.getMtlsAddress().isEmpty()); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java index 1fb2111b8..6022178d3 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java @@ -45,7 +45,8 @@ class SecureSessionAgentTest { private static final String S2A_PLAINTEXT_ADDRESS = "plaintext"; private static final String S2A_MTLS_ADDRESS = "mtls"; - @Test void getS2AAddress_validAddress() { + @Test + void getS2AAddress_validAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -64,7 +65,8 @@ class SecureSessionAgentTest { assertEquals(S2A_MTLS_ADDRESS, mtlsS2AAddress); } - @Test void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { + @Test + void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -83,7 +85,8 @@ class SecureSessionAgentTest { assertTrue(mtlsS2AAddress.isEmpty()); } - @Test void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { + @Test + void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -103,7 +106,8 @@ class SecureSessionAgentTest { assertTrue(mtlsS2AAddress.isEmpty()); } - @Test void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintextEmptyAddress() { + @Test + void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintextEmptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -122,7 +126,8 @@ class SecureSessionAgentTest { assertEquals(S2A_MTLS_ADDRESS, mtlsS2AAddress); } - @Test void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddress() { + @Test + void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 1905721d7..7bc91cfdd 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -157,7 +157,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti return createDefaultBuilderWithKey(privateKey); } - @Test void setLifetime() throws IOException { + @Test + void setLifetime() throws IOException { ServiceAccountCredentials.Builder builder = createDefaultBuilder(); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.getLifetime()); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); @@ -170,7 +171,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); } - @Test void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { + @Test + void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { try { createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(); fail( @@ -182,13 +184,15 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void createWithCustomLifetime() throws IOException { + @Test + void createWithCustomLifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); credentials = credentials.createWithCustomLifetime(4000); assertEquals(4000, credentials.getLifetime()); } - @Test void createdScoped_clones() throws IOException { + @Test + void createdScoped_clones() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilderWithKey(privateKey) @@ -213,7 +217,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti SCOPES.toArray(), ((ServiceAccountCredentials) credentials).getScopes().toArray()); } - @Test void createdDelegated_clones() throws IOException { + @Test + void createdDelegated_clones() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilderWithKey(privateKey) @@ -237,7 +242,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(USER, ((ServiceAccountCredentials) credentials).getServiceAccountUser()); } - @Test void createAssertion_correct() throws IOException { + @Test + void createAssertion_correct() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = createDefaultBuilderWithScopes(scopes); ServiceAccountCredentials credentials = builder.setServiceAccountUser(USER).build(); @@ -256,7 +262,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); } - @Test void createAssertion_defaultScopes_correct() throws IOException { + @Test + void createAssertion_defaultScopes_correct() throws IOException { List defaultScopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = createDefaultBuilder(); builder.setScopes(null, defaultScopes).setServiceAccountUser(USER); @@ -278,7 +285,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(Joiner.on(' ').join(defaultScopes), payload.get("scope")); } - @Test void createAssertion_custom_lifetime() throws IOException { + @Test + void createAssertion_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -290,7 +298,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(currentTimeMillis / 1000 + 4000, (long) payload.getExpirationTimeSeconds()); } - @Test void createAssertionForIdToken_correct() throws IOException { + @Test + void createAssertionForIdToken_correct() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilder() @@ -313,7 +322,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(USER, payload.getSubject()); } - @Test void createAssertionForIdToken_custom_lifetime() throws IOException { + @Test + void createAssertionForIdToken_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -326,7 +336,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(currentTimeMillis / 1000 + 4000, (long) payload.getExpirationTimeSeconds()); } - @Test void createAssertionForIdToken_incorrect() throws IOException { + @Test + void createAssertionForIdToken_incorrect() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -353,7 +364,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(USER, payload.getSubject()); } - @Test void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() + @Test + void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() throws IOException { GoogleCredentials credentials = createDefaultBuilderWithToken(ACCESS_TOKEN).build(); @@ -374,7 +386,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void createdScoped_withUniverse_selfSignedJwt() throws IOException { + @Test + void createdScoped_withUniverse_selfSignedJwt() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setUniverseDomain("foo.bar").build(); @@ -413,7 +426,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti verifyJwtAccess(metadata, "dummy.default.scope2"); } - @Test void noScopes_withUniverse_selfSignedJwt() throws IOException { + @Test + void noScopes_withUniverse_selfSignedJwt() throws IOException { GoogleCredentials credentials = createDefaultBuilder().setUniverseDomain("foo.bar").build(); try { @@ -430,7 +444,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti verifyJwtAccess(metadata, null); } - @Test void createdScoped_defaultScopes() throws IOException { + @Test + void createdScoped_defaultScopes() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -467,7 +482,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals("dummy.default.scope", credentials.getDefaultScopes().toArray()[0]); } - @Test void createScopedRequired_emptyScopes() throws IOException { + @Test + void createScopedRequired_emptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, EMPTY_SCOPES); @@ -475,7 +491,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertTrue(credentials.createScopedRequired()); } - @Test void createScopedRequired_nonEmptyScopes() throws IOException { + @Test + void createScopedRequired_nonEmptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, SCOPES); @@ -483,7 +500,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(credentials.createScopedRequired()); } - @Test void createScopedRequired_nonEmptyDefaultScopes() throws IOException { + @Test + void createScopedRequired_nonEmptyDefaultScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null, SCOPES); @@ -491,7 +509,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(credentials.createScopedRequired()); } - @Test void fromJSON_getProjectId() throws IOException { + @Test + void fromJSON_getProjectId() throws IOException { GenericJson json = writeServiceAccountJson(PROJECT_ID, null, null); ServiceAccountCredentials credentials = @@ -500,7 +519,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromJSON_Universe_getUniverseDomain() throws IOException { + @Test + void fromJSON_Universe_getUniverseDomain() throws IOException { GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "foo.bar"); ServiceAccountCredentials credentials = @@ -508,7 +528,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals("foo.bar", credentials.getUniverseDomain()); } - @Test void fromJSON_getProjectIdNull() throws IOException { + @Test + void fromJSON_getProjectIdNull() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(null, null, null); @@ -518,7 +539,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertNull(credentials.getProjectId()); } - @Test void fromJSON_hasAccessToken() throws IOException { + @Test + void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, null, null); @@ -530,7 +552,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void fromJSON_withUniverse_selfSignedJwt() throws IOException { + @Test + void fromJSON_withUniverse_selfSignedJwt() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "foo.bar"); @@ -542,7 +565,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti verifyJwtAccess(metadata, "dummy.scope"); } - @Test void fromJSON_tokenServerUri() throws IOException { + @Test + void fromJSON_tokenServerUri() throws IOException { final String tokenServerUri = "https://foo.com/bar"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -553,7 +577,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(URI.create(tokenServerUri), credentials.getTokenServerUri()); } - @Test void fromJson_hasQuotaProjectId() throws IOException { + @Test + void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, QUOTA_PROJECT, null); @@ -568,14 +593,16 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti Collections.singletonList(QUOTA_PROJECT)); } - @Test void getRequestMetadata_hasAccessToken() throws IOException { + @Test + void getRequestMetadata_hasAccessToken() throws IOException { GoogleCredentials credentials = createDefaultBuilderWithToken(ACCESS_TOKEN).setScopes(SCOPES).build(); Map> metadata = credentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + @Test + 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); @@ -596,12 +623,14 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti com.google.auth.oauth2.TestUtils.validateMetricsHeader(accessTokenRequestHeader, "at", "sa"); } - @Test void getUniverseDomain_defaultUniverse() throws IOException { + @Test + void getUniverseDomain_defaultUniverse() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void refreshAccessToken_refreshesToken() throws IOException { + @Test + void refreshAccessToken_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -616,7 +645,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test void refreshAccessToken_tokenExpiry() throws IOException { + @Test + void refreshAccessToken_tokenExpiry() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -635,7 +665,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); } - @Test void refreshAccessToken_IOException_Retry() throws IOException { + @Test + void refreshAccessToken_IOException_Retry() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -653,7 +684,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test void refreshAccessToken_retriesServerErrors() throws IOException { + @Test + void refreshAccessToken_retriesServerErrors() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -672,7 +704,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { + @Test + void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -691,7 +724,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test void refreshAccessToken_defaultRetriesDisabled() throws IOException { + @Test + void refreshAccessToken_defaultRetriesDisabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -721,7 +755,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void refreshAccessToken_maxRetries_maxDelay() throws IOException { + @Test + void refreshAccessToken_maxRetries_maxDelay() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = @@ -753,7 +788,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void refreshAccessToken_RequestFailure_retried() throws IOException { + @Test + void refreshAccessToken_RequestFailure_retried() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = @@ -786,7 +822,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + @Test + void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -815,7 +852,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOException { + @Test + void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -851,7 +889,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti com.google.auth.oauth2.TestUtils.validateMetricsHeader(idTokenRequestHeader, "it", "sa"); } - @Test void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() + @Test + void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -876,7 +915,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { + @Test + void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { String nonGDU = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(nonGDU); @@ -906,7 +946,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { + @Test + void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { String nonGDU = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(nonGDU); @@ -934,7 +975,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti tokenCredential.getIdToken().getJsonWebSignature().getPayload().getAudience()); } - @Test void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOException { + @Test + void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.setError(new IOException("404 Not Found")); ServiceAccountCredentials credentials = @@ -951,7 +993,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertThrows(IOException.class, tokenCredential::refresh); } - @Test void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOException { + @Test + void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOException { String universeDomain = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(universeDomain); @@ -979,7 +1022,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertThrows(IOException.class, tokenCredential::refresh); } - @Test void getScopes_nullReturnsEmpty() throws IOException { + @Test + void getScopes_nullReturnsEmpty() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); Collection scopes = credentials.getScopes(); @@ -987,12 +1031,14 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertTrue(scopes.isEmpty()); } - @Test void getAccount_sameAs() throws IOException { + @Test + void getAccount_sameAs() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); assertEquals(CLIENT_EMAIL, credentials.getAccount()); } - @Test void sign_sameAs() + @Test + void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] toSign = {0xD, 0xE, 0xA, 0xD}; ServiceAccountCredentials credentials = createDefaultBuilder().build(); @@ -1005,7 +1051,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertArrayEquals(signature.sign(), signedBytes); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1030,7 +1077,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_clientId() throws IOException { + @Test + void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1055,7 +1103,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_email() throws IOException { + @Test + void equals_false_email() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1080,7 +1129,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_super() throws IOException { + @Test + void equals_false_super() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1108,7 +1158,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_keyId() throws IOException { + @Test + void equals_false_keyId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1133,7 +1184,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_scopes() throws IOException { + @Test + void equals_false_scopes() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1158,7 +1210,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_transportFactory() throws IOException { + @Test + void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1184,7 +1237,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_tokenServer() throws IOException { + @Test + 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(); @@ -1210,7 +1264,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1244,7 +1299,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1276,7 +1332,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void hashCode_not_equals_quota() throws IOException { + @Test + void hashCode_not_equals_quota() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1301,7 +1358,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertNotEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -1329,7 +1387,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti deserializedCredentials.toBuilder().getHttpTransportFactory().getClass()); } - @Test void fromStream_nullTransport_throws() throws IOException { + @Test + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { ServiceAccountCredentials.fromStream(stream, null); @@ -1339,7 +1398,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void fromStream_nullStream_throws() throws IOException { + @Test + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); @@ -1349,7 +1409,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void fromStream_providesToken() throws IOException { + @Test + void fromStream_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -1364,21 +1425,24 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void fromStream_noClientId_throws() throws IOException { + @Test + void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(null, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); testFromStreamException(serviceAccountStream, "client_id"); } - @Test void fromStream_noClientEmail_throws() throws IOException { + @Test + void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, null, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); testFromStreamException(serviceAccountStream, "client_email"); } - @Test void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { + @Test + void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.setError(new IOException("Invalid grant: Account not found")); @@ -1402,21 +1466,24 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } } - @Test void fromStream_noPrivateKey_throws() throws IOException { + @Test + void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, null, PRIVATE_KEY_ID); testFromStreamException(serviceAccountStream, "private_key"); } - @Test void fromStream_noPrivateKeyId_throws() throws IOException { + @Test + void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, null); testFromStreamException(serviceAccountStream, "private_key_id"); } - @Test void getUriForSelfSignedJWT() { + @Test + void getUriForSelfSignedJWT() { assertNull(ServiceAccountCredentials.getUriForSelfSignedJWT(null)); URI uri = URI.create("https://compute.googleapis.com/compute/v1/projects/"); @@ -1424,19 +1491,22 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } - @Test void getUriForSelfSignedJWT_noHost() { + @Test + void getUriForSelfSignedJWT_noHost() { URI uri = URI.create("file:foo"); URI expected = URI.create("file:foo"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } - @Test void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { + @Test + void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { URI uri = URI.create("compute.googleapis.com"); URI expected = URI.create("compute.googleapis.com"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } - @Test void getRequestMetadata_setsQuotaProjectId() throws IOException { + @Test + void getRequestMetadata_setsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1462,7 +1532,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertEquals("my-quota-project-id", headerValues.get(0)); } - @Test void getRequestMetadata_noQuotaProjectId() throws IOException { + @Test + void getRequestMetadata_noQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1484,7 +1555,8 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test void getRequestMetadata_withCallback() throws IOException { + @Test + void getRequestMetadata_withCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1523,7 +1595,8 @@ public void onFailure(Throwable exception) { assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test void getRequestMetadata_withScopes_withUniverseDomain_SelfSignedJwt() throws IOException { + @Test + void getRequestMetadata_withScopes_withUniverseDomain_SelfSignedJwt() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1562,7 +1635,8 @@ public void onFailure(Throwable exception) { assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { + @Test + void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1587,7 +1661,8 @@ public void onFailure(Throwable exception) { credentials.getMetricsCredentialType()); } - @Test void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { + @Test + void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1622,7 +1697,8 @@ public void onFailure(Throwable exception) { TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken2); } - @Test void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { + @Test + void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1639,7 +1715,8 @@ public void onFailure(Throwable exception) { verifyJwtAccess(metadata, null); } - @Test void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOException { + @Test + void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1657,7 +1734,8 @@ public void onFailure(Throwable exception) { verifyJwtAccess(metadata, "dummy.scope"); } - @Test void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { + @Test + void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1696,7 +1774,8 @@ public void onFailure(Throwable exception) { assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test void createScopes_existingAccessTokenInvalidated() throws IOException { + @Test + void createScopes_existingAccessTokenInvalidated() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index 65bee2a3c..e2185f1b3 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -95,7 +95,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final String QUOTA_PROJECT = "sample-quota-project-id"; - @Test void constructor_allParameters_constructs() throws IOException { + @Test + void constructor_allParameters_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -114,7 +115,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void constructor_noClientId_constructs() throws IOException { + @Test + void constructor_noClientId_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) @@ -123,7 +125,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { .build(); } - @Test void constructor_noPrivateKeyId_constructs() throws IOException { + @Test + void constructor_noPrivateKeyId_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -132,7 +135,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { .build(); } - @Test void constructor_noEmail_throws() throws IOException { + @Test + void constructor_noEmail_throws() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); try { ServiceAccountJwtAccessCredentials.newBuilder() @@ -146,7 +150,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { } } - @Test void constructor_noPrivateKey_throws() { + @Test + void constructor_noPrivateKey_throws() { try { ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -159,28 +164,32 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { } } - @Test void getAuthenticationType_returnsJwtAccess() throws IOException { + @Test + void getAuthenticationType_returnsJwtAccess() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); assertEquals(credentials.getAuthenticationType(), "JWTAccess"); } - @Test void hasRequestMetadata_returnsTrue() throws IOException { + @Test + void hasRequestMetadata_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); assertTrue(credentials.hasRequestMetadata()); } - @Test void hasRequestMetadataOnly_returnsTrue() throws IOException { + @Test + void hasRequestMetadataOnly_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); assertTrue(credentials.hasRequestMetadataOnly()); } - @Test void getRequestMetadata_blocking_hasJwtAccess() throws IOException { + @Test + void getRequestMetadata_blocking_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -195,7 +204,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { + @Test + void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -211,7 +221,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test void getRequestMetadata_blocking_noURI_throws() throws IOException { + @Test + void getRequestMetadata_blocking_noURI_throws() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -229,7 +240,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { } } - @Test void getRequestMetadata_blocking_cached() throws IOException { + @Test + void getRequestMetadata_blocking_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -253,7 +265,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals(metadata1, metadata2); } - @Test void getRequestMetadata_blocking_cache_expired() throws IOException { + @Test + void getRequestMetadata_blocking_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -277,7 +290,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertNotEquals(metadata1, metadata2); } - @Test void getRequestMetadata_async_hasJwtAccess() throws IOException { + @Test + void getRequestMetadata_async_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -295,7 +309,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(callback.metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { + @Test + void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -314,7 +329,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(callback.metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test void getRequestMetadata_async_noURI_exception() throws IOException { + @Test + void getRequestMetadata_async_noURI_exception() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -331,7 +347,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertNotNull(callback.exception); } - @Test void getRequestMetadata_async_cache_expired() throws IOException { + @Test + void getRequestMetadata_async_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -358,7 +375,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertNotEquals(callback1.metadata, callback2.metadata); } - @Test void getRequestMetadata_async_cached() throws IOException { + @Test + void getRequestMetadata_async_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -385,7 +403,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals(callback1.metadata, callback2.metadata); } - @Test void getRequestMetadata_contains_quotaProjectId() throws IOException { + @Test + void getRequestMetadata_contains_quotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -404,7 +423,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { Collections.singletonList(QUOTA_PROJECT)); } - @Test void getAccount_sameAs() throws IOException { + @Test + void getAccount_sameAs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -416,7 +436,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals(SA_CLIENT_EMAIL, credentials.getAccount()); } - @Test void sign_sameAs() + @Test + void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); byte[] toSign = {0xD, 0xE, 0xA, 0xD}; @@ -434,7 +455,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertArrayEquals(signature.sign(), signedBytes); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -456,7 +478,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_clientId() throws IOException { + @Test + void equals_false_clientId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -478,7 +501,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_email() throws IOException { + @Test + void equals_false_email() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -500,7 +524,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_keyId() throws IOException { + @Test + void equals_false_keyId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -522,7 +547,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_callUri() throws IOException { + @Test + void equals_false_callUri() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); final URI otherCallUri = URI.create("https://foo.com/bar"); ServiceAccountJwtAccessCredentials credentials = @@ -545,7 +571,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -564,7 +591,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + void hashCode_equals() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -585,7 +613,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + void serialize() throws IOException, ClassNotFoundException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -605,7 +634,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test void fromStream_nullStream_throws() throws IOException { + @Test + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); @@ -615,7 +645,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { } } - @Test void fromStream_hasJwtAccess() throws IOException { + @Test + void fromStream_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -627,7 +658,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test void fromStream_defaultURI_hasJwtAccess() throws IOException { + @Test + void fromStream_defaultURI_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -640,7 +672,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, CALL_URI, SA_PRIVATE_KEY_ID); } - @Test void fromStream_noClientId_throws() throws IOException { + @Test + void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -648,7 +681,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "client_id"); } - @Test void fromStream_noClientEmail_throws() throws IOException { + @Test + void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -656,7 +690,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "client_email"); } - @Test void fromStream_noPrivateKey_throws() throws IOException { + @Test + void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -664,7 +699,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "private_key"); } - @Test void fromStream_noPrivateKeyId_throws() throws IOException { + @Test + void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -672,7 +708,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { testFromStreamException(serviceAccountStream, "private_key_id"); } - @Test void jwtWithClaims_overrideAudience() throws IOException { + @Test + void jwtWithClaims_overrideAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -689,7 +726,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, URI.create("new-audience"), SA_PRIVATE_KEY_ID); } - @Test void jwtWithClaims_noAudience() throws IOException { + @Test + void jwtWithClaims_noAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -706,7 +744,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { } } - @Test void jwtWithClaims_defaultAudience() throws IOException { + @Test + void jwtWithClaims_defaultAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -722,7 +761,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { verifyJwtAccess(metadata, SA_CLIENT_EMAIL, URI.create("default-audience"), SA_PRIVATE_KEY_ID); } - @Test void getRequestMetadataSetsQuotaProjectId() throws IOException { + @Test + void getRequestMetadataSetsQuotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -741,7 +781,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertEquals("my-quota-project-id", headerValues.get(0)); } - @Test void getRequestMetadataNoQuotaProjectId() throws IOException { + @Test + void getRequestMetadataNoQuotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -756,7 +797,8 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test void getRequestMetadataWithCallback() throws IOException { + @Test + void getRequestMetadataWithCallback() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -789,7 +831,8 @@ public void onFailure(Throwable exception) { assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test void fromJSON_noUniverseDomain() throws IOException { + @Test + void fromJSON_noUniverseDomain() throws IOException { GenericJson json = writeServiceAccountJson( SA_CLIENT_ID, @@ -809,7 +852,8 @@ public void onFailure(Throwable exception) { assertEquals(GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromJSON_UniverseDomainSet() throws IOException { + @Test + void fromJSON_UniverseDomainSet() throws IOException { GenericJson json = writeServiceAccountJson( SA_CLIENT_ID, @@ -829,7 +873,8 @@ public void onFailure(Throwable exception) { assertEquals("example.com", credentials.getUniverseDomain()); } - @Test void fromPkcs8_NoUniverseDomain() throws IOException { + @Test + void fromPkcs8_NoUniverseDomain() throws IOException { ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -841,7 +886,8 @@ public void onFailure(Throwable exception) { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void fromPkcs8_CustomUniverseDomain() throws IOException { + @Test + void fromPkcs8_CustomUniverseDomain() throws IOException { ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, @@ -859,7 +905,8 @@ public void onFailure(Throwable exception) { assertEquals("example.com", credentials.getUniverseDomain()); } - @Test void builder_defaultUniverseDomain() throws IOException { + @Test + void builder_defaultUniverseDomain() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -872,7 +919,8 @@ public void onFailure(Throwable exception) { assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } - @Test void builder_customUniverseDomain() throws IOException { + @Test + void builder_customUniverseDomain() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java index 80353ecc2..5c7b44bd6 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java @@ -66,7 +66,8 @@ class Slf4jUtilsLogbackTest { testEnvironmentProvider = new TestEnvironmentProvider(); } - @Test void testLogWithMDC_slf4jLogger() { + @Test + void testLogWithMDC_slf4jLogger() { TestAppender testAppender = setupTestLogger(); @@ -88,7 +89,8 @@ class Slf4jUtilsLogbackTest { testAppender.stop(); } - @Test void testLogWithMDC_INFO() { + @Test + void testLogWithMDC_INFO() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.INFO, new HashMap<>(), "test message"); @@ -97,7 +99,8 @@ class Slf4jUtilsLogbackTest { testAppender.stop(); } - @Test void testLogWithMDC_TRACE_notEnabled() { + @Test + void testLogWithMDC_TRACE_notEnabled() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.TRACE, new HashMap<>(), "test message"); @@ -105,7 +108,8 @@ class Slf4jUtilsLogbackTest { testAppender.stop(); } - @Test void testLogWithMDC_WARN() { + @Test + void testLogWithMDC_WARN() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.WARN, new HashMap<>(), "test message"); @@ -114,7 +118,8 @@ class Slf4jUtilsLogbackTest { testAppender.stop(); } - @Test void testLogWithMDC_ERROR() { + @Test + void testLogWithMDC_ERROR() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.ERROR, new HashMap<>(), "test message"); @@ -123,7 +128,8 @@ class Slf4jUtilsLogbackTest { testAppender.stop(); } - @Test void testLogGenericData() { + @Test + void testLogGenericData() { // mimic GOOGLE_SDK_JAVA_LOGGING = true testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); @@ -149,7 +155,8 @@ class Slf4jUtilsLogbackTest { testAppender.stop(); } - @Test void testLogRequest() throws IOException { + @Test + void testLogRequest() throws IOException { // mimic GOOGLE_SDK_JAVA_LOGGING = true testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java index 2468f01a7..9ae400da4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java @@ -57,7 +57,8 @@ class Slf4jUtilsTest { } // This test mimics GOOGLE_SDK_JAVA_LOGGING != true - @Test void testGetLogger_loggingDisabled_shouldGetNOPLogger() { + @Test + void testGetLogger_loggingDisabled_shouldGetNOPLogger() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "false"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); Logger logger = Slf4jUtils.getLogger(Slf4jUtilsTest.class); @@ -68,7 +69,8 @@ class Slf4jUtilsTest { } // This test require binding (e.g. logback) be present - @Test void testGetLogger_loggingEnabled_slf4jBindingPresent() { + @Test + void testGetLogger_loggingEnabled_slf4jBindingPresent() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); Logger logger = Slf4jUtils.getLogger(LoggingUtilsTest.class); @@ -76,7 +78,8 @@ class Slf4jUtilsTest { assertNotEquals(NOPLogger.class, logger.getClass()); } - @Test void testGetLogger_loggingEnabled_noBinding() { + @Test + void testGetLogger_loggingEnabled_noBinding() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); // Create a mock LoggerFactoryProvider @@ -93,12 +96,14 @@ class Slf4jUtilsTest { assertTrue(logger instanceof org.slf4j.helpers.NOPLogger); } - @Test void testCheckIfClazzAvailable() { + @Test + void testCheckIfClazzAvailable() { assertFalse(Slf4jUtils.checkIfClazzAvailable("fake.class.should.not.be.in.classpath")); assertTrue(Slf4jUtils.checkIfClazzAvailable("org.slf4j.event.KeyValuePair")); } - @Test void testMatchLevelSevere() { + @Test + void testMatchLevelSevere() { assertEquals( org.slf4j.event.Level.ERROR, Slf4jLoggingHelpers.matchUtilLevelToSLF4JLevel(Level.SEVERE)); assertEquals( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java index 36ededd91..0bd03b1ce 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java @@ -64,7 +64,8 @@ final class StsRequestHandlerTest { transport = new MockStsTransport(); } - @Test void exchangeToken() throws IOException { + @Test + void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType") .setScopes(Collections.singletonList(OAuth2Utils.CLOUD_PLATFORM_SCOPE)) @@ -97,7 +98,8 @@ final class StsRequestHandlerTest { assertEquals(expectedRequestContent.getUnknownKeys(), actualRequestContent); } - @Test void exchangeToken_withOptionalParams() throws IOException { + @Test + void exchangeToken_withOptionalParams() throws IOException { // Return optional params scope and the refresh_token. transport.addScopeSequence(Arrays.asList("scope1", "scope2", "scope3")); transport.addRefreshTokenSequence("refreshToken"); @@ -160,7 +162,8 @@ final class StsRequestHandlerTest { assertEquals(expectedRequestContent.getUnknownKeys(), actualRequestContent); } - @Test void exchangeToken_throwsException() throws IOException { + @Test + void exchangeToken_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -183,7 +186,8 @@ final class StsRequestHandlerTest { assertNull(e.getErrorUri()); } - @Test void exchangeToken_withOptionalParams_throwsException() throws IOException { + @Test + void exchangeToken_withOptionalParams_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -205,7 +209,8 @@ final class StsRequestHandlerTest { assertEquals("errorUri", e.getErrorUri()); } - @Test void exchangeToken_ioException() { + @Test + void exchangeToken_ioException() { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -224,7 +229,8 @@ final class StsRequestHandlerTest { assertEquals(e, thrownException); } - @Test void exchangeToken_noExpiresInReturned() throws IOException { + @Test + 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); @@ -250,7 +256,8 @@ final class StsRequestHandlerTest { assertNull(response.getExpiresInSeconds()); } - @Test void exchangeToken_withAccessBoundarySessionKey() throws IOException { + @Test + void exchangeToken_withAccessBoundarySessionKey() throws IOException { transport.setReturnAccessBoundarySessionKey(/* returnAccessBoundarySessionKey= */ true); StsTokenExchangeRequest stsTokenExchangeRequest = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index 0a658d959..c133210f9 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java @@ -79,7 +79,8 @@ public long currentTimeMillis() { } }; - @Test void verifyExpiredToken() { + @Test + void verifyExpiredToken() { for (String token : ALL_TOKENS) { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build(); try { @@ -91,7 +92,8 @@ public long currentTimeMillis() { } } - @Test void verifyExpectedAudience() { + @Test + void verifyExpectedAudience() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setAudience("expected audience").build(); for (String token : ALL_TOKENS) { @@ -104,7 +106,8 @@ public long currentTimeMillis() { } } - @Test void verifyExpectedIssuer() { + @Test + void verifyExpectedIssuer() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build(); for (String token : ALL_TOKENS) { try { @@ -116,7 +119,8 @@ public long currentTimeMillis() { } } - @Test void verifyEs256Token404CertificateUrl() { + @Test + void verifyEs256Token404CertificateUrl() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -155,7 +159,8 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test void verifyEs256TokenPublicKeyMismatch() { + @Test + void verifyEs256TokenPublicKeyMismatch() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -191,7 +196,8 @@ public LowLevelHttpResponse execute() throws IOException { } } - @Test void verifyPublicKeyStoreIntermittentError() throws VerificationException, IOException { + @Test + void verifyPublicKeyStoreIntermittentError() throws VerificationException, IOException { // mock responses MockLowLevelHttpResponse response404 = new MockLowLevelHttpResponse() @@ -240,7 +246,8 @@ public LowLevelHttpResponse execute() throws IOException { assertNotNull(tokenVerifier.verify(ES256_TOKEN)); } - @Test void verifyEs256Token() throws VerificationException, IOException { + @Test + void verifyEs256Token() throws VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.gstatic.com/iap/verify/public_key-jwk", @@ -253,7 +260,8 @@ public LowLevelHttpResponse execute() throws IOException { assertNotNull(tokenVerifier.verify(ES256_TOKEN)); } - @Test void verifyRs256Token() throws VerificationException, IOException { + @Test + void verifyRs256Token() throws VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.googleapis.com/oauth2/v3/certs", @@ -266,7 +274,8 @@ public LowLevelHttpResponse execute() throws IOException { assertNotNull(tokenVerifier.verify(FEDERATED_SIGNON_RS256_TOKEN)); } - @Test void verifyRs256TokenWithLegacyCertificateUrlFormat() + @Test + void verifyRs256TokenWithLegacyCertificateUrlFormat() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java index 577bcab20..cfa9708f1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java @@ -82,7 +82,8 @@ class UserAuthorizerTest { private static final URI BASE_URI = URI.create("http://example.com/foo"); private static final PKCEProvider pkce = new DefaultPKCEProvider(); - @Test void constructorMinimum() { + @Test + void constructorMinimum() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -101,7 +102,8 @@ class UserAuthorizerTest { authorizer.getClientAuthenticationType()); } - @Test void constructorCommon() { + @Test + void constructorCommon() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -123,7 +125,8 @@ class UserAuthorizerTest { authorizer.getClientAuthenticationType()); } - @Test void constructorWithClientAuthenticationTypeNone() { + @Test + void constructorWithClientAuthenticationTypeNone() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -156,7 +159,8 @@ void constructorCommon_nullScopes_throws() { NullPointerException.class, () -> UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build()); } - @Test void getCallbackUri_relativeToBase() { + @Test + void getCallbackUri_relativeToBase() { final URI callbackURI = URI.create("/bar"); final URI expectedCallbackURI = URI.create("http://example.com/bar"); UserAuthorizer authorizer = @@ -171,7 +175,8 @@ void constructorCommon_nullScopes_throws() { assertEquals(expectedCallbackURI, absoluteCallbackURI); } - @Test void getAuthorizationUrl() throws IOException { + @Test + void getAuthorizationUrl() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -206,7 +211,8 @@ void constructorCommon_nullScopes_throws() { assertEquals("consent", parameters.get("prompt")); } - @Test void getAuthorizationUrl_additionalParameters() throws IOException { + @Test + void getAuthorizationUrl_additionalParameters() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -249,7 +255,8 @@ void constructorCommon_nullScopes_throws() { assertFalse(parameters.containsKey("param2")); } - @Test void getCredentials_noCredentials_returnsNull() throws IOException { + @Test + void getCredentials_noCredentials_returnsNull() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -262,7 +269,8 @@ void constructorCommon_nullScopes_throws() { assertNull(credentials); } - @Test void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() throws IOException { + @Test + void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode( @@ -289,7 +297,8 @@ void constructorCommon_nullScopes_throws() { assertEquals(GRANTED_SCOPES, response.getAccessToken().getScopes()); } - @Test void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationClientAuthBasic() + @Test + void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationClientAuthBasic() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -330,7 +339,8 @@ void constructorCommon_nullScopes_throws() { assertEquals(1, authHeader.size()); } - @Test void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationNoClientAuth() + @Test + void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationNoClientAuth() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -364,7 +374,8 @@ void constructorCommon_nullScopes_throws() { assertNull(headers.get("authorization")); } - @Test void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { + @Test + void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { UserAuthorizer authorizer = UserAuthorizer.newBuilder().setClientId(CLIENT_ID).setScopes(DUMMY_SCOPES).build(); @@ -376,7 +387,8 @@ void constructorCommon_nullScopes_throws() { }); } - @Test void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() + @Test + void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -408,7 +420,8 @@ void constructorCommon_nullScopes_throws() { .contains("Error reading result of Token API:Expected value access_token not found.")); } - @Test void getCredentials_storedCredentials_returnsStored() throws IOException { + @Test + void getCredentials_storedCredentials_returnsStored() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserCredentials initialCredentials = @@ -448,7 +461,8 @@ void getCredentials_nullUserId_throws() throws IOException { assertThrows(NullPointerException.class, () -> authorizer.getCredentials(null)); } - @Test void getCredentials_refreshedToken_stored() throws IOException { + @Test + void getCredentials_refreshedToken_stored() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; AccessToken accessToken1 = @@ -502,7 +516,8 @@ void getCredentials_nullUserId_throws() throws IOException { assertEquals(GRANTED_SCOPES, credentials2.getAccessToken().getScopes()); } - @Test void getCredentials_refreshedToken_different_granted_scopes() throws IOException { + @Test + void getCredentials_refreshedToken_different_granted_scopes() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; final List grantedRefreshScopes = Arrays.asList("scope3"); @@ -556,7 +571,8 @@ void getCredentials_nullUserId_throws() throws IOException { assertEquals(grantedRefreshScopes, credentials2.getAccessToken().getScopes()); } - @Test void getCredentialsFromCode_convertsCodeToTokens() throws IOException { + @Test + void getCredentialsFromCode_convertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode( @@ -577,7 +593,8 @@ void getCredentials_nullUserId_throws() throws IOException { assertEquals(GRANTED_SCOPES, credentials.getAccessToken().getScopes()); } - @Test void getCredentialsFromCode_additionalParameters() throws IOException { + @Test + void getCredentialsFromCode_additionalParameters() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -634,7 +651,8 @@ void getCredentialsFromCode_nullCode_throws() throws IOException { assertThrows(NullPointerException.class, () -> authorizer.getCredentialsFromCode(null, BASE_URI)); } - @Test void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { + @Test + void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -700,7 +718,8 @@ void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOException { () -> authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI)); } - @Test void revokeAuthorization_revokesAndClears() throws IOException { + @Test + void revokeAuthorization_revokesAndClears() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -836,7 +855,8 @@ public String getCodeChallenge() { .build()); } - @Test void testTokenResponseWithConfig() { + @Test + void testTokenResponseWithConfig() { String clientId = "testClientId"; String clientSecret = "testClientSecret"; String refreshToken = "testRefreshToken"; @@ -862,7 +882,8 @@ public String getCodeChallenge() { assertEquals(httpTransportFactory, tokenResponse.getHttpTransportFactory()); } - @Test void testTokenResponseWithConfig_noRefreshToken() { + @Test + void testTokenResponseWithConfig_noRefreshToken() { String clientId = "testClientId"; String clientSecret = "testClientSecret"; AccessToken accessToken = new AccessToken("token", new Date()); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index c9dcebfc1..9868e9d7c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -90,7 +90,8 @@ void constructor_accessAndRefreshTokenNull_throws() { () -> UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build()); } - @Test void constructor() { + @Test + void constructor() { UserCredentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -104,7 +105,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals(QUOTA_PROJECT, credentials.getQuotaProjectId()); } - @Test void createScoped_same() { + @Test + void createScoped_same() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -114,7 +116,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertSame(userCredentials, userCredentials.createScoped(SCOPES)); } - @Test void createScopedRequired_false() { + @Test + void createScopedRequired_false() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -124,7 +127,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(userCredentials.createScopedRequired()); } - @Test void fromJson_hasAccessToken() throws IOException { + @Test + void fromJson_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -136,7 +140,8 @@ void constructor_accessAndRefreshTokenNull_throws() { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void fromJson_hasTokenUri() throws IOException { + @Test + void fromJson_hasTokenUri() throws IOException { String tokenUrl = "token.url.xyz"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -147,7 +152,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals(URI.create(tokenUrl), credentials.toBuilder().getTokenServerUri()); } - @Test void fromJson_emptyTokenUri() throws IOException { + @Test + void fromJson_emptyTokenUri() throws IOException { String tokenUrl = ""; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -158,7 +164,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals(OAuth2Utils.TOKEN_SERVER_URI, credentials.toBuilder().getTokenServerUri()); } - @Test void fromJson_hasQuotaProjectId() throws IOException { + @Test + void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -173,7 +180,8 @@ void constructor_accessAndRefreshTokenNull_throws() { Collections.singletonList(QUOTA_PROJECT)); } - @Test void getRequestMetadata_initialToken_hasAccessToken() throws IOException { + @Test + void getRequestMetadata_initialToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -190,7 +198,8 @@ void constructor_accessAndRefreshTokenNull_throws() { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { + @Test + void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -210,7 +219,8 @@ void constructor_accessAndRefreshTokenNull_throws() { } } - @Test void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { + @Test + void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -227,7 +237,8 @@ void constructor_accessAndRefreshTokenNull_throws() { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + @Test + 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); @@ -247,7 +258,8 @@ void constructor_accessAndRefreshTokenNull_throws() { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void equals_true() throws IOException { + @Test + void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -275,7 +287,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertTrue(otherCredentials.equals(credentials)); } - @Test void equals_false_clientId() throws IOException { + @Test + void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -301,7 +314,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_clientSecret() throws IOException { + @Test + void equals_false_clientSecret() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -327,7 +341,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_refreshToken() throws IOException { + @Test + void equals_false_refreshToken() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -353,7 +368,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_accessToken() throws IOException { + @Test + void equals_false_accessToken() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); AccessToken otherAccessToken = new AccessToken("otherAccessToken", null); @@ -381,7 +397,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertNotEquals(credentials.hashCode(), otherAccessToken.hashCode()); } - @Test void equals_false_transportFactory() throws IOException { + @Test + void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -408,7 +425,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_tokenServer() throws IOException { + @Test + void equals_false_tokenServer() throws IOException { 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); @@ -435,7 +453,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(otherCredentials.equals(credentials)); } - @Test void equals_false_quotaProjectId() throws IOException { + @Test + void equals_false_quotaProjectId() throws IOException { final String quotaProject1 = "sample-id-1"; final String quotaProject2 = "sample-id-2"; AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -462,7 +481,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(otherCredentials.equals(credentials)); } - @Test void toString_containsFields() throws IOException { + @Test + void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -493,7 +513,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals(expectedToString, credentials.toString()); } - @Test void hashCode_equals() throws IOException { + @Test + 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); @@ -520,7 +541,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } - @Test void serialize() throws IOException, ClassNotFoundException { + @Test + 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); @@ -540,7 +562,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertSame(deserializedCredentials.clock, Clock.SYSTEM); } - @Test void fromStream_nullTransport_throws() throws IOException { + @Test + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { UserCredentials.fromStream(stream, null); @@ -550,7 +573,8 @@ void constructor_accessAndRefreshTokenNull_throws() { } } - @Test void fromStream_nullStream_throws() throws IOException { + @Test + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { UserCredentials.fromStream(null, transportFactory); @@ -560,7 +584,8 @@ void constructor_accessAndRefreshTokenNull_throws() { } } - @Test void fromStream_user_providesToken() throws IOException { + @Test + void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -574,25 +599,29 @@ void constructor_accessAndRefreshTokenNull_throws() { TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); } - @Test void fromStream_userNoClientId_throws() throws IOException { + @Test + void fromStream_userNoClientId_throws() throws IOException { InputStream userStream = writeUserStream(null, CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_id"); } - @Test void fromStream_userNoClientSecret_throws() throws IOException { + @Test + void fromStream_userNoClientSecret_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_secret"); } - @Test void fromStream_userNoRefreshToken_throws() throws IOException { + @Test + void fromStream_userNoRefreshToken_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, CLIENT_SECRET, null, QUOTA_PROJECT); testFromStreamException(userStream, "refresh_token"); } - @Test void saveUserCredentials_saved_throws() throws IOException { + @Test + void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -606,7 +635,8 @@ void constructor_accessAndRefreshTokenNull_throws() { userCredentials.save(filePath); } - @Test void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { + @Test + void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -630,7 +660,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals(userCredentials.getRefreshToken(), restoredCredentials.getRefreshToken()); } - @Test void getRequestMetadataSetsQuotaProjectId() throws IOException { + @Test + void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -651,7 +682,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertEquals("my-quota-project-id", headerValues.get(0)); } - @Test void getRequestMetadataNoQuotaProjectId() throws IOException { + @Test + void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -668,7 +700,8 @@ void constructor_accessAndRefreshTokenNull_throws() { assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test void getRequestMetadataWithCallback() throws IOException { + @Test + void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -702,7 +735,8 @@ public void onFailure(Throwable exception) { assertTrue(success.get(), "Should have run onSuccess() callback"); } - @Test void IdTokenCredentials_WithUserEmailScope_success() throws IOException { + @Test + void IdTokenCredentials_WithUserEmailScope_success() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -739,7 +773,8 @@ public void onFailure(Throwable exception) { com.google.auth.oauth2.TestUtils.validateMetricsHeader(idTokenRequestHeader, "untracked", "u"); } - @Test void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { + @Test + void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -779,7 +814,8 @@ public void onFailure(Throwable exception) { } } - @Test void idTokenWithAudience_non2xxError() throws IOException { + @Test + void idTokenWithAudience_non2xxError() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.setError(new IOException("404 Not Found")); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -793,7 +829,8 @@ public void onFailure(Throwable exception) { assertThrows(GoogleAuthException.class, tokenCredential::refresh); } - @Test void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + @Test + void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -820,7 +857,8 @@ public void onFailure(Throwable exception) { } } - @Test void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + @Test + void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -846,7 +884,8 @@ public void onFailure(Throwable exception) { } } - @Test void userCredentials_toBuilder_copyEveryAttribute() { + @Test + void userCredentials_toBuilder_copyEveryAttribute() { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); UserCredentials credentials = UserCredentials.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java index a26066a08..1121b82f7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java @@ -50,7 +50,8 @@ final class FTComputeEngineCredentialsTest { private final String computeUrl = "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; - @Test void RefreshCredentials() throws Exception { + @Test + void RefreshCredentials() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); AccessToken accessToken = credentials.refreshAccessToken(); @@ -59,7 +60,8 @@ final class FTComputeEngineCredentialsTest { assertTrue(accessToken.getExpirationTime().getTime() > System.currentTimeMillis()); } - @Test void DefaultCredentials() throws Exception { + @Test + void DefaultCredentials() throws Exception { final GoogleCredentials defaultCredential = GoogleCredentials.getApplicationDefault().createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE); @@ -68,7 +70,8 @@ final class FTComputeEngineCredentialsTest { assertTrue(accessToken.getExpirationTime().getTime() > System.currentTimeMillis()); } - @Test void IdTokenFromMetadata() throws Exception { + @Test + void IdTokenFromMetadata() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); IdToken idToken = credentials.idTokenWithAudience(computeUrl, null); assertNotNull(idToken); @@ -79,7 +82,8 @@ final class FTComputeEngineCredentialsTest { assertEquals("https://accounts.google.com", jws.getPayload().get("iss")); } - @Test void FetchIdToken() throws Exception { + @Test + void FetchIdToken() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); IdTokenCredentials idTokenCredential = IdTokenCredentials.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java index 22ce72760..865abc3f2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java @@ -40,12 +40,14 @@ public final class FTQuotaProjectId { - @Test void validate_quota_from_environment_used() throws IOException { + @Test + void validate_quota_from_environment_used() throws IOException { GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); assertEquals("gcloud-devel", credentials.getQuotaProjectId()); } - @Test void validate_quota_from_environment_not_used() throws IOException { + @Test + void validate_quota_from_environment_not_used() throws IOException { // Check the environment value for quota project assertEquals("gcloud-devel", System.getenv("GOOGLE_CLOUD_QUOTA_PROJECT")); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java index b567d2040..875fb5a37 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java @@ -63,24 +63,28 @@ final class FTServiceAccountCredentialsTest { private final String computeUrl = "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; - @Test void NoScopeNoAudienceComputeTest() throws Exception { + @Test + void NoScopeNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(computeUrl); assertEquals(200, response.getStatusCode()); } - @Test void NoScopeNoAudienceBigQueryTest() throws Exception { + @Test + void NoScopeNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(bigQueryUrl); assertEquals(200, response.getStatusCode()); } - @Test void NoScopeNoAudienceOnePlatformTest() throws Exception { + @Test + void NoScopeNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(cloudTasksUrl); assertEquals(200, response.getStatusCode()); } // TODO: add Storage case - @Test void AudienceSetNoScopeTest() throws Exception { + @Test + void AudienceSetNoScopeTest() throws Exception { final GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); IdTokenCredentials tokenCredential = @@ -100,44 +104,52 @@ final class FTServiceAccountCredentialsTest { assertEquals("https://accounts.google.com", jws.getPayload().get("iss")); } - @Test void ScopeSetNoAudienceStorageTest() throws Exception { + @Test + void ScopeSetNoAudienceStorageTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(storageUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test void ScopeSetNoAudienceComputeTest() throws Exception { + @Test + void ScopeSetNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(computeUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test void ScopeSetNoAudienceBigQueryTest() throws Exception { + @Test + void ScopeSetNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(bigQueryUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test void ScopeSetNoAudienceOnePlatformTest() throws Exception { + @Test + void ScopeSetNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(cloudTasksUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } - @Test void WrongScopeComputeTest() throws Exception { + @Test + void WrongScopeComputeTest() throws Exception { executeRequestWrongScope(computeUrl); } - @Test void WrongScopeStorageTest() throws Exception { + @Test + void WrongScopeStorageTest() throws Exception { executeRequestWrongScope(storageUrl); } - @Test void WrongScopeBigQueryTest() throws Exception { + @Test + void WrongScopeBigQueryTest() throws Exception { executeRequestWrongScope(bigQueryUrl); } - @Test void WrongScopeOnePlatformTest() throws Exception { + @Test + void WrongScopeOnePlatformTest() throws Exception { executeRequestWrongScope(cloudTasksUrl); } diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index 494364df0..992e15db6 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -86,29 +86,34 @@ private static String getIdTokenFromServiceAccount( return idToken.getTokenValue(); } - @Test void testIdTokenFromServiceAccount() throws IOException { + @Test + void testIdTokenFromServiceAccount() throws IOException { IdTokenFromServiceAccount.getIdTokenFromServiceAccount(CREDENTIALS, "https://example.com"); assertThat(stdOut.toString()).contains("Generated ID token."); } - @Test void testVerifyGoogleIdToken() throws IOException { + @Test + void testVerifyGoogleIdToken() throws IOException { String idToken = getIdTokenFromServiceAccount(CREDENTIALS, "https://example.com"); VerifyGoogleIdToken.verifyGoogleIdToken( idToken, "https://example.com", "https://www.googleapis.com/oauth2/v3/certs"); } - @Test void testIdTokenFromMetadataServer() throws GeneralSecurityException, IOException { + @Test + void testIdTokenFromMetadataServer() throws GeneralSecurityException, IOException { IdTokenFromMetadataServer.getIdTokenFromMetadataServer("https://www.google.com"); assertThat(stdOut.toString()).contains("Generated ID token."); } - @Test void testAuthenticateImplicitWithAdc() throws IOException { + @Test + void testAuthenticateImplicitWithAdc() throws IOException { AuthenticateImplicitWithAdc.authenticateImplicitWithAdc(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } - @Test void testAuthenticateExplicit() throws IOException { + @Test + void testAuthenticateExplicit() throws IOException { AuthenticateExplicit.authenticateExplicit(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } From e0249eb804e2f1d00f05087d5718f1bbdcb3fb36 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 14:22:40 -0500 Subject: [PATCH 03/19] chore: Fix JUnit annotations being on the same line --- .../appengine/AppEngineCredentialsTest.java | 3 +- .../appengine/MockAppIdentityService.java | 2 +- ...deCredentialAccessBoundaryFactoryTest.java | 21 +++---- ...lientSideCredentialAccessBoundaryTest.java | 3 +- .../com/google/auth/SigningExceptionTest.java | 3 +- .../javatests/com/google/auth/TestClock.java | 2 +- .../javatests/com/google/auth/TestUtils.java | 3 +- .../auth/http/HttpCredentialsAdapterTest.java | 5 +- .../auth/mtls/SecureConnectProviderTest.java | 7 ++- .../WorkloadCertificateConfigurationTest.java | 4 +- .../google/auth/mtls/X509ProviderTest.java | 4 +- .../google/auth/oauth2/AccessTokenTest.java | 3 +- .../auth/oauth2/AppEngineCredentialsTest.java | 3 +- .../auth/oauth2/AwsCredentialsTest.java | 14 ++--- .../auth/oauth2/AwsRequestSignerTest.java | 6 +- .../auth/oauth2/BaseSerializationTest.java | 2 +- ...eIdentityPoolSubjectTokenSupplierTest.java | 24 ++++--- .../com/google/auth/oauth2/ClientIdTest.java | 10 +-- .../oauth2/CloudShellCredentialsTest.java | 4 +- .../oauth2/ComputeEngineCredentialsTest.java | 11 ++-- .../oauth2/CredentialAccessBoundaryTest.java | 4 +- .../DefaultCredentialsProviderTest.java | 10 ++- .../auth/oauth2/DefaultPKCEProviderTest.java | 3 +- .../oauth2/DownscopedCredentialsTest.java | 7 +-- .../auth/oauth2/ExecutableResponseTest.java | 9 ++- ...lAccountAuthorizedUserCredentialsTest.java | 8 +-- .../ExternalAccountCredentialsTest.java | 16 +++-- .../ExternalAccountSupplierContextTest.java | 3 +- .../auth/oauth2/GdchCredentialsTest.java | 4 +- .../auth/oauth2/GdchCredentialsTestUtil.java | 2 +- .../auth/oauth2/GoogleAuthUtilsTest.java | 3 +- .../auth/oauth2/GoogleCredentialsTest.java | 10 ++- .../google/auth/oauth2/ITDownscopingTest.java | 3 +- .../ITWorkloadIdentityFederationTest.java | 6 +- .../com/google/auth/oauth2/IamUtilsTest.java | 7 ++- .../auth/oauth2/IdTokenCredentialsTest.java | 4 +- .../com/google/auth/oauth2/IdTokenTest.java | 4 +- .../IdentityPoolCredentialsSourceTest.java | 4 +- .../oauth2/IdentityPoolCredentialsTest.java | 13 ++-- .../oauth2/ImpersonatedCredentialsTest.java | 63 ++++++++++++------- ...nalAwsSecurityCredentialsSupplierTest.java | 5 +- .../com/google/auth/oauth2/JwtClaimsTest.java | 3 +- .../auth/oauth2/JwtCredentialsTest.java | 3 +- .../com/google/auth/oauth2/LoggingTest.java | 17 ++--- .../google/auth/oauth2/LoggingUtilsTest.java | 6 +- .../google/auth/oauth2/MetricsUtilsTest.java | 3 +- .../com/google/auth/oauth2/MockExecutor.java | 2 +- ...ckExternalAccountCredentialsTransport.java | 3 +- .../auth/oauth2/MockHttpTransportFactory.java | 2 +- .../MockIAMCredentialsServiceTransport.java | 2 +- ...IAMCredentialsServiceTransportFactory.java | 2 +- .../oauth2/MockMetadataServerTransport.java | 2 +- .../oauth2/MockRequestMetadataCallback.java | 2 +- .../google/auth/oauth2/MockStsTransport.java | 3 +- .../oauth2/MockTokenCheckingTransport.java | 2 +- .../auth/oauth2/MockTokenServerTransport.java | 2 +- .../MockTokenServerTransportFactory.java | 2 +- .../auth/oauth2/OAuth2CredentialsTest.java | 27 ++++---- .../OAuth2CredentialsWithRefreshTest.java | 7 +-- .../google/auth/oauth2/OAuth2UtilsTest.java | 4 +- .../auth/oauth2/OAuthExceptionTest.java | 4 +- .../oauth2/PluggableAuthCredentialsTest.java | 6 +- .../oauth2/PluggableAuthExceptionTest.java | 3 +- .../auth/oauth2/PluggableAuthHandlerTest.java | 25 +++----- .../oauth2/SecureSessionAgentConfigTest.java | 4 +- .../auth/oauth2/SecureSessionAgentTest.java | 4 +- .../oauth2/ServiceAccountCredentialsTest.java | 10 ++- ...erviceAccountJwtAccessCredentialsTest.java | 5 +- .../auth/oauth2/Slf4jUtilsLogbackTest.java | 9 ++- .../google/auth/oauth2/Slf4jUtilsTest.java | 5 +- .../auth/oauth2/StsRequestHandlerTest.java | 22 +++---- .../com/google/auth/oauth2/TestAppender.java | 2 +- .../auth/oauth2/TestEnvironmentProvider.java | 2 +- .../com/google/auth/oauth2/TestUtils.java | 3 +- .../google/auth/oauth2/TokenVerifierTest.java | 6 +- .../auth/oauth2/UserAuthorizerTest.java | 22 ++++--- .../auth/oauth2/UserCredentialsTest.java | 10 ++- .../FTComputeEngineCredentialsTest.java | 3 +- .../oauth2/functional/FTQuotaProjectId.java | 3 +- .../FTServiceAccountCredentialsTest.java | 3 +- 80 files changed, 294 insertions(+), 273 deletions(-) diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index 7fa155fe7..c52c65c46 100644 --- a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java +++ b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java @@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.BaseSerializationTest; @@ -248,4 +249,4 @@ private static void assertContainsBearerToken(Map> metadata assertNotNull(authorizations, "Authorization headers not found"); assertTrue(authorizations.contains(expectedValue), "Bearer token not found"); } -} \ No newline at end of file +} diff --git a/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java b/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java index a7fa4eb40..c0befa4c7 100644 --- a/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java +++ b/appengine/javatests/com/google/auth/appengine/MockAppIdentityService.java @@ -120,4 +120,4 @@ public ParsedAppId parseFullAppId(String fullAppId) { public String getDefaultGcsBucketName() { return null; } -} \ No newline at end of file +} diff --git a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java index 6a77f67b7..c42c15af5 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java @@ -31,12 +31,11 @@ package com.google.auth.credentialaccessboundary; +import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -77,7 +76,6 @@ * Tests for {@link * com.google.auth.credentialaccessboundary.ClientSideCredentialAccessBoundaryFactory}. */ - class ClientSideCredentialAccessBoundaryFactoryTest { private static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n" @@ -105,7 +103,8 @@ public HttpTransport create() { } } - @BeforeEach void setUp() { + @BeforeEach + void setUp() { mockStsTransportFactory = new MockStsTransportFactory(); mockStsTransportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -185,8 +184,7 @@ void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOExceptio } @Test - void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() - throws Exception { + void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() throws Exception { // Simulate STS not returning expires_in. mockStsTransportFactory.transport.setReturnExpiresIn(false); @@ -214,8 +212,7 @@ void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() } @Test - void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() - throws IOException { + void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -307,8 +304,7 @@ void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { } @Test - void refreshCredentialsIfRequired_blockingMultiThread() - throws IOException, InterruptedException { + void refreshCredentialsIfRequired_blockingMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -328,8 +324,7 @@ void refreshCredentialsIfRequired_blockingMultiThread() } @Test - void refreshCredentialsIfRequired_asyncMultiThread() - throws IOException, InterruptedException { + void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -993,4 +988,4 @@ void generateToken_withMalformSessionKey_failure() throws Exception { assertThrows(GeneralSecurityException.class, () -> factory.generateToken(accessBoundary)); } -} \ No newline at end of file +} diff --git a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java index 04a8a926d..cab0183f1 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java @@ -34,6 +34,7 @@ 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; import com.google.api.client.http.HttpRequestFactory; @@ -149,4 +150,4 @@ private void retrieveObjectFromGcs(Credentials credentials, String objectName) HttpResponse response = request.execute(); assertTrue(response.isSuccessStatusCode()); } -} \ No newline at end of file +} diff --git a/credentials/javatests/com/google/auth/SigningExceptionTest.java b/credentials/javatests/com/google/auth/SigningExceptionTest.java index 8787c71a0..14293b082 100644 --- a/credentials/javatests/com/google/auth/SigningExceptionTest.java +++ b/credentials/javatests/com/google/auth/SigningExceptionTest.java @@ -35,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.auth.ServiceAccountSigner.SigningException; import java.io.IOException; import org.junit.jupiter.api.Test; @@ -82,4 +83,4 @@ void hashCode_equals() throws IOException { SigningException otherSigningException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertEquals(signingException.hashCode(), otherSigningException.hashCode()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/TestClock.java b/oauth2_http/javatests/com/google/auth/TestClock.java index 364d66321..fa3dd027f 100644 --- a/oauth2_http/javatests/com/google/auth/TestClock.java +++ b/oauth2_http/javatests/com/google/auth/TestClock.java @@ -50,4 +50,4 @@ public void addToCurrentTime(long milliseconds) { public void setCurrentTime(long currentTime) { this.currentTime = currentTime; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/TestUtils.java b/oauth2_http/javatests/com/google/auth/TestUtils.java index 52d8f726d..d794ba184 100644 --- a/oauth2_http/javatests/com/google/auth/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/TestUtils.java @@ -34,6 +34,7 @@ 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; import com.google.api.client.json.GenericJson; @@ -150,4 +151,4 @@ public static String getDefaultExpireTime() { } private TestUtils() {} -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index 45acbecac..e99f7f682 100644 --- a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java +++ b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java @@ -31,9 +31,9 @@ package com.google.auth.http; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.hamcrest.CoreMatchers.instanceOf; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; @@ -50,7 +50,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link HttpCredentialsAdapter}. */ - class HttpCredentialsAdapterTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @@ -171,4 +170,4 @@ void getCredentials() { Credentials returnedCredentials = adapter.getCredentials(); assertThat(returnedCredentials, instanceOf(Credentials.class)); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java index 2b8f3d562..5f796fc16 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java @@ -34,6 +34,7 @@ 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 java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -141,7 +142,9 @@ void testRunCertificateProviderCommandTimeout() throws InterruptedException { assertThrows( IOException.class, () -> SecureConnectProvider.runCertificateProviderCommand(certCommandProcess, 100)); - assertTrue(actual.getMessage().contains("SecureConnect: Cert provider command timed out"), "expected to fail with timeout"); + assertTrue( + actual.getMessage().contains("SecureConnect: Cert provider command timed out"), + "expected to fail with timeout"); } @Test @@ -155,4 +158,4 @@ void testGetKeyStore_FileNotFoundException() assertEquals("SecureConnect metadata does not exist.", exception.getMessage()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java index 8490144ad..bd17436c1 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java @@ -34,11 +34,11 @@ 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.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; import java.io.InputStream; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class WorkloadCertificateConfigurationTest { @@ -147,4 +147,4 @@ private static GenericJson writeWorkloadCertificateConfigJson( json.put("cert_configs", certConfigs); return json; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java index de684377b..7f3927654 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java @@ -35,6 +35,7 @@ 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 java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; @@ -47,7 +48,6 @@ import java.security.cert.CertificateFactory; import java.util.HashMap; import java.util.Map; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class X509ProviderTest { @@ -235,4 +235,4 @@ InputStream createInputStream(File file) throws FileNotFoundException { return stream; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java index 4bf342da2..d93e2c98f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java @@ -36,6 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -245,4 +246,4 @@ void serialize() throws IOException, ClassNotFoundException { assertEquals(accessToken.hashCode(), deserializedAccessToken.hashCode()); assertEquals(accessToken.toString(), deserializedAccessToken.toString()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index 43b575be7..bb2bc1ff3 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -37,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.util.ArrayList; @@ -302,4 +303,4 @@ Class forName(String className) throws ClassNotFoundException { throw new ClassNotFoundException(className); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java index fd25e5c2a..4764d27ec 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; +import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; 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.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonParser; @@ -59,7 +59,6 @@ import org.junit.jupiter.api.Test; /** Tests for {@link AwsCredentials}. */ - class AwsCredentialsTest extends BaseSerializationTest { private static final String STS_URL = "https://sts.googleapis.com/v1/token"; @@ -242,8 +241,7 @@ void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() } @Test - void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() - throws IOException { + void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -384,8 +382,7 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } @Test - void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() - throws IOException { + void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -430,8 +427,7 @@ void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() } @Test - void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() - throws IOException { + void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -1397,4 +1393,4 @@ public AwsSecurityCredentials getCredentials(ExternalAccountSupplierContext cont return credentials; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java index 0161d2983..a1125edef 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java @@ -32,6 +32,7 @@ package com.google.auth.oauth2; import static org.junit.jupiter.api.Assertions.assertEquals; + import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; @@ -62,7 +63,8 @@ class AwsRequestSignerTest { private AwsSecurityCredentials awsSecurityCredentials; - @BeforeEach void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { // Required for date parsing when run in different Locales Locale.setDefault(Locale.US); awsSecurityCredentials = retrieveAwsSecurityCredentials(); @@ -542,4 +544,4 @@ public AwsSecurityCredentials retrieveAwsSecurityCredentials() throws IOExceptio return new AwsSecurityCredentials(accessKeyId, secretAccessKey, awsToken); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java index 23fd21b6b..f9fbac134 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/BaseSerializationTest.java @@ -51,4 +51,4 @@ public T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundExc return (T) input.readObject(); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java index 9c7e551b7..9ff8f7f5f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java @@ -57,7 +57,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; - import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -83,7 +82,8 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { private byte[] testCertBytesFromFile; private byte[] intermediateCertBytesFromFile; - @BeforeEach void setUp() throws IOException, URISyntaxException { + @BeforeEach + void setUp() throws IOException, URISyntaxException { ClassLoader classLoader = getClass().getClassLoader(); URL leafCertUrl = classLoader.getResource("x509_leaf_certificate.pem"); assertNotNull(leafCertUrl, "Test leaf certificate file not found!"); @@ -93,11 +93,14 @@ class CertificateIdentityPoolSubjectTokenSupplierTest { assertNotNull(intermediateCertUrl, "Test intermediate certificate file not found!"); lenient().when(mockCertificateConfig.useDefaultCertificateConfig()).thenReturn(false); - lenient().when(mockCertificateConfig.getCertificateConfigLocation()) + lenient() + .when(mockCertificateConfig.getCertificateConfigLocation()) .thenReturn(testCertFile.getAbsolutePath()); lenient().when(mockCredentialSource.getCertificateConfig()).thenReturn(mockCertificateConfig); - lenient().when(mockCredentialSource.getCredentialLocation()).thenReturn(testCertFile.getAbsolutePath()); + lenient() + .when(mockCredentialSource.getCredentialLocation()) + .thenReturn(testCertFile.getAbsolutePath()); supplier = new CertificateIdentityPoolSubjectTokenSupplier(mockCredentialSource); testCertBytesFromFile = Files.readAllBytes(Paths.get(leafCertUrl.toURI())); @@ -251,7 +254,9 @@ void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException() { Throwable cause = exception.getCause(); assertNotNull(cause, "Exception cause should not be null"); - assertTrue(cause instanceof IllegalArgumentException, "Exception cause should be an IllegalArgumentException"); + assertTrue( + cause instanceof IllegalArgumentException, + "Exception cause should be an IllegalArgumentException"); assertEquals(expectedRootErrorMessage, cause.getMessage()); } @@ -261,7 +266,9 @@ void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { // simulating a scenario where the trust chain file contains only the leaf. ClassLoader classLoader = getClass().getClassLoader(); URL trustChainUrl = classLoader.getResource("x509_leaf_certificate.pem"); - assertNotNull(trustChainUrl, "Test resource 'x509_leaf_certificate.pem' (used as trust chain) not found!"); + assertNotNull( + trustChainUrl, + "Test resource 'x509_leaf_certificate.pem' (used as trust chain) not found!"); when(mockCertificateConfig.getTrustChainPath()) .thenReturn(new File(trustChainUrl.getFile()).getAbsolutePath()); @@ -350,7 +357,8 @@ void getSubjectToken_leafCertFileNotFound_throwsIOException() { // Check that the cause is the original NoSuchFileException. assertNotNull(exception.getCause(), "Exception should have a cause"); - assertTrue(exception.getCause() instanceof NoSuchFileException, "Cause should be NoSuchFileException"); + assertTrue( + exception.getCause() instanceof NoSuchFileException, "Cause should be NoSuchFileException"); // Check the message of the cause (which is the path) in a platform-agnostic way. Path expectedCausePath = Paths.get(nonExistentPath); @@ -427,4 +435,4 @@ void readTrustChain_emptyFile_returnsEmptyList() throws IOException, Certificate assertNotNull(certs); assertTrue(certs.isEmpty()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java index f7cdbb305..c002cf7e4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java @@ -34,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; + import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; @@ -41,7 +42,6 @@ import org.junit.jupiter.api.Test; /** Unit tests for ClientId */ - class ClientIdTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @@ -58,7 +58,8 @@ void constructor() { @Test void constructor_nullClientId_throws() { assertThrows( - NullPointerException.class, () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); + NullPointerException.class, + () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); } @Test @@ -130,7 +131,8 @@ void fromResource() throws IOException { @Test void fromResource_badResource() throws IOException { assertThrows( - NullPointerException.class, () -> ClientId.fromResource(ClientIdTest.class, "invalid.json")); + NullPointerException.class, + () -> ClientId.fromResource(ClientIdTest.class, "invalid.json")); } @Test @@ -183,4 +185,4 @@ private GenericJson writeClientIdJson(String type, String clientId, String clien json.put(type, details); return json; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java index fdd60474e..2f0dde620 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java @@ -35,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.api.client.util.Clock; import java.io.BufferedReader; import java.io.IOException; @@ -45,7 +46,6 @@ import org.junit.jupiter.api.Test; /** Unit tests for CloudShellCredentials */ - class CloudShellCredentialsTest extends BaseSerializationTest { @Test @@ -137,4 +137,4 @@ void toBuilder() { assertEquals(credentials, secondCredentials); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java index 16dd48543..c41f7a770 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -31,6 +31,8 @@ package com.google.auth.oauth2; +import static com.google.auth.oauth2.ComputeEngineCredentials.METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE; +import static com.google.auth.oauth2.ImpersonatedCredentialsTest.SA_CLIENT_EMAIL; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -40,8 +42,6 @@ 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 static com.google.auth.oauth2.ComputeEngineCredentials.METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE; -import static com.google.auth.oauth2.ImpersonatedCredentialsTest.SA_CLIENT_EMAIL; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -69,11 +69,9 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** Test case for {@link ComputeEngineCredentials}. */ - class ComputeEngineCredentialsTest extends BaseSerializationTest { private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); @@ -795,8 +793,7 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - IOException exception = - assertThrows(IOException.class, () -> credentials.refreshAccessToken()); + IOException exception = assertThrows(IOException.class, () -> credentials.refreshAccessToken()); assertTrue(exception.getCause().getMessage().contains("503")); assertTrue(exception instanceof GoogleAuthException); assertTrue(((GoogleAuthException) exception).isRetryable()); @@ -1154,4 +1151,4 @@ public HttpTransport create() { return transport; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java index d6af084ee..0dee7011e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java @@ -34,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; + import com.google.auth.oauth2.CredentialAccessBoundary.AccessBoundaryRule; import com.google.auth.oauth2.CredentialAccessBoundary.AccessBoundaryRule.AvailabilityCondition; import java.util.ArrayList; @@ -42,7 +43,6 @@ import org.junit.jupiter.api.Test; /** Tests for {@link CredentialAccessBoundary} and encompassing classes. */ - class CredentialAccessBoundaryTest { @Test @@ -317,4 +317,4 @@ void availabilityCondition_emptyExpression_throws() { assertEquals("The provided expression is empty.", e.getMessage()); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java index ceef91329..1852629ee 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java @@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; @@ -67,7 +68,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link DefaultCredentialsProvider}. */ - class DefaultCredentialsProviderTest { private static final String USER_CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @@ -285,8 +285,7 @@ void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() } @Test - void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() - throws IOException { + void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -768,8 +767,7 @@ void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredential } @Test - void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo() - throws IOException { + void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -1027,4 +1025,4 @@ public HttpTransport create() { return transport; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java index 4a5027194..114e27298 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; + import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; @@ -62,4 +63,4 @@ void testNoBase64Padding() throws NoSuchAlgorithmException { assertFalse(pkce.getCodeChallenge().endsWith("=")); assertFalse(pkce.getCodeChallenge().contains("=")); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index 2319ba37c..31c4e776e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; +import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; +import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; -import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; -import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; import com.google.api.client.http.HttpTransport; import com.google.auth.TestUtils; @@ -46,7 +46,6 @@ import org.junit.jupiter.api.Test; /** Tests for {@link DownscopedCredentials}. */ - class DownscopedCredentialsTest { private static final String SA_PRIVATE_KEY_PKCS8 = @@ -341,4 +340,4 @@ public String getUniverseDomain() throws IOException { throw new IOException(); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java index 3a745f92c..da7ea8cc6 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java @@ -36,6 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.json.GenericJson; import java.io.IOException; import java.math.BigDecimal; @@ -67,8 +68,7 @@ void constructor_successOidcResponse() throws IOException { } @Test - void constructor_successOidcResponseMissingExpirationTimeField_notExpired() - throws IOException { + void constructor_successOidcResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("expiration_time"); @@ -97,8 +97,7 @@ void constructor_successSamlResponse() throws IOException { } @Test - void constructor_successSamlResponseMissingExpirationTimeField_notExpired() - throws IOException { + void constructor_successSamlResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildSamlResponse(); jsonResponse.remove("expiration_time"); @@ -306,4 +305,4 @@ private static GenericJson buildErrorResponse() { json.put("message", "Caller not authorized."); return json; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java index a489d5294..4913e5aec 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java @@ -31,6 +31,7 @@ package com.google.auth.oauth2; +import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -39,7 +40,6 @@ 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 static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -67,7 +67,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link ExternalAccountAuthorizedUserCredentials}. */ - class ExternalAccountAuthorizedUserCredentialsTest extends BaseSerializationTest { private static final String AUDIENCE = @@ -126,7 +125,8 @@ public HttpTransport create() { } } - @BeforeEach void setup() { + @BeforeEach + void setup() { transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); } @@ -1264,4 +1264,4 @@ private static void validateAuthHeader(MockLowLevelHttpRequest request) { assertEquals(BASIC_AUTH, authHeader.iterator().next()); assertEquals(1, authHeader.size()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java index 6e38a84cc..d45979cfb 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; +import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; 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.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -60,7 +60,6 @@ import org.junit.jupiter.api.Test; /** Tests for {@link ExternalAccountCredentials}. */ - class ExternalAccountCredentialsTest extends BaseSerializationTest { private static final String STS_URL = "https://sts.googleapis.com/v1/token"; @@ -86,7 +85,8 @@ public HttpTransport create() { private MockExternalAccountCredentialsTransportFactory transportFactory; - @BeforeEach void setup() { + @BeforeEach + void setup() { transportFactory = new MockExternalAccountCredentialsTransportFactory(); } @@ -223,8 +223,7 @@ void fromJson_identityPoolCredentialsWorkforce() throws IOException { } @Test - void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() - throws IOException { + void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set( "service_account_impersonation", buildServiceAccountImpersonationOptions(2800)); @@ -958,9 +957,8 @@ void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPas } @Test - void - exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() - throws IOException { + void exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() + throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), transportFactory); @@ -1391,4 +1389,4 @@ public String retrieveSubjectToken() { return "subjectToken"; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java index 67b9c17ba..0774c6e7d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java @@ -32,6 +32,7 @@ package com.google.auth.oauth2; import static org.junit.jupiter.api.Assertions.assertEquals; + import com.google.auth.oauth2.ExternalAccountCredentials.SubjectTokenTypes; import org.junit.jupiter.api.Test; @@ -66,4 +67,4 @@ void constructor_builder_subjectTokenEnum() { assertEquals(expectedAudience, context.getAudience()); assertEquals(expectedTokenType.value, context.getSubjectTokenType()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java index 11632d211..b55514916 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java @@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; 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; import com.google.api.client.json.webtoken.JsonWebSignature; @@ -56,7 +57,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link GdchCredentials}. */ - class GdchCredentialsTest extends BaseSerializationTest { private static final String FORMAT_VERSION = GdchCredentials.SUPPORTED_FORMAT_VERSION; private static final String PRIVATE_KEY_ID = "d84a4fefcf50791d4a90f2d7af17469d6282df9d"; @@ -937,4 +937,4 @@ static InputStream writeGdchServiceAccountStream( tokenServerUri); return TestUtils.jsonToInputStream(json); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java index 7bbf88b5c..76385a5e8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java @@ -24,4 +24,4 @@ public static GdchCredentials fromJson( throws IOException { return GdchCredentials.fromJson(json, transportFactory); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java index 56a6c9667..7c883df0f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import org.junit.jupiter.api.Test; @@ -54,4 +55,4 @@ void getWellKnownCredentialsPath_correct() { assertNotNull(obtainedPath); assertEquals(obtainedPath, wellKnownFile.getAbsolutePath()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java index dfe51741f..503c87d54 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -39,6 +39,7 @@ 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.http.HttpStatusCodes; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Clock; @@ -61,7 +62,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link GoogleCredentials}. */ - class GoogleCredentialsTest extends BaseSerializationTest { private static final String SA_CLIENT_EMAIL = @@ -564,8 +564,7 @@ void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { } @Test - void fromStream_externalAccountAuthorizedUserCredentials_providesToken() - throws IOException { + void fromStream_externalAccountAuthorizedUserCredentials_providesToken() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); InputStream stream = @@ -579,8 +578,7 @@ void fromStream_externalAccountAuthorizedUserCredentials_providesToken() } @Test - void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() - throws IOException { + void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); @@ -931,4 +929,4 @@ void getCredentialInfo_impersonatedServiceAccount() throws IOException { assertEquals( ImpersonatedCredentialsTest.IMPERSONATED_CLIENT_EMAIL, credentialInfo.get("Principal")); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java index c1d285fac..2a04d7710 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java @@ -34,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; @@ -146,4 +147,4 @@ private void retrieveObjectFromGcs(Credentials credentials, String objectName) HttpResponse response = request.execute(); assertTrue(response.isSuccessStatusCode()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index 019dcb076..d1574a06a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; @@ -78,7 +79,8 @@ final class ITWorkloadIdentityFederationTest { private String clientEmail; - @BeforeEach void setup() throws IOException { + @BeforeEach + void setup() throws IOException { GenericJson keys = getServiceAccountKeyFileAsJson(); clientEmail = (String) keys.get("client_email"); } @@ -469,4 +471,4 @@ public AwsSecurityCredentials getCredentials(ExternalAccountSupplierContext cont return this.credentials; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index fabb5de5d..c9413c6cb 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -34,6 +34,7 @@ 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.HttpStatusCodes; import com.google.auth.Credentials; import com.google.auth.ServiceAccountSigner; @@ -41,7 +42,6 @@ import java.io.IOException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - import org.mockito.Mockito; class IamUtilsTest { @@ -51,7 +51,8 @@ class IamUtilsTest { private ServiceAccountCredentials credentials; - @BeforeEach void setup() throws IOException { + @BeforeEach + void setup() throws IOException { // Mock this call for the Credentials because the IAM SignBlob RPC requires an access token. The // call is initialized with HttpCredentialsAdapter which will make a call to get the access // token @@ -236,4 +237,4 @@ void sign_4xxError_noRetry_exception() { // Only one request will have been made for a 4xx error (no retries) assertEquals(1, transportFactory.getTransport().getNumRequests()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java index 856877fce..e3dcec4b5 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java @@ -32,11 +32,11 @@ package com.google.auth.oauth2; import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.IOException; import org.junit.jupiter.api.Test; /** Test case for {@link IdTokenCredentials}. */ - class IdTokenCredentialsTest extends BaseSerializationTest { @Test @@ -110,4 +110,4 @@ void serialize() throws IOException, ClassNotFoundException { IdTokenCredentials deserializedCredentials = serializeAndDeserialize(tokenCredential); assertEquals(tokenCredential, deserializedCredentials); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java index cccc570a1..52fa2c008 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java @@ -34,12 +34,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.util.Date; import org.junit.jupiter.api.Test; /** Unit tests for AccessToken */ - class IdTokenTest extends BaseSerializationTest { private static final String TOKEN_1 = @@ -104,4 +104,4 @@ void token_with_0x20() throws IOException { IdToken accessToken = IdToken.create(TOKEN_WITH_0x20); assertEquals(TOKEN_WITH_0x20, accessToken.getTokenValue()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java index f05c33f6d..aecd82f94 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java @@ -36,13 +36,13 @@ 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.auth.oauth2.IdentityPoolCredentialSource.IdentityPoolCredentialSourceType; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; /** Tests for {@link IdentityPoolCredentialSource}. */ - class IdentityPoolCredentialsSourceTest { @Test @@ -152,4 +152,4 @@ void constructor_certificateConfig_invalidType_throws() { "Invalid type for 'use_default_certificate_config' in certificate configuration: expected Boolean, got String.", exception.getMessage()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java index 2ad2d3dd8..6997c79b0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java @@ -31,16 +31,15 @@ package com.google.auth.oauth2; +import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; +import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; +import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; -import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; -import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY; - import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -66,7 +65,6 @@ import java.util.Map; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; - import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @@ -575,8 +573,7 @@ void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOExce } @Test - void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() - throws IOException { + void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -1311,4 +1308,4 @@ void setShouldThrowOnGetCertificatePath(boolean shouldThrow) { this.shouldThrowOnGetCertificatePath = shouldThrow; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java index 264d4e493..d85f2db80 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java @@ -75,7 +75,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link ImpersonatedCredentials}. */ - class ImpersonatedCredentialsTest extends BaseSerializationTest { public static final String SA_CLIENT_EMAIL = @@ -155,7 +154,8 @@ class ImpersonatedCredentialsTest extends BaseSerializationTest { private GoogleCredentials sourceCredentials; private MockIAMCredentialsServiceTransportFactory mockTransportFactory; - @BeforeEach void setup() throws IOException { + @BeforeEach + void setup() throws IOException { sourceCredentials = getSourceCredentials(); mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); } @@ -177,7 +177,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { return sourceCredentials; } - @Test() void fromJson_userAsSource_WithQuotaProjectId() throws IOException { + @Test() + void fromJson_userAsSource_WithQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -199,7 +200,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { + @Test() + void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -221,7 +223,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() void fromJson_userAsSource_MissingDelegatesField() throws IOException { + @Test() + void fromJson_userAsSource_MissingDelegatesField() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -244,7 +247,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test() void fromJson_ServiceAccountAsSource() throws IOException { + @Test() + void fromJson_ServiceAccountAsSource() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, DELEGATES, QUOTA_PROJECT_ID, IMMUTABLE_SCOPES_LIST); @@ -260,7 +264,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(sourceCredentials instanceof ServiceAccountCredentials); } - @Test() void fromJson_InvalidFormat() throws IOException { + @Test() + void fromJson_InvalidFormat() throws IOException { GenericJson json = buildInvalidCredentialsJson(); try { ImpersonatedCredentials.fromJson(json, mockTransportFactory); @@ -270,7 +275,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { } } - @Test() void createScopedRequired_True() { + @Test() + void createScopedRequired_True() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -282,7 +288,8 @@ static GoogleCredentials getSourceCredentials() throws IOException { assertTrue(targetCredentials.createScopedRequired()); } - @Test() void createScopedRequired_False() { + @Test() + void createScopedRequired_False() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -413,7 +420,8 @@ void refreshAccessToken_unauthorized() throws IOException { } } - @Test() void refreshAccessToken_malformedTarget() throws IOException { + @Test() + void refreshAccessToken_malformedTarget() throws IOException { String invalidTargetEmail = "foo"; String expectedMessage = "Request contains an invalid argument"; @@ -442,14 +450,16 @@ void refreshAccessToken_unauthorized() throws IOException { } } - @Test() void credential_with_zero_lifetime() throws IllegalStateException { + @Test() + void credential_with_zero_lifetime() throws IllegalStateException { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, IMMUTABLE_SCOPES_LIST, 0); assertEquals(3600, targetCredentials.getLifetime()); } - @Test() void credential_with_invalid_lifetime() throws IOException, IllegalStateException { + @Test() + void credential_with_invalid_lifetime() throws IOException, IllegalStateException { try { ImpersonatedCredentials targetCredentials = @@ -469,7 +479,8 @@ void refreshAccessToken_unauthorized() throws IOException { } } - @Test() void credential_with_invalid_scope() throws IOException, IllegalStateException { + @Test() + void credential_with_invalid_scope() throws IOException, IllegalStateException { assertThrows( NullPointerException.class, () -> @@ -477,7 +488,8 @@ void refreshAccessToken_unauthorized() throws IOException { sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, null, VALID_LIFETIME)); } - @Test() void refreshAccessToken_success() throws IOException, IllegalStateException { + @Test() + void refreshAccessToken_success() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -502,7 +514,8 @@ void refreshAccessToken_unauthorized() throws IOException { assertTrue(requestHeader.containsKey("authorization")); } - @Test() void refreshAccessToken_success_SSJflow() throws IOException, IllegalStateException { + @Test() + void refreshAccessToken_success_SSJflow() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -527,7 +540,8 @@ void refreshAccessToken_unauthorized() throws IOException { DEFAULT_IMPERSONATION_URL, mockTransportFactory.getTransport().getRequest().getUrl()); } - @Test() void refreshAccessToken_success_nonGDU() throws IOException, IllegalStateException { + @Test() + void refreshAccessToken_success_nonGDU() throws IOException, IllegalStateException { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(TEST_UNIVERSE_DOMAIN); transportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -578,7 +592,8 @@ void refreshAccessToken_endpointOverride() throws IOException, IllegalStateExcep IMPERSONATION_OVERRIDE_URL, mockTransportFactory.getTransport().getRequest().getUrl()); } - @Test() void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { + @Test() + void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -600,7 +615,8 @@ void refreshAccessToken_endpointOverride() throws IOException, IllegalStateExcep assertEquals(QUOTA_PROJECT_ID, headerValues.get(0)); } - @Test() void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { + @Test() + void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -618,7 +634,8 @@ void refreshAccessToken_endpointOverride() throws IOException, IllegalStateExcep assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test() void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { + @Test() + void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -637,8 +654,7 @@ void refreshAccessToken_endpointOverride() throws IOException, IllegalStateExcep } @Test - void refreshAccessToken_GMT_dateParsedCorrectly() - throws IOException, IllegalStateException { + void refreshAccessToken_GMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -664,8 +680,7 @@ void refreshAccessToken_GMT_dateParsedCorrectly() } @Test - void refreshAccessToken_nonGMT_dateParsedCorrectly() - throws IOException, IllegalStateException { + void refreshAccessToken_nonGMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -1407,4 +1422,4 @@ static InputStream writeImpersonationCredentialsStream( buildImpersonationCredentialsJson(impersonationUrl, delegates, quotaProjectId, scopes); return TestUtils.jsonToInputStream(json); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java index cc21cb3fa..28b98cdb8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; +import static com.google.auth.oauth2.AwsCredentialsTest.buildAwsImdsv2CredentialSource; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import static com.google.auth.oauth2.AwsCredentialsTest.buildAwsImdsv2CredentialSource; import com.google.auth.oauth2.ExternalAccountCredentialsTest.MockExternalAccountCredentialsTransportFactory; import com.google.common.collect.ImmutableList; @@ -41,7 +41,6 @@ import org.junit.jupiter.api.Test; /** Tests for {@link InternalAwsSecurityCredentialsSupplier}. */ - class InternalAwsSecurityCredentialsSupplierTest { @Test void shouldUseMetadataServer_withRequiredEnvironmentVariables() { @@ -160,4 +159,4 @@ void shouldUseMetadataServer_noEnvironmentVars() { transportFactory); assertTrue(supplier.shouldUseMetadataServer()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java index 433cec68e..8c81a7707 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java @@ -35,6 +35,7 @@ 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.jupiter.api.Test; @@ -147,4 +148,4 @@ void testIsComplete() { .build(); assertTrue(claims.isComplete()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java index 480bf48d8..95a4e3f4d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java @@ -36,6 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; @@ -310,4 +311,4 @@ private void verifyJwtAccess( assertEquals(entry.getValue(), signature.getPayload().get(entry.getKey())); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java index 8138cbaa9..8be16a89a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java @@ -31,9 +31,6 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static com.google.auth.TestUtils.getDefaultExpireTime; import static com.google.auth.oauth2.ImpersonatedCredentialsTest.DEFAULT_IMPERSONATION_URL; import static com.google.auth.oauth2.ImpersonatedCredentialsTest.IMMUTABLE_SCOPES_LIST; @@ -49,6 +46,9 @@ import static com.google.auth.oauth2.UserCredentialsTest.CLIENT_ID; import static com.google.auth.oauth2.UserCredentialsTest.CLIENT_SECRET; import static com.google.auth.oauth2.UserCredentialsTest.REFRESH_TOKEN; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import ch.qos.logback.classic.spi.ILoggingEvent; import com.google.api.client.http.HttpStatusCodes; @@ -83,7 +83,8 @@ private TestAppender setupTestLogger(Class clazz) { return testAppender; } - @BeforeAll static void setup() { + @BeforeAll + static void setup() { // mimic GOOGLE_SDK_JAVA_LOGGING = true TestEnvironmentProvider testEnvironmentProvider = new TestEnvironmentProvider(); testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); @@ -91,8 +92,7 @@ private TestAppender setupTestLogger(Class clazz) { } @Test - void userCredentials_getRequestMetadata_fromRefreshToken_hasAccessToken() - throws IOException { + void userCredentials_getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(UserCredentials.class); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -258,7 +258,8 @@ void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatches testAppender.stop(); } - @Test() void impersonatedCredentials_refreshAccessToken_success() + @Test() + void impersonatedCredentials_refreshAccessToken_success() throws IOException, IllegalStateException { TestAppender testAppender = setupTestLogger(ImpersonatedCredentials.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = @@ -520,4 +521,4 @@ void idTokenWithAudience_full() throws IOException { testAppender.events.get(2).getKeyValuePairs().get(0).value); testAppender.stop(); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java index bb95cd4aa..c746a19de 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,7 +41,8 @@ class LoggingUtilsTest { private TestEnvironmentProvider testEnvironmentProvider; - @BeforeEach void setup() { + @BeforeEach + void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } @@ -62,4 +64,4 @@ void testIsLoggingEnabled_defaultToFalse() { LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); assertFalse(LoggingUtils.isLoggingEnabled()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java index fa2db6545..2a602b153 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.auth.CredentialTypeForMetrics; import com.google.auth.oauth2.MetricsUtils.RequestType; import java.util.regex.Pattern; @@ -83,4 +84,4 @@ void getGoogleCredentialsMetricsHeaderTest() { RequestType.UNTRACKED, CredentialTypeForMetrics.DO_NOT_SEND); assertPatterns(metricsStringNoTypes, VERSION_PATTERN); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java index ee51b4e1f..ce36548e2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java @@ -66,4 +66,4 @@ int runTasksExhaustively() { int numTasks() { return tasks.size(); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java index 5d4f41ed1..fc9f8ba3e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java @@ -34,6 +34,7 @@ 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; import com.google.api.client.json.GenericJson; @@ -298,4 +299,4 @@ public void setExpireTime(String expireTime) { public void setMetadataServerContentType(String contentType) { this.metadataServerContentType = contentType; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java b/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java index c6d0f7fea..00976e00f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockHttpTransportFactory.java @@ -12,4 +12,4 @@ public class MockHttpTransportFactory implements HttpTransportFactory { public HttpTransport create() { return transport; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java index de34a253e..cbd57d115 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransport.java @@ -228,4 +228,4 @@ public LowLevelHttpResponse execute() throws IOException { return this.request; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java index 4bc3c9154..a1df56b4b 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockIAMCredentialsServiceTransportFactory.java @@ -53,4 +53,4 @@ public MockIAMCredentialsServiceTransport getTransport() { public HttpTransport create() { return transport; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java index 650951c3d..725a124fc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java @@ -352,4 +352,4 @@ protected boolean isMtlsConfigRequestUrl(String url) { ComputeEngineCredentials.getMetadataServerUrl() + SecureSessionAgent.S2A_CONFIG_ENDPOINT_POSTFIX); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java b/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java index 82884b82c..0d98a9a8e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockRequestMetadataCallback.java @@ -78,4 +78,4 @@ private void checkNotSet() { Preconditions.checkState(this.metadata == null); Preconditions.checkState(this.exception == null); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java index 52e3d5376..cdb0a068e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java @@ -33,6 +33,7 @@ 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; import com.google.api.client.http.LowLevelHttpResponse; @@ -200,4 +201,4 @@ public void setReturnAccessBoundarySessionKey(boolean returnAccessBoundarySessio public int getRequestCount() { return requestCount; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java index 60af67959..3ef4df2fe 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenCheckingTransport.java @@ -92,4 +92,4 @@ private MockLowLevelHttpResponse makeSuccessResponse() { successResponse.setContent(SUCCESS_CONTENT); return successResponse; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java index b16cac1be..a61c185b5 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java @@ -437,4 +437,4 @@ private void validateAdditionalParameters(Map query) { } } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java index 66220d164..a1d5831ad 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransportFactory.java @@ -11,4 +11,4 @@ public class MockTokenServerTransportFactory implements HttpTransportFactory { public HttpTransport create() { return transport; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java index 25ce4bf5c..a54765abc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java @@ -31,6 +31,7 @@ package com.google.auth.oauth2; +import static java.util.concurrent.TimeUnit.HOURS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -39,7 +40,6 @@ 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 static java.util.concurrent.TimeUnit.HOURS; import com.google.api.client.util.Clock; import com.google.auth.TestClock; @@ -74,10 +74,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; /** Test case for {@link OAuth2Credentials}. */ - class OAuth2CredentialsTest extends BaseSerializationTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @@ -88,11 +86,13 @@ class OAuth2CredentialsTest extends BaseSerializationTest { private ExecutorService realExecutor; - @BeforeEach void setUp() { + @BeforeEach + void setUp() { realExecutor = Executors.newCachedThreadPool(); } - @AfterEach void tearDown() { + @AfterEach + void tearDown() { realExecutor.shutdown(); } @@ -417,8 +417,7 @@ void getRequestMetadata_async() throws IOException { } @Test - 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); @@ -669,17 +668,12 @@ public Map> call() throws Exception { // Get the error that getRequestMetadata(uri) created Throwable actualBlockingError = - assertThrows( - ExecutionException.class, - () -> blockingCall.get()) - .getCause(); + assertThrows(ExecutionException.class, () -> blockingCall.get()).getCause(); assertEquals(error, actualBlockingError); RuntimeException actualAsyncError = - assertThrows( - RuntimeException.class, - () -> callback1.awaitResult()); + assertThrows(RuntimeException.class, () -> callback1.awaitResult()); assertEquals(error, actualAsyncError); } @@ -862,7 +856,8 @@ void serialize() throws IOException, ClassNotFoundException { } @Test - @Disabled void updateTokenValueBeforeWake() throws IOException, InterruptedException { + @Disabled + void updateTokenValueBeforeWake() throws IOException, InterruptedException { final SettableFuture refreshedTokenFuture = SettableFuture.create(); AccessToken refreshedToken = new AccessToken("2/MkSJoj1xsli0AccessToken_NKPY2", null); refreshedTokenFuture.set(refreshedToken); @@ -970,4 +965,4 @@ public void onChanged(OAuth2Credentials credentials) throws IOException { callCount++; } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java index 782499c24..2c285c549 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -31,10 +31,10 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; import static com.google.auth.oauth2.OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN; import static com.google.auth.oauth2.OAuth2Credentials.DEFAULT_REFRESH_MARGIN; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import com.google.auth.TestUtils; import java.io.IOException; @@ -47,7 +47,6 @@ import org.junit.jupiter.api.Test; /** Tests for {@link OAuth2CredentialsWithRefresh}. */ - class OAuth2CredentialsWithRefreshTest { private static final AccessToken ACCESS_TOKEN = new AccessToken("accessToken", new Date()); @@ -224,4 +223,4 @@ public AccessToken refreshAccessToken() { TestUtils.assertContainsBearerToken(metadata, refreshedToken.getTokenValue()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java index f1b65b3cd..f540ac41d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; +import static com.google.auth.oauth2.OAuth2Utils.generateBasicAuthHeader; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static com.google.auth.oauth2.OAuth2Utils.generateBasicAuthHeader; import org.junit.jupiter.api.Test; @@ -98,4 +98,4 @@ void testNullPassword_throws() { generateBasicAuthHeader(username, password); }); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java index d5f0f3b89..e70ba6851 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java @@ -33,12 +33,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; + import com.google.auth.TestUtils; import java.io.IOException; import org.junit.jupiter.api.Test; /** Tests for {@link OAuthException}. */ - final class OAuthExceptionTest { private static final String FULL_MESSAGE_FORMAT = "Error code %s: %s - %s"; @@ -129,4 +129,4 @@ void createFromHttpResponseException_baseFormat() throws IOException { String expectedMessage = String.format(BASE_MESSAGE_FORMAT, "errorCode"); assertEquals(expectedMessage, e.getMessage()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java index a830987de..9832c7821 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java @@ -31,12 +31,12 @@ package com.google.auth.oauth2; +import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; +import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; 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 static org.junit.jupiter.api.Assertions.fail; -import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; -import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -642,4 +642,4 @@ static InputStream writeCredentialsStream(String tokenUrl) throws IOException { json.put("credential_source", credentialSource); return TestUtils.jsonToInputStream(json); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java index 4cf42d86d..f924d4137 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; + import org.junit.jupiter.api.Test; /** Tests for {@link PluggableAuthException}. */ @@ -67,4 +68,4 @@ void getMessage() { String expectedMessage = String.format("Error code %s: %s", "errorCode", "errorDescription"); assertEquals(expectedMessage, e.getMessage()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java index 9ac4e40f4..c31266d27 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthHandlerTest.java @@ -42,7 +42,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.mockito.Mockito; import com.google.api.client.json.GenericJson; import com.google.auth.oauth2.ExecutableHandler.ExecutableOptions; import com.google.auth.oauth2.PluggableAuthHandler.InternalProcessBuilder; @@ -59,8 +58,8 @@ import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; - import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; /** Unit tests for {@link PluggableAuthHandler}. */ @@ -190,8 +189,7 @@ void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedE } @Test - void retrieveTokenFromExecutable_errorResponse_throws() - throws InterruptedException, IOException { + void retrieveTokenFromExecutable_errorResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -356,9 +354,8 @@ public String getOutputFilePath() { } @Test - void - retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() - throws InterruptedException, IOException { + void retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -856,8 +853,7 @@ void getExecutableResponse_errorResponse() throws IOException, InterruptedExcept } @Test - void getExecutableResponse_timeoutExceeded_throws() - throws InterruptedException, IOException { + void getExecutableResponse_timeoutExceeded_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -887,8 +883,7 @@ void getExecutableResponse_timeoutExceeded_throws() } @Test - void getExecutableResponse_nonZeroExitCode_throws() - throws InterruptedException, IOException { + void getExecutableResponse_nonZeroExitCode_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -921,8 +916,7 @@ void getExecutableResponse_nonZeroExitCode_throws() } @Test - void getExecutableResponse_processInterrupted_throws() - throws InterruptedException, IOException { + void getExecutableResponse_processInterrupted_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -954,8 +948,7 @@ void getExecutableResponse_processInterrupted_throws() } @Test - void getExecutableResponse_invalidResponse_throws() - throws InterruptedException, IOException { + void getExecutableResponse_invalidResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -1044,4 +1037,4 @@ Process start() { } }; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java index 4da447f1b..b9249517c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java @@ -32,10 +32,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; /** Test cases for {@linkSecureSessionAgentConfig}. */ - class SecureSessionAgentConfigTest { private static final String S2A_PLAINTEXT_ADDRESS = "plaintext"; private static final String S2A_MTLS_ADDRESS = "mtls"; @@ -57,4 +57,4 @@ void createEmptyS2AConfig_success() { assertTrue(config.getPlaintextAddress().isEmpty()); assertTrue(config.getMtlsAddress().isEmpty()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java index 6022178d3..8f66a90b8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java @@ -32,13 +32,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; + import com.google.api.client.http.HttpStatusCodes; import com.google.auth.oauth2.ComputeEngineCredentialsTest.MockMetadataServerTransportFactory; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.Test; /** Test cases for {@link SecureSessionAgent}. */ - class SecureSessionAgentTest { private static final String INVALID_JSON_KEY = "invalid_key"; @@ -145,4 +145,4 @@ void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddress() { assertEquals(S2A_PLAINTEXT_ADDRESS, plaintextS2AAddress); assertTrue(mtlsS2AAddress.isEmpty()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 7bc91cfdd..2c516a9b2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -41,6 +41,7 @@ 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.http.HttpResponseException; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.json.GenericJson; @@ -82,7 +83,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ - class ServiceAccountCredentialsTest extends BaseSerializationTest { static final String CLIENT_EMAIL = @@ -365,8 +365,7 @@ void createAssertionForIdToken_incorrect() throws IOException { } @Test - void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() - throws IOException { + void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() throws IOException { GoogleCredentials credentials = createDefaultBuilderWithToken(ACCESS_TOKEN).build(); // No aud, no scopes gives an exception. @@ -890,8 +889,7 @@ void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOExce } @Test - void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() - throws IOException { + void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -1901,4 +1899,4 @@ private static void testFromStreamException(InputStream stream, String expectedM assertTrue(expected.getMessage().contains(expectedMessageContent)); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index e2185f1b3..8d6966631 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -31,6 +31,7 @@ package com.google.auth.oauth2; +import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -40,7 +41,6 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import static com.google.auth.Credentials.GOOGLE_DEFAULT_UNIVERSE; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -68,7 +68,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ - class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { private static final String SA_CLIENT_EMAIL = @@ -1002,4 +1001,4 @@ private GenericJson writeServiceAccountJson( json.put("type", GoogleCredentialsInfo.SERVICE_ACCOUNT_CREDENTIALS.getFileType()); return json; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java index 5c7b44bd6..99b7e81c4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java @@ -62,7 +62,8 @@ class Slf4jUtilsLogbackTest { private TestEnvironmentProvider testEnvironmentProvider; - @BeforeEach void setup() { + @BeforeEach + void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } @@ -149,7 +150,9 @@ void testLogGenericData() { assertEquals(2, keyValuePairs.size()); for (KeyValuePair kvp : keyValuePairs) { - assertTrue(kvp.key.equals("key1", "Key should be either 'key1' or 'token'") || kvp.key.equals("token")); + assertTrue( + kvp.key.equals("key1", "Key should be either 'key1' or 'token'") + || kvp.key.equals("token")); } testAppender.stop(); @@ -210,4 +213,4 @@ private TestAppender setupTestLogger() { ((ch.qos.logback.classic.Logger) LOGGER).addAppender(testAppender); return testAppender; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java index 9ae400da4..c3ee5b872 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java @@ -52,7 +52,8 @@ class Slf4jUtilsTest { private TestEnvironmentProvider testEnvironmentProvider; - @BeforeEach void setup() { + @BeforeEach + void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } @@ -115,4 +116,4 @@ void testMatchLevelSevere() { assertEquals( org.slf4j.event.Level.TRACE, Slf4jLoggingHelpers.matchUtilLevelToSLF4JLevel(Level.FINER)); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java index 0bd03b1ce..6607403a4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java @@ -34,6 +34,7 @@ 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; import com.google.api.client.util.GenericData; @@ -46,10 +47,8 @@ import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; /** Tests for {@link StsRequestHandler}. */ - final class StsRequestHandlerTest { private static final String TOKEN_EXCHANGE_GRANT_TYPE = @@ -60,7 +59,8 @@ final class StsRequestHandlerTest { private MockStsTransport transport; - @BeforeEach void setup() { + @BeforeEach + void setup() { transport = new MockStsTransport(); } @@ -176,10 +176,7 @@ void exchangeToken_throwsException() throws IOException { TestUtils.buildHttpResponseException( "invalidRequest", /* errorDescription= */ null, /* errorUri= */ null)); - OAuthException e = - assertThrows( - OAuthException.class, - () -> requestHandler.exchangeToken()); + OAuthException e = assertThrows(OAuthException.class, () -> requestHandler.exchangeToken()); assertEquals("invalidRequest", e.getErrorCode()); assertNull(e.getErrorDescription()); @@ -199,10 +196,7 @@ void exchangeToken_withOptionalParams_throwsException() throws IOException { transport.addResponseErrorSequence( TestUtils.buildHttpResponseException("invalidRequest", "errorDescription", "errorUri")); - OAuthException e = - assertThrows( - OAuthException.class, - () -> requestHandler.exchangeToken()); + OAuthException e = assertThrows(OAuthException.class, () -> requestHandler.exchangeToken()); assertEquals("invalidRequest", e.getErrorCode()); assertEquals("errorDescription", e.getErrorDescription()); @@ -223,9 +217,7 @@ void exchangeToken_ioException() { transport.addResponseErrorSequence(e); IOException thrownException = - assertThrows( - IOException.class, - () -> requestHandler.exchangeToken()); + assertThrows(IOException.class, () -> requestHandler.exchangeToken()); assertEquals(e, thrownException); } @@ -273,4 +265,4 @@ void exchangeToken_withAccessBoundarySessionKey() throws IOException { // Validate response. assertEquals(transport.getAccessBoundarySessionKey(), response.getAccessBoundarySessionKey()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java b/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java index d0101d3ba..aef72daa7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java @@ -50,4 +50,4 @@ protected void append(ILoggingEvent eventObject) { public void clearEvents() { events.clear(); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java b/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java index a5acb238f..9e6de1108 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestEnvironmentProvider.java @@ -16,4 +16,4 @@ public TestEnvironmentProvider setEnv(String name, String value) { environmentVariables.put(name, value); return this; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java b/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java index 6a3aec7ce..4efc138bb 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java @@ -33,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.List; import java.util.Map; @@ -68,4 +69,4 @@ static void validateMetricsHeader( } assertEquals(expectedMetricsValue, actualMetricsValue); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index c133210f9..6872214f0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java @@ -34,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; @@ -290,7 +291,8 @@ void verifyRs256TokenWithLegacyCertificateUrlFormat() } @Test - @Disabled void verifyServiceAccountRs256Token() throws VerificationException { + @Disabled + void verifyServiceAccountRs256Token() throws VerificationException { final Clock clock = new Clock() { @Override @@ -339,4 +341,4 @@ public LowLevelHttpResponse execute() throws IOException { } }; } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java index cfa9708f1..050a9d199 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java @@ -31,6 +31,8 @@ package com.google.auth.oauth2; +import static com.google.auth.TestUtils.WORKFORCE_IDENTITY_FEDERATION_AUTH_URI; +import static com.google.auth.TestUtils.WORKFORCE_IDENTITY_FEDERATION_TOKEN_SERVER_URI; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -39,8 +41,6 @@ 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 static com.google.auth.TestUtils.WORKFORCE_IDENTITY_FEDERATION_AUTH_URI; -import static com.google.auth.TestUtils.WORKFORCE_IDENTITY_FEDERATION_TOKEN_SERVER_URI; import com.google.auth.TestUtils; import com.google.auth.http.HttpTransportFactory; @@ -58,7 +58,6 @@ import org.junit.jupiter.api.Test; /** Unit Tests for UserAuthorizer */ - class UserAuthorizerTest { private static final String CLIENT_ID_VALUE = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @@ -150,13 +149,18 @@ void constructorWithClientAuthenticationTypeNone() { void constructorCommon_nullClientId_throws() { assertThrows( NullPointerException.class, - () -> UserAuthorizer.newBuilder().setScopes(DUMMY_SCOPES).setCallbackUri(CALLBACK_URI).build()); + () -> + UserAuthorizer.newBuilder() + .setScopes(DUMMY_SCOPES) + .setCallbackUri(CALLBACK_URI) + .build()); } @Test void constructorCommon_nullScopes_throws() { assertThrows( - NullPointerException.class, () -> UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build()); + NullPointerException.class, + () -> UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build()); } @Test @@ -388,8 +392,7 @@ void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { } @Test - void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() - throws IOException { + void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); // Missing access token. @@ -648,7 +651,8 @@ void getCredentialsFromCode_nullCode_throws() throws IOException { .setTokenStore(new MemoryTokensStorage()) .build(); - assertThrows(NullPointerException.class, () -> authorizer.getCredentialsFromCode(null, BASE_URI)); + assertThrows( + NullPointerException.class, () -> authorizer.getCredentialsFromCode(null, BASE_URI)); } @Test @@ -906,4 +910,4 @@ void testTokenResponseWithConfig_noRefreshToken() { assertEquals(httpTransportFactory, tokenResponse.getHttpTransportFactory()); assertNull(tokenResponse.getRefreshToken()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index 9868e9d7c..e5a6c658a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -40,6 +40,7 @@ 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.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Clock; @@ -66,7 +67,6 @@ import org.junit.jupiter.api.Test; /** Test case for {@link UserCredentials}. */ - class UserCredentialsTest extends BaseSerializationTest { static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @@ -87,7 +87,11 @@ class UserCredentialsTest extends BaseSerializationTest { void constructor_accessAndRefreshTokenNull_throws() { assertThrows( IllegalStateException.class, - () -> UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build()); + () -> + UserCredentials.newBuilder() + .setClientId(CLIENT_ID) + .setClientSecret(CLIENT_SECRET) + .build()); } @Test @@ -947,4 +951,4 @@ private static void testFromStreamException(InputStream stream, String expectedM assertTrue(expected.getMessage().contains(expectedMessageContent)); } } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java index 1121b82f7..1a27d3cdc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java @@ -35,6 +35,7 @@ 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 com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.auth.oauth2.AccessToken; @@ -101,4 +102,4 @@ void FetchIdToken() throws Exception { assertEquals(computeUrl, jws.getPayload().get("aud")); assertEquals("https://accounts.google.com", jws.getPayload().get("iss")); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java index 865abc3f2..034507e07 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTQuotaProjectId.java @@ -32,6 +32,7 @@ package com.google.auth.oauth2.functional; import static org.junit.jupiter.api.Assertions.assertEquals; + import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import com.google.auth.oauth2.GoogleCredentials; @@ -62,4 +63,4 @@ void validate_quota_from_environment_not_used() throws IOException { // Validate that the quota project from the json is used instead of environment value assertEquals("quota_from_file", credentials.getQuotaProjectId()); } -} \ No newline at end of file +} diff --git a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java index 875fb5a37..ca0ec4fc1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java @@ -36,6 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; + import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; @@ -187,4 +188,4 @@ private HttpResponse executeRequestWithCredentialsWithScope(String serviceUrl, S HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl); return request.execute(); } -} \ No newline at end of file +} From 7699c29ea257ce426d94a1bbc74cec7918d76bf0 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 14:29:23 -0500 Subject: [PATCH 04/19] chore: Add junit ignore deps for dependency plugin --- appengine/pom.xml | 7 ++++++- cab-token-generator/pom.xml | 7 ++++++- credentials/pom.xml | 7 ++++++- oauth2_http/pom.xml | 17 +++++++---------- pom.xml | 14 ++++++++------ 5 files changed, 33 insertions(+), 19 deletions(-) diff --git a/appengine/pom.xml b/appengine/pom.xml index 8199e0676..00b623f07 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -65,7 +65,12 @@ org.junit.jupiter - junit-jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/cab-token-generator/pom.xml b/cab-token-generator/pom.xml index e3a31c722..1e0f72af6 100644 --- a/cab-token-generator/pom.xml +++ b/cab-token-generator/pom.xml @@ -59,7 +59,12 @@ org.junit.jupiter - junit-jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/credentials/pom.xml b/credentials/pom.xml index 3bb116ac0..225b77bc7 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -47,7 +47,12 @@ org.junit.jupiter - junit-jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index de9c62a42..d07518f88 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -23,7 +23,7 @@ - junit47 + junit true @@ -186,14 +186,6 @@ org.apache.maven.plugins maven-javadoc-plugin - - org.apache.maven.plugins - maven-dependency-plugin - - com.google.auto.value:auto-value - - - org.apache.maven.plugins maven-jar-plugin @@ -324,7 +316,12 @@ org.junit.jupiter - junit-jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/pom.xml b/pom.xml index 77d5d94a1..a9c6f9c36 100644 --- a/pom.xml +++ b/pom.xml @@ -157,12 +157,6 @@ pom import - - org.junit.jupiter - junit-jupiter - ${project.junit.version} - test - com.google.appengine appengine @@ -410,6 +404,14 @@ maven-resources-plugin 3.3.1 + + org.apache.maven.plugins + maven-dependency-plugin + + + org.junit.jupiter:junit-jupiter-engine + + From 24872140f5628d3a8d18c7a4b97855d8042cbf4a Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 14:34:32 -0500 Subject: [PATCH 05/19] chore: Fix samples imports to use new junit and truth --- samples/snippets/pom.xml | 13 ++++++++++++- samples/snippets/src/test/java/SnippetsIT.java | 12 ++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 14944baff..370d127c2 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -77,9 +77,20 @@ software.amazon.awssdk regions + + com.google.truth + truth + 1.4.5 + + + org.junit.jupiter + junit-jupiter-api + 5.11.4 + test + org.junit.jupiter - junit-jupiter + junit-jupiter-engine 5.11.4 test diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index 992e15db6..5dd58d5d2 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -46,7 +46,8 @@ static void requireEnvVar(String envVarName) { .isNotEmpty(); } - @BeforeAll static void setup() throws IOException { + @BeforeAll + static void setup() throws IOException { final PrintStream out = System.out; ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); @@ -57,14 +58,17 @@ static void requireEnvVar(String envVarName) { System.setOut(out); } - @AfterAll static void cleanup() {} + @AfterAll + static void cleanup() {} - @BeforeEach void beforeEach() { + @BeforeEach + void beforeEach() { stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); } - @AfterEach void afterEach() { + @AfterEach + void afterEach() { stdOut = null; System.setOut(null); } From 61dcc637ac59d3d63b53832d3a8329bfe8353de9 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 14:39:42 -0500 Subject: [PATCH 06/19] chore: Fix invalid test --- .../com/google/auth/oauth2/Slf4jUtilsLogbackTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java index 99b7e81c4..fd8ad94af 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java @@ -149,10 +149,9 @@ void testLogGenericData() { List keyValuePairs = testAppender.events.get(0).getKeyValuePairs(); assertEquals(2, keyValuePairs.size()); for (KeyValuePair kvp : keyValuePairs) { - assertTrue( - kvp.key.equals("key1", "Key should be either 'key1' or 'token'") - || kvp.key.equals("token")); + kvp.key.equals("key1") || kvp.key.equals("token"), + "Key should be either 'key1' or 'token'"); } testAppender.stop(); From 9a694b347955b33f82dbbac8ed5409c9b2b44efa Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 14:45:01 -0500 Subject: [PATCH 07/19] chore: Address some sonatype code smells --- .../appengine/AppEngineCredentialsTest.java | 24 +++++++++---------- .../auth/mtls/SecureConnectProviderTest.java | 11 ++++----- .../auth/oauth2/AppEngineCredentialsTest.java | 17 ++++++------- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index c52c65c46..7a0ba8ddf 100644 --- a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java +++ b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java @@ -34,6 +34,7 @@ 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.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -56,7 +57,7 @@ /** Unit tests for AppEngineCredentials */ class AppEngineCredentialsTest extends BaseSerializationTest { - private static Collection SCOPES = + private static final Collection SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope1", "scope2")); private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); private static final String EXPECTED_ACCOUNT = "serviceAccount"; @@ -97,7 +98,7 @@ void refreshAccessToken_sameAs() throws IOException { } @Test - void getAccount_sameAs() throws IOException { + void getAccount_sameAs() { MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setServiceAccountName(EXPECTED_ACCOUNT); AppEngineCredentials credentials = @@ -109,7 +110,7 @@ void getAccount_sameAs() throws IOException { } @Test - void sign_sameAs() throws IOException { + void sign_sameAs() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setSignature(expectedSignature); @@ -152,7 +153,7 @@ void createScoped_clonesWithScopes() throws IOException { } @Test - void equals_true() throws IOException { + void equals_true() { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -166,13 +167,12 @@ void equals_true() throws IOException { .setScopes(emptyScopes) .setAppIdentityService(appIdentity) .build(); - assertTrue(credentials.equals(credentials)); - assertTrue(credentials.equals(otherCredentials)); - assertTrue(otherCredentials.equals(credentials)); + assertEquals(credentials, otherCredentials); + assertEquals(otherCredentials, credentials); } @Test - void equals_false_scopes() throws IOException { + void equals_false_scopes() { Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -187,12 +187,12 @@ void equals_false_scopes() throws IOException { .setScopes(scopes) .setAppIdentityService(appIdentity) .build(); - assertFalse(credentials.equals(otherCredentials)); - assertFalse(otherCredentials.equals(credentials)); + assertNotEquals(credentials, otherCredentials); + assertNotEquals(otherCredentials, credentials); } @Test - void toString_containsFields() throws IOException { + void toString_containsFields() { String expectedToString = String.format( "AppEngineCredentials{scopes=[%s], scopesRequired=%b, appIdentityServiceClassName=%s}", @@ -210,7 +210,7 @@ void toString_containsFields() throws IOException { } @Test - void hashCode_equals() throws IOException { + void hashCode_equals() { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = diff --git a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java index 5f796fc16..7e962014a 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java @@ -46,8 +46,8 @@ class SecureConnectProviderTest { private static class TestCertProviderCommandProcess extends Process { - private boolean runForever; - private int exitValue; + private final boolean runForever; + private final int exitValue; public TestCertProviderCommandProcess(int exitValue, boolean runForever) { this.runForever = runForever; @@ -88,7 +88,7 @@ public void destroy() {} static class TestProcessProvider implements SecureConnectProvider.ProcessProvider { - private int exitCode; + private final int exitCode; public TestProcessProvider(int exitCode) { this.exitCode = exitCode; @@ -101,8 +101,7 @@ public Process createProcess(InputStream metadata) throws IOException { } @Test - void testGetKeyStoreNonZeroExitCode() - throws IOException, InterruptedException, GeneralSecurityException { + void testGetKeyStoreNonZeroExitCode() { InputStream metadata = this.getClass() .getClassLoader() @@ -136,7 +135,7 @@ void testRunCertificateProviderCommandSuccess() throws IOException, InterruptedE } @Test - void testRunCertificateProviderCommandTimeout() throws InterruptedException { + void testRunCertificateProviderCommandTimeout() { Process certCommandProcess = new TestCertProviderCommandProcess(0, true); IOException actual = assertThrows( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index bb2bc1ff3..45884fc0d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -34,6 +34,8 @@ 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.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -60,7 +62,7 @@ class AppEngineCredentialsTest extends BaseSerializationTest { private static final Collection SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope1", "scope2")); private static final Collection DEFAULT_SCOPES = - Collections.unmodifiableCollection(Arrays.asList("scope3")); + Collections.singletonList("scope3"); @Test void constructor_usesAppIdentityService() throws IOException { @@ -75,14 +77,14 @@ void constructor_usesAppIdentityService() throws IOException { } @Test - void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { + void constructor_noAppEngineRuntime_throwsHelpfulLoadError() { try { new TestAppEngineCredentialsNoSdk(); fail("Credential expected to fail to load if credential class not present."); } catch (IOException e) { String message = e.getMessage(); assertTrue(message.contains("Check that the App Engine SDK is deployed.")); - assertTrue(e.getCause() instanceof ClassNotFoundException); + assertInstanceOf(ClassNotFoundException.class, e.getCause()); assertTrue( e.getCause() .getMessage() @@ -152,9 +154,8 @@ void createScoped_defaultScopes() throws IOException { void equals_true() throws IOException { GoogleCredentials credentials = new TestAppEngineCredentials(SCOPES); GoogleCredentials otherCredentials = new TestAppEngineCredentials(SCOPES); - assertTrue(credentials.equals(credentials)); - assertTrue(credentials.equals(otherCredentials)); - assertTrue(otherCredentials.equals(credentials)); + assertEquals(credentials, otherCredentials); + assertEquals(otherCredentials, credentials); } @Test @@ -163,8 +164,8 @@ void equals_false_scopes() throws IOException { Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(emptyScopes); AppEngineCredentials otherCredentials = new TestAppEngineCredentials(scopes); - assertFalse(credentials.equals(otherCredentials)); - assertFalse(otherCredentials.equals(credentials)); + assertNotEquals(credentials, otherCredentials); + assertNotEquals(otherCredentials, credentials); } @Test From 164b6c5f0d545d2f19dc0d1e1b1bdb1ecbe6ecde Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 14:53:25 -0500 Subject: [PATCH 08/19] chore: Fix lint issues --- .../com/google/auth/appengine/AppEngineCredentialsTest.java | 1 - .../com/google/auth/oauth2/AppEngineCredentialsTest.java | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index 7a0ba8ddf..05f81d578 100644 --- a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java +++ b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java @@ -33,7 +33,6 @@ 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.assertNotSame; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index 45884fc0d..43139e2be 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -61,8 +61,7 @@ class AppEngineCredentialsTest extends BaseSerializationTest { private static final Collection SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope1", "scope2")); - private static final Collection DEFAULT_SCOPES = - Collections.singletonList("scope3"); + private static final Collection DEFAULT_SCOPES = Collections.singletonList("scope3"); @Test void constructor_usesAppIdentityService() throws IOException { From 43f62473e8609dff98c2625f2a36960503e1de7c Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 15:23:18 -0500 Subject: [PATCH 09/19] chore: Remove unnecessary old junit profile --- oauth2_http/pom.xml | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index d07518f88..1ab15393c 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -22,29 +22,6 @@ - - junit - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - - - **/IT*.java - **/functional/*.java - - sponge_log - - - - - native-test From 588af191748641183b7b3a15b53aef2e4b31f435 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 2 Jan 2026 15:49:50 -0500 Subject: [PATCH 10/19] chore: Add junit5 platform runner --- oauth2_http/pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index 1ab15393c..8c3c25c08 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -197,6 +197,13 @@ org.apache.maven.plugins maven-failsafe-plugin 3.5.3 + + + org.apache.maven.surefire + surefire-junit-platform + 3.5.2 + + 1200 sponge_log From 9bc91f1fa8eb8433dccce47fb8f65c897f97a9dd Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Sat, 3 Jan 2026 15:02:59 -0500 Subject: [PATCH 11/19] chore: Add junit4 test dep back --- cab-token-generator/pom.xml | 1 - oauth2_http/pom.xml | 12 ++++++++++-- pom.xml | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/cab-token-generator/pom.xml b/cab-token-generator/pom.xml index 1e0f72af6..cee7c3db7 100644 --- a/cab-token-generator/pom.xml +++ b/cab-token-generator/pom.xml @@ -77,7 +77,6 @@ org.mockito mockito-core - 4.11.0 test diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index 8c3c25c08..d2e3f078a 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -196,12 +196,12 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.3 + ${surefire.version} org.apache.maven.surefire surefire-junit-platform - 3.5.2 + ${surefire.version} @@ -298,6 +298,14 @@ com.google.api api-common + + + + junit + junit + 4.13.2 + test + org.junit.jupiter junit-jupiter-api diff --git a/pom.xml b/pom.xml index a9c6f9c36..bc7fbbea8 100644 --- a/pom.xml +++ b/pom.xml @@ -293,7 +293,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.2 + ${surefire.version} sponge_log From 07dafe0150dcf34f4b10a4cb38d5539f2496b074 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Sat, 3 Jan 2026 15:18:27 -0500 Subject: [PATCH 12/19] chore: Add junit4 to ignore in dependency check --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index bc7fbbea8..5d5e4ae83 100644 --- a/pom.xml +++ b/pom.xml @@ -408,6 +408,10 @@ org.apache.maven.plugins maven-dependency-plugin + + + + junit:junit org.junit.jupiter:junit-jupiter-engine From 9ee9246f13afa6f10d92eef7410f99b1ad008d75 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Sat, 3 Jan 2026 15:35:14 -0500 Subject: [PATCH 13/19] chore: Add junit4 to ignore in dependency check --- pom.xml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 5d5e4ae83..4da5388cb 100644 --- a/pom.xml +++ b/pom.xml @@ -408,12 +408,14 @@ org.apache.maven.plugins maven-dependency-plugin - - - - junit:junit - - org.junit.jupiter:junit-jupiter-engine + + + + + junit:junit + + org.junit.jupiter:junit-jupiter-engine + From 9d2286ee6ae1503c737fa50e9472a1aa9271f333 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 5 Jan 2026 10:49:41 -0500 Subject: [PATCH 14/19] chore: Add junit4 tests to CAB module --- cab-token-generator/pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/cab-token-generator/pom.xml b/cab-token-generator/pom.xml index cee7c3db7..b044a6fb6 100644 --- a/cab-token-generator/pom.xml +++ b/cab-token-generator/pom.xml @@ -57,6 +57,14 @@ + + + + junit + junit + 4.13.2 + test + org.junit.jupiter junit-jupiter-api From 51908664d6a89a4f9d9121d240ba051e9674dd8b Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 5 Jan 2026 11:27:23 -0500 Subject: [PATCH 15/19] chore: Remove hamcrest dependency --- .../com/google/auth/http/HttpCredentialsAdapterTest.java | 5 ++--- oauth2_http/pom.xml | 6 ------ 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index e99f7f682..10d2141fd 100644 --- a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java +++ b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java @@ -31,9 +31,8 @@ package com.google.auth.http; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; @@ -168,6 +167,6 @@ void getCredentials() { HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials); Credentials returnedCredentials = adapter.getCredentials(); - assertThat(returnedCredentials, instanceOf(Credentials.class)); + assertInstanceOf(Credentials.class, returnedCredentials); } } diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index d2e3f078a..92bdc6a94 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -316,12 +316,6 @@ junit-jupiter-engine test - - org.hamcrest - hamcrest-core - 1.3 - test - org.mockito mockito-core From 5137ce2ea187140dcd53be14e0e0b41dbcf0b4d4 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 5 Jan 2026 15:26:26 -0500 Subject: [PATCH 16/19] chore: Revert Junit5 changes in samples directory --- samples/snippets/pom.xml | 18 -------- .../snippets/src/test/java/SnippetsIT.java | 43 ++++++++++--------- 2 files changed, 23 insertions(+), 38 deletions(-) diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 370d127c2..941191a80 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -77,24 +77,6 @@ software.amazon.awssdk regions - - com.google.truth - truth - 1.4.5 - - - org.junit.jupiter - junit-jupiter-api - 5.11.4 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.11.4 - test - - diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index 5dd58d5d2..e4df3e255 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -27,27 +27,30 @@ import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -class SnippetsIT { +@RunWith(JUnit4.class) +public class SnippetsIT { private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String CREDENTIALS = System.getenv("GOOGLE_APPLICATION_CREDENTIALS"); private ByteArrayOutputStream stdOut; // Check if the required environment variables are set. - static void requireEnvVar(String envVarName) { + public static void requireEnvVar(String envVarName) { assertWithMessage(String.format("Missing environment variable '%s' ", envVarName)) .that(System.getenv(envVarName)) .isNotEmpty(); } - @BeforeAll - static void setup() throws IOException { + @BeforeClass + public static void setup() throws IOException { final PrintStream out = System.out; ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); @@ -58,17 +61,17 @@ static void setup() throws IOException { System.setOut(out); } - @AfterAll - static void cleanup() {} + @AfterClass + public static void cleanup() {} - @BeforeEach - void beforeEach() { + @Before + public void beforeEach() { stdOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(stdOut)); } - @AfterEach - void afterEach() { + @After + public void afterEach() { stdOut = null; System.setOut(null); } @@ -91,13 +94,13 @@ private static String getIdTokenFromServiceAccount( } @Test - void testIdTokenFromServiceAccount() throws IOException { + public void testIdTokenFromServiceAccount() throws IOException { IdTokenFromServiceAccount.getIdTokenFromServiceAccount(CREDENTIALS, "https://example.com"); assertThat(stdOut.toString()).contains("Generated ID token."); } @Test - void testVerifyGoogleIdToken() throws IOException { + public void testVerifyGoogleIdToken() throws IOException { String idToken = getIdTokenFromServiceAccount(CREDENTIALS, "https://example.com"); VerifyGoogleIdToken.verifyGoogleIdToken( @@ -105,19 +108,19 @@ void testVerifyGoogleIdToken() throws IOException { } @Test - void testIdTokenFromMetadataServer() throws GeneralSecurityException, IOException { + public void testIdTokenFromMetadataServer() throws GeneralSecurityException, IOException { IdTokenFromMetadataServer.getIdTokenFromMetadataServer("https://www.google.com"); assertThat(stdOut.toString()).contains("Generated ID token."); } @Test - void testAuthenticateImplicitWithAdc() throws IOException { + public void testAuthenticateImplicitWithAdc() throws IOException { AuthenticateImplicitWithAdc.authenticateImplicitWithAdc(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } @Test - void testAuthenticateExplicit() throws IOException { + public void testAuthenticateExplicit() throws IOException { AuthenticateExplicit.authenticateExplicit(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } From 28f41f8b86733b33991fb454844ae8a828f62a35 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 5 Jan 2026 15:28:13 -0500 Subject: [PATCH 17/19] chore: Revert Junit5 changes in samples directory --- samples/snippets/pom.xml | 2 +- samples/snippets/src/test/java/SnippetsIT.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 941191a80..5feb455e4 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -79,4 +79,4 @@ - + \ No newline at end of file diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index e4df3e255..ff4a66ae6 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -124,4 +124,4 @@ public void testAuthenticateExplicit() throws IOException { AuthenticateExplicit.authenticateExplicit(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } -} \ No newline at end of file +} From 1c39a2c2be58a914aed4f473ea828d25d3c30dda Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 5 Jan 2026 15:29:43 -0500 Subject: [PATCH 18/19] chore: Remove end of file whitespace --- samples/snippets/src/test/java/SnippetsIT.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index ff4a66ae6..e4df3e255 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -124,4 +124,4 @@ public void testAuthenticateExplicit() throws IOException { AuthenticateExplicit.authenticateExplicit(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } -} +} \ No newline at end of file From eabd9c506b5b730165ad8be1c8f9c75c3e8d094c Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 5 Jan 2026 15:31:24 -0500 Subject: [PATCH 19/19] chore: Remove whitespace --- samples/snippets/pom.xml | 3 ++- samples/snippets/src/test/java/SnippetsIT.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 5feb455e4..5b7217972 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -79,4 +79,5 @@ - \ No newline at end of file + + diff --git a/samples/snippets/src/test/java/SnippetsIT.java b/samples/snippets/src/test/java/SnippetsIT.java index e4df3e255..ff4a66ae6 100644 --- a/samples/snippets/src/test/java/SnippetsIT.java +++ b/samples/snippets/src/test/java/SnippetsIT.java @@ -124,4 +124,4 @@ public void testAuthenticateExplicit() throws IOException { AuthenticateExplicit.authenticateExplicit(PROJECT_ID); assertThat(stdOut.toString()).contains("Listed all storage buckets."); } -} \ No newline at end of file +}