diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index e1c3d5201..05f81d578 100644 --- a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java +++ b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.appengine; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.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; +import static org.junit.jupiter.api.Assertions.fail; import com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; @@ -51,21 +51,18 @@ 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 = + 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"; @Test - public void constructor_usesAppIdentityService() throws IOException { + void constructor_usesAppIdentityService() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -83,7 +80,7 @@ public void constructor_usesAppIdentityService() throws IOException { } @Test - public void refreshAccessToken_sameAs() throws IOException { + void refreshAccessToken_sameAs() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -100,7 +97,7 @@ public void refreshAccessToken_sameAs() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() { MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setServiceAccountName(EXPECTED_ACCOUNT); AppEngineCredentials credentials = @@ -112,7 +109,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setSignature(expectedSignature); @@ -125,7 +122,7 @@ public void sign_sameAs() throws IOException { } @Test - public void createScoped_clonesWithScopes() throws IOException { + void createScoped_clonesWithScopes() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; Collection emptyScopes = Collections.emptyList(); @@ -155,7 +152,7 @@ public void createScoped_clonesWithScopes() throws IOException { } @Test - public void equals_true() throws IOException { + void equals_true() { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -169,13 +166,12 @@ public 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 - public void equals_false_scopes() throws IOException { + void equals_false_scopes() { Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -190,12 +186,12 @@ public 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 - public void toString_containsFields() throws IOException { + void toString_containsFields() { String expectedToString = String.format( "AppEngineCredentials{scopes=[%s], scopesRequired=%b, appIdentityServiceClassName=%s}", @@ -213,7 +209,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -230,7 +226,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -249,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"); } } diff --git a/appengine/pom.xml b/appengine/pom.xml index fde9650c8..00b623f07 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -64,8 +64,13 @@ guava - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine 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..c42c15af5 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java @@ -32,10 +32,10 @@ package com.google.auth.credentialaccessboundary; 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.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.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -69,17 +69,14 @@ 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 +103,8 @@ public HttpTransport create() { } } - @Before - public void setUp() { + @BeforeEach + void setUp() { mockStsTransportFactory = new MockStsTransportFactory(); mockStsTransportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -117,7 +114,7 @@ public void setUp() { } @Test - public void fetchIntermediateCredentials() throws Exception { + void fetchIntermediateCredentials() throws Exception { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -146,7 +143,7 @@ public void fetchIntermediateCredentials() throws Exception { } @Test - public void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { + void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { String universeDomain = "foobar"; GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() @@ -168,7 +165,7 @@ public void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOExc } @Test - public void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() + void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() throws Exception { // Simulate error when refreshing the source credential. mockTokenServerTransportFactory.transport.setError(new IOException()); @@ -187,8 +184,7 @@ public void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOE } @Test - public void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() - throws Exception { + void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpiration() throws Exception { // Simulate STS not returning expires_in. mockStsTransportFactory.transport.setReturnExpiresIn(false); @@ -216,8 +212,7 @@ public void fetchIntermediateCredentials_noExpiresInReturned_copiesSourceExpirat } @Test - public void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() - throws IOException { + void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentials() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -236,7 +231,7 @@ public void refreshCredentialsIfRequired_firstCallWillFetchIntermediateCredentia } @Test - public void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { + void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.NONE); @@ -252,7 +247,7 @@ public void refreshCredentialsIfRequired_noRefreshNeeded() throws IOException { } @Test - public void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { + void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -274,7 +269,7 @@ public void refreshCredentialsIfRequired_blockingSingleThread() throws IOExcepti } @Test - public void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { + void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -309,8 +304,7 @@ public void refreshCredentialsIfRequired_asyncSingleThread() throws IOException } @Test - public void refreshCredentialsIfRequired_blockingMultiThread() - throws IOException, InterruptedException { + void refreshCredentialsIfRequired_blockingMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.BLOCKING); @@ -330,8 +324,7 @@ public void refreshCredentialsIfRequired_blockingMultiThread() } @Test - public void refreshCredentialsIfRequired_asyncMultiThread() - throws IOException, InterruptedException { + void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); @@ -358,7 +351,7 @@ public void refreshCredentialsIfRequired_asyncMultiThread() } @Test - public void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOException() + void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOException() throws Exception { // Simulate error when refreshing the source credential. mockTokenServerTransportFactory.transport.setError(new IOException()); @@ -378,7 +371,7 @@ public void refreshCredentialsIfRequired_sourceCredentialCannotRefresh_throwsIOE // Tests related to the builder methods. @Test - public void builder_noSourceCredential_throws() { + void builder_noSourceCredential_throws() { NullPointerException exception = assertThrows( NullPointerException.class, @@ -390,7 +383,7 @@ public void builder_noSourceCredential_throws() { } @Test - public void builder_minimumTokenLifetime_negative_throws() throws IOException { + void builder_minimumTokenLifetime_negative_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -405,7 +398,7 @@ public void builder_minimumTokenLifetime_negative_throws() throws IOException { } @Test - public void builder_minimumTokenLifetime_zero_throws() throws IOException { + void builder_minimumTokenLifetime_zero_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -420,7 +413,7 @@ public void builder_minimumTokenLifetime_zero_throws() throws IOException { } @Test - public void builder_refreshMargin_negative_throws() throws IOException { + void builder_refreshMargin_negative_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -435,7 +428,7 @@ public void builder_refreshMargin_negative_throws() throws IOException { } @Test - public void builder_refreshMargin_zero_throws() throws IOException { + void builder_refreshMargin_zero_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); IllegalArgumentException exception = @@ -450,7 +443,7 @@ public void builder_refreshMargin_zero_throws() throws IOException { } @Test - public void builder_setsCorrectDefaultValues() throws IOException { + void builder_setsCorrectDefaultValues() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); ClientSideCredentialAccessBoundaryFactory factory = @@ -465,7 +458,7 @@ public void builder_setsCorrectDefaultValues() throws IOException { } @Test - public void builder_universeDomainMismatch_throws() throws IOException { + void builder_universeDomainMismatch_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -483,7 +476,7 @@ public void builder_universeDomainMismatch_throws() throws IOException { } @Test - public void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { + void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -503,7 +496,7 @@ public void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws } @Test - public void builder_invalidRefreshMargin_throws() throws IOException { + void builder_invalidRefreshMargin_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -522,7 +515,7 @@ public void builder_invalidRefreshMargin_throws() throws IOException { } @Test - public void builder_invalidMinimumTokenLifetime_throws() throws IOException { + void builder_invalidMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -541,7 +534,7 @@ public void builder_invalidMinimumTokenLifetime_throws() throws IOException { } @Test - public void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException { + void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -557,7 +550,7 @@ public void builder_minimumTokenLifetimeNotSet_usesDefault() throws IOException } @Test - public void builder_refreshMarginNotSet_usesDefault() throws IOException { + void builder_refreshMarginNotSet_usesDefault() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(mockTokenServerTransportFactory); @@ -710,7 +703,7 @@ private static ClientSideAccessBoundary decryptRestriction(String restriction, S } @Test - public void generateToken_withAvailablityCondition_success() throws Exception { + void generateToken_withAvailablityCondition_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -770,7 +763,7 @@ public void generateToken_withAvailablityCondition_success() throws Exception { } @Test - public void generateToken_withoutAvailabilityCondition_success() throws Exception { + void generateToken_withoutAvailabilityCondition_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -822,7 +815,7 @@ public void generateToken_withoutAvailabilityCondition_success() throws Exceptio } @Test - public void generateToken_withMultipleRules_success() throws Exception { + void generateToken_withMultipleRules_success() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -886,7 +879,7 @@ public void generateToken_withMultipleRules_success() throws Exception { } @Test - public void generateToken_withInvalidAvailabilityCondition_failure() throws Exception { + void generateToken_withInvalidAvailabilityCondition_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); @@ -923,7 +916,7 @@ public void generateToken_withInvalidAvailabilityCondition_failure() throws Exce } @Test - public void generateToken_withSessionKeyNotBase64Encoded_failure() throws Exception { + void generateToken_withSessionKeyNotBase64Encoded_failure() throws Exception { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); transportFactory.transport.setReturnAccessBoundarySessionKey(true); transportFactory.transport.setAccessBoundarySessionKey("invalid_key"); @@ -960,7 +953,7 @@ public void generateToken_withSessionKeyNotBase64Encoded_failure() throws Except } @Test - public void generateToken_withMalformSessionKey_failure() throws Exception { + 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 5ef5bfb68..cab0183f1 100644 --- a/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java +++ b/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ITClientSideCredentialAccessBoundaryTest.java @@ -31,9 +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; @@ -52,7 +52,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 +61,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"; @@ -98,7 +98,7 @@ public final class ITClientSideCredentialAccessBoundaryTest { * in the same bucket. */ @Test - public void clientSideCredentialAccessBoundary_serviceAccountSource() throws IOException { + void clientSideCredentialAccessBoundary_serviceAccountSource() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = () -> { ServiceAccountCredentials sourceCredentials = diff --git a/cab-token-generator/pom.xml b/cab-token-generator/pom.xml index 9fa12ab2e..b044a6fb6 100644 --- a/cab-token-generator/pom.xml +++ b/cab-token-generator/pom.xml @@ -57,9 +57,22 @@ + + junit junit + 4.13.2 + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test @@ -72,7 +85,6 @@ org.mockito mockito-core - 4.11.0 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..14293b082 100644 --- a/credentials/javatests/com/google/auth/SigningExceptionTest.java +++ b/credentials/javatests/com/google/auth/SigningExceptionTest.java @@ -31,29 +31,29 @@ 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 +61,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 +69,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,7 +78,7 @@ 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()); diff --git a/credentials/pom.xml b/credentials/pom.xml index da1fc3e4f..225b77bc7 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -46,8 +46,13 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test diff --git a/oauth2_http/javatests/com/google/auth/TestUtils.java b/oauth2_http/javatests/com/google/auth/TestUtils.java index 99d601da8..d794ba184 100644 --- a/oauth2_http/javatests/com/google/auth/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/TestUtils.java @@ -31,9 +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; @@ -70,20 +70,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); } diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index bdbcd2c91..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.junit.Assert.assertEquals; -import static org.junit.Assert.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; @@ -47,20 +46,17 @@ import com.google.auth.oauth2.OAuth2Credentials; import com.google.auth.oauth2.UserCredentials; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link HttpCredentialsAdapter}. */ -@RunWith(JUnit4.class) -public class HttpCredentialsAdapterTest { +class HttpCredentialsAdapterTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @Test - public void initialize_populatesOAuth2Credentials() throws IOException { + void initialize_populatesOAuth2Credentials() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -87,7 +83,7 @@ public void initialize_populatesOAuth2Credentials() throws IOException { } @Test - public void initialize_populatesOAuth2Credentials_handle401() throws IOException { + void initialize_populatesOAuth2Credentials_handle401() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; @@ -125,7 +121,7 @@ public void initialize_populatesOAuth2Credentials_handle401() throws IOException } @Test - public void initialize_noURI() throws IOException { + void initialize_noURI() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory tokenServerTransportFactory = @@ -154,7 +150,7 @@ public void initialize_noURI() throws IOException { } @Test - public void getCredentials() { + void getCredentials() { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory(); @@ -171,6 +167,6 @@ public 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/javatests/com/google/auth/mtls/SecureConnectProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java index 9592a52d6..7e962014a 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/SecureConnectProviderTest.java @@ -31,23 +31,23 @@ 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 { - 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 - public void testGetKeyStoreNonZeroExitCode() - throws IOException, InterruptedException, GeneralSecurityException { + void testGetKeyStoreNonZeroExitCode() { InputStream metadata = this.getClass() .getClassLoader() @@ -112,14 +111,14 @@ 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 { + void testExtractCertificateProviderCommand() throws IOException { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mtls_context_aware_metadata.json"); List command = SecureConnectProvider.extractCertificateProviderCommand(inputStream); @@ -129,26 +128,26 @@ public void testExtractCertificateProviderCommand() throws IOException { } @Test - public void testRunCertificateProviderCommandSuccess() throws IOException, InterruptedException { + 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 { + void testRunCertificateProviderCommandTimeout() { 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")); + actual.getMessage().contains("SecureConnect: Cert provider command timed out"), + "expected to fail with timeout"); } @Test - public void testGetKeyStore_FileNotFoundException() + 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 70bb4294e..bd17436c1 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/WorkloadCertificateConfigurationTest.java @@ -31,20 +31,20 @@ 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.Test; -public class WorkloadCertificateConfigurationTest { +class WorkloadCertificateConfigurationTest { @Test - public void workloadCertificateConfig_fromStream_Succeeds() throws IOException { + void workloadCertificateConfig_fromStream_Succeeds() throws IOException { String certPath = "cert.crt"; String privateKeyPath = "key.crt"; InputStream configStream = writeWorkloadCertificateConfigStream(certPath, privateKeyPath); @@ -55,13 +55,13 @@ public void workloadCertificateConfig_fromStream_Succeeds() throws IOException { } @Test - public void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws IOException { + 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)); @@ -73,13 +73,13 @@ public void workloadCertificateConfig_fromStreamMissingCertPath_Fails() throws I } @Test - public void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() throws IOException { + 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)); @@ -91,13 +91,13 @@ public void workloadCertificateConfig_fromStreamMissingPrivateKeyPath_Fails() th } @Test - public void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws IOException { + 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)); @@ -109,12 +109,12 @@ public void workloadCertificateConfig_fromStreamMissingWorkload_Fails() throws I } @Test - public void workloadCertificateConfig_fromStreamMissingCertConfig_Fails() throws IOException { + 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)); diff --git a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java index de016cf55..7f3927654 100644 --- a/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/mtls/X509ProviderTest.java @@ -31,9 +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; @@ -47,10 +48,9 @@ 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.Test; -public class X509ProviderTest { +class X509ProviderTest { private static final String TEST_CERT = "-----BEGIN CERTIFICATE-----\n" @@ -87,18 +87,18 @@ public class X509ProviderTest { + "-----END PRIVATE KEY-----"; @Test - public void x509Provider_fileDoesntExist_throws() { + 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() { + void x509Provider_emptyFile_throws() { String certConfigPath = "certConfig.txt"; InputStream certConfigStream = new ByteArrayInputStream("".getBytes()); TestX509Provider testProvider = new TestX509Provider(certConfigPath); @@ -106,12 +106,12 @@ 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 { + void x509Provider_succeeds() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; String keyPath = "key.crt"; @@ -135,7 +135,7 @@ public void x509Provider_succeeds() throws IOException, KeyStoreException, Certi } @Test - public void x509Provider_succeeds_withEnvVariable() + void x509Provider_succeeds_withEnvVariable() throws IOException, KeyStoreException, CertificateException { String certConfigPath = "certConfig.txt"; String certPath = "cert.crt"; @@ -161,7 +161,7 @@ public void x509Provider_succeeds_withEnvVariable() } @Test - public void x509Provider_succeeds_withWellKnownPath() + 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/AccessTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java index f32fe231b..d93e2c98f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java @@ -31,24 +31,21 @@ 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 +53,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 +62,7 @@ public void constructor() { } @Test - public void builder() { + void builder() { AccessToken accessToken = AccessToken.newBuilder() .setExpirationTime(EXPIRATION_DATE) @@ -108,7 +105,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 +126,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 +146,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 +166,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 +186,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 +201,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 +220,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) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index 82b76d879..43139e2be 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -31,12 +31,14 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.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.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; import com.google.common.collect.ImmutableMap; import java.io.IOException; @@ -47,12 +49,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 = @@ -62,11 +61,10 @@ public 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")); + private static final Collection DEFAULT_SCOPES = Collections.singletonList("scope3"); @Test - public void constructor_usesAppIdentityService() throws IOException { + void constructor_usesAppIdentityService() throws IOException { Collection scopes = Collections.singleton("SomeScope"); TestAppEngineCredentials credentials = new TestAppEngineCredentials(scopes); List forNameArgs = credentials.getForNameArgs(); @@ -78,14 +76,14 @@ public void constructor_usesAppIdentityService() throws IOException { } @Test - public 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() @@ -94,7 +92,7 @@ public void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOExc } @Test - public void refreshAccessToken_sameAs() throws IOException { + void refreshAccessToken_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); @@ -102,19 +100,19 @@ public void refreshAccessToken_sameAs() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(EXPECTED_ACCOUNT, credentials.getAccount()); } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertArrayEquals(EXPECTED_SIGNATURE, credentials.sign("Bytes to sign".getBytes())); } @Test - public void createScoped_clonesWithScopes() throws IOException { + void createScoped_clonesWithScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); try { @@ -133,7 +131,7 @@ public void createScoped_clonesWithScopes() throws IOException { } @Test - public void createScoped_defaultScopes() throws IOException { + void createScoped_defaultScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); @@ -152,26 +150,25 @@ public void createScoped_defaultScopes() throws IOException { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { GoogleCredentials credentials = new TestAppEngineCredentials(SCOPES); GoogleCredentials otherCredentials = new TestAppEngineCredentials(SCOPES); - assertTrue(credentials.equals(credentials)); - assertTrue(credentials.equals(otherCredentials)); - assertTrue(otherCredentials.equals(credentials)); + assertEquals(credentials, otherCredentials); + assertEquals(otherCredentials, credentials); } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() throws IOException { final Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(emptyScopes); AppEngineCredentials otherCredentials = new TestAppEngineCredentials(scopes); - assertFalse(credentials.equals(otherCredentials)); - assertFalse(otherCredentials.equals(credentials)); + assertNotEquals(credentials, otherCredentials); + assertNotEquals(otherCredentials, credentials); } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { String expectedToString = String.format( "TestAppEngineCredentials{scopes=[%s], scopesRequired=%b}", "SomeScope", false); @@ -181,13 +178,13 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { AppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(credentials.hashCode(), credentials.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(scopes); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java index e8b401063..4764d27ec 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -32,12 +32,12 @@ package com.google.auth.oauth2; 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 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 com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonParser; @@ -56,13 +56,10 @@ 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"; @@ -112,7 +109,7 @@ public class AwsCredentialsTest extends BaseSerializationTest { ExternalAccountSupplierContext.newBuilder().setAudience("").setSubjectTokenType("").build(); @Test - public void test_awsCredentialSource() { + void test_awsCredentialSource() { String keys[] = {"region_url", "url", "imdsv2_session_token_url"}; for (String key : keys) { Map credentialSourceWithInvalidUrl = buildAwsIpv6CredentialSourceMap(); @@ -124,7 +121,7 @@ public void test_awsCredentialSource() { } @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -146,7 +143,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc } @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -176,7 +173,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept } @Test - public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -216,7 +213,7 @@ public void refreshAccessToken_withServiceAccountImpersonationOptions() throws I } @Test - public void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() + void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -244,8 +241,7 @@ public void refreshAccessTokenProgrammaticRefresh_withoutServiceAccountImpersona } @Test - public void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() - throws IOException { + void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -278,7 +274,7 @@ public void refreshAccessTokenProgrammaticRefresh_withServiceAccountImpersonatio @Test @SuppressWarnings("unchecked") - public void retrieveSubjectToken() throws IOException { + void retrieveSubjectToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -322,7 +318,7 @@ public void retrieveSubjectToken() throws IOException { @Test @SuppressWarnings("unchecked") - public void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { + void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -386,8 +382,7 @@ public void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } @Test - public void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() - throws IOException { + void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -432,8 +427,7 @@ public void retrieveSubjectToken_imdsv1EnvVariablesSet_metadataServerNotCalled() } @Test - public void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() - throws IOException { + void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -478,7 +472,7 @@ public void retrieveSubjectToken_imdsv2EnvVariablesSet_metadataServerNotCalled() } @Test - public void retrieveSubjectToken_noRegion_expectThrows() { + void retrieveSubjectToken_noRegion_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -506,7 +500,7 @@ public void retrieveSubjectToken_noRegion_expectThrows() { } @Test - public void retrieveSubjectToken_noRole_expectThrows() { + void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -538,7 +532,7 @@ public void retrieveSubjectToken_noRole_expectThrows() { } @Test - public void retrieveSubjectToken_noCredentials_expectThrows() { + void retrieveSubjectToken_noCredentials_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -573,7 +567,7 @@ public void retrieveSubjectToken_noCredentials_expectThrows() { } @Test - public void retrieveSubjectToken_noRegionUrlProvided() { + void retrieveSubjectToken_noRegionUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -603,7 +597,7 @@ public void retrieveSubjectToken_noRegionUrlProvided() { } @Test - public void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { + void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -642,7 +636,7 @@ public void retrieveSubjectToken_withProgrammaticRefresh() throws IOException { } @Test - public void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IOException { + void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -685,7 +679,7 @@ public void retrieveSubjectToken_withProgrammaticRefreshSessionToken() throws IO } @Test - public void retrieveSubjectToken_passesContext() throws IOException { + void retrieveSubjectToken_passesContext() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -715,7 +709,7 @@ public void retrieveSubjectToken_passesContext() throws IOException { } @Test - public void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOException { + void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -742,7 +736,7 @@ public void retrieveSubjectToken_withProgrammaticRefreshThrowsError() throws IOE } @Test - public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { + void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -762,7 +756,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws I } @Test - public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { + void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -795,7 +789,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws } @Test - public void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerCall() + void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerCall() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider @@ -817,7 +811,7 @@ public void getAwsSecurityCredentials_fromEnvironmentVariables_noMetadataServerC } @Test - public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { + void getAwsSecurityCredentials_fromMetadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -845,7 +839,7 @@ public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { } @Test - public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { + void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -874,7 +868,7 @@ public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { } @Test - public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { + void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_REGION", "region"); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -900,7 +894,7 @@ public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { } @Test - public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { + void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -925,7 +919,7 @@ public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOExceptio } @Test - public void getAwsRegion_metadataServer() throws IOException { + void getAwsRegion_metadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredentials = @@ -952,7 +946,7 @@ public void getAwsRegion_metadataServer() throws IOException { } @Test - public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + void createdScoped_clonedCredentialWithAddedScopes() throws IOException { AwsCredentials credentials = AwsCredentials.newBuilder(AWS_CREDENTIAL) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -983,7 +977,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { } @Test - public void credentialSource_invalidAwsEnvironmentId() { + void credentialSource_invalidAwsEnvironmentId() { Map credentialSource = new HashMap<>(); credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "azure1"); @@ -997,7 +991,7 @@ public void credentialSource_invalidAwsEnvironmentId() { } @Test - public void credentialSource_invalidAwsEnvironmentVersion() { + void credentialSource_invalidAwsEnvironmentVersion() { Map credentialSource = new HashMap<>(); int environmentVersion = 2; credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); @@ -1015,7 +1009,7 @@ public void credentialSource_invalidAwsEnvironmentVersion() { } @Test - public void credentialSource_missingRegionalCredVerificationUrl() { + void credentialSource_missingRegionalCredVerificationUrl() { try { new AwsCredentialSource(new HashMap()); fail("Exception should be thrown."); @@ -1027,7 +1021,7 @@ public void credentialSource_missingRegionalCredVerificationUrl() { } @Test - public void builder_allFields() throws IOException { + void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1063,7 +1057,7 @@ public void builder_allFields() throws IOException { } @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1100,7 +1094,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { } @Test - public void newBuilder_allFields() throws IOException { + void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1138,7 +1132,7 @@ public void newBuilder_allFields() throws IOException { } @Test - public void newBuilder_noUniverseDomain_defaults() throws IOException { + void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsCredentials credentials = @@ -1175,7 +1169,7 @@ public void newBuilder_noUniverseDomain_defaults() throws IOException { } @Test - public void builder_defaultRegionalCredentialVerificationUrlOverride() throws IOException { + void builder_defaultRegionalCredentialVerificationUrlOverride() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsSecurityCredentialsSupplier supplier = @@ -1203,7 +1197,7 @@ public void builder_defaultRegionalCredentialVerificationUrlOverride() throws IO } @Test - public void builder_supplierAndCredSourceThrows() throws IOException { + void builder_supplierAndCredSourceThrows() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); AwsSecurityCredentialsSupplier supplier = @@ -1234,7 +1228,7 @@ public void builder_supplierAndCredSourceThrows() throws IOException { } @Test - public void builder_noSupplieOrCredSourceThrows() throws IOException { + void builder_noSupplieOrCredSourceThrows() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); Supplier testSupplier = () -> null; @@ -1263,7 +1257,7 @@ public void builder_noSupplieOrCredSourceThrows() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + 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 3bac05214..a1125edef 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java @@ -31,7 +31,7 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -43,8 +43,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 +52,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 +63,8 @@ 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(); @@ -73,7 +73,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() { + void sign_getHost() { String url = "https://host.foo.com"; Map headers = new HashMap<>(); @@ -104,7 +104,7 @@ public void sign_getHost() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-relative-relative.sreq @Test - public void sign_getHostRelativePath() { + void sign_getHostRelativePath() { String url = "https://host.foo.com/foo/bar/../.."; Map headers = new HashMap<>(); @@ -135,7 +135,7 @@ public void sign_getHostRelativePath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-dot-slash.sreq @Test - public void sign_getHostInvalidPath() { + void sign_getHostInvalidPath() { String url = "https://host.foo.com/./"; Map headers = new HashMap<>(); @@ -166,7 +166,7 @@ public void sign_getHostInvalidPath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-slash-pointless-dot.sreq @Test - public void sign_getHostDotPath() { + void sign_getHostDotPath() { String url = "https://host.foo.com/./foo"; Map headers = new HashMap<>(); @@ -197,7 +197,7 @@ public void sign_getHostDotPath() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-utf8.sreq @Test - public void sign_getHostUtf8Path() { + void sign_getHostUtf8Path() { String url = "https://host.foo.com/%E1%88%B4"; Map headers = new HashMap<>(); @@ -228,7 +228,7 @@ public void sign_getHostUtf8Path() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla-query-order-key-case.sreq @Test - public void sign_getHostDuplicateQueryParam() { + void sign_getHostDuplicateQueryParam() { String url = "https://host.foo.com/?foo=Zoo&foo=aha"; Map headers = new HashMap<>(); @@ -259,7 +259,7 @@ public void sign_getHostDuplicateQueryParam() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-key-sort.sreq @Test - public void sign_postWithUpperCaseHeaderKey() { + void sign_postWithUpperCaseHeaderKey() { String url = "https://host.foo.com/"; String headerKey = "ZOO"; String headerValue = "zoobar"; @@ -294,7 +294,7 @@ public void sign_postWithUpperCaseHeaderKey() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-header-value-case.sreq @Test - public void sign_postWithUpperCaseHeaderValue() { + void sign_postWithUpperCaseHeaderValue() { String url = "https://host.foo.com/"; String headerKey = "zoo"; String headerValue = "ZOOBAR"; @@ -329,7 +329,7 @@ public void sign_postWithUpperCaseHeaderValue() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.sreq @Test - public void sign_postWithHeader() { + void sign_postWithHeader() { String url = "https://host.foo.com/"; String headerKey = "p"; String headerValue = "phfft"; @@ -364,7 +364,7 @@ public void sign_postWithHeader() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-x-www-form-urlencoded.sreq @Test - public void sign_postWithBodyNoCustomHeaders() { + void sign_postWithBodyNoCustomHeaders() { String url = "https://host.foo.com/"; String headerKey = "Content-Type"; String headerValue = "application/x-www-form-urlencoded"; @@ -400,7 +400,7 @@ public void sign_postWithBodyNoCustomHeaders() { // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/post-vanilla-query.sreq @Test - public void sign_postWithQueryString() { + void sign_postWithQueryString() { String url = "https://host.foo.com/?foo=bar"; Map headers = new HashMap<>(); @@ -429,7 +429,7 @@ public void sign_postWithQueryString() { } @Test - public void sign_getDescribeRegions() { + void sign_getDescribeRegions() { String url = "https://ec2.us-east-2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15"; Map additionalHeaders = new HashMap<>(); @@ -460,7 +460,7 @@ public void sign_getDescribeRegions() { } @Test - public void sign_postGetCallerIdentity() { + void sign_postGetCallerIdentity() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; Map additionalHeaders = new HashMap<>(); @@ -491,7 +491,7 @@ public void sign_postGetCallerIdentity() { } @Test - public void sign_postGetCallerIdentityNoToken() { + void sign_postGetCallerIdentityNoToken() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; AwsSecurityCredentials awsSecurityCredentialsWithoutToken = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CertificateIdentityPoolSubjectTokenSupplierTest.java index bfc7c59cb..9ff8f7f5f 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,15 @@ 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,22 +82,25 @@ 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())); @@ -109,14 +108,14 @@ public void setUp() throws IOException, URISyntaxException { } @Test - public void parseCertificate_validData_returnsCertificate() throws Exception { + void parseCertificate_validData_returnsCertificate() throws Exception { X509Certificate cert = CertificateIdentityPoolSubjectTokenSupplier.parseCertificate(testCertBytesFromFile); assertNotNull(cert); } @Test - public void parseCertificate_emptyData_throwsIllegalArgumentException() { + void parseCertificate_emptyData_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -126,7 +125,7 @@ public void parseCertificate_emptyData_throwsIllegalArgumentException() { } @Test - public void parseCertificate_nullData_throwsIllegalArgumentException() { + void parseCertificate_nullData_throwsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, @@ -136,7 +135,7 @@ public void parseCertificate_nullData_throwsIllegalArgumentException() { } @Test - public void parseCertificate_invalidData_throwsCertificateException() { + void parseCertificate_invalidData_throwsCertificateException() { CertificateException exception = assertThrows( CertificateException.class, @@ -145,7 +144,7 @@ public void parseCertificate_invalidData_throwsCertificateException() { } @Test - public void getSubjectToken_withoutTrustChain_success() throws Exception { + void getSubjectToken_withoutTrustChain_success() throws Exception { // Calculate expected result based on the file content. CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate expectedCert = @@ -162,11 +161,11 @@ public void getSubjectToken_withoutTrustChain_success() throws Exception { } @Test - public void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { + 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()); @@ -196,11 +195,11 @@ public void getSubjectToken_trustChainWithLeafFirst_success() throws Exception { } @Test - public void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { + 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()); @@ -235,10 +234,10 @@ public void getSubjectToken_trustChainWithoutLeaf_success() throws Exception { // 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() { + 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 +253,22 @@ public void getSubjectToken_trustChainWrongOrder_throwsIllegalArgumentException( assertEquals(expectedOuterExceptionMessage, exception.getMessage()); Throwable cause = exception.getCause(); - assertNotNull("Exception cause should not be null", cause); + assertNotNull(cause, "Exception cause should not be null"); assertTrue( - "Exception cause should be an IllegalArgumentException", - cause instanceof IllegalArgumentException); + cause instanceof IllegalArgumentException, + "Exception cause should be an IllegalArgumentException"); assertEquals(expectedRootErrorMessage, cause.getMessage()); } @Test - public void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { + 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); + trustChainUrl, + "Test resource 'x509_leaf_certificate.pem' (used as trust chain) not found!"); when(mockCertificateConfig.getTrustChainPath()) .thenReturn(new File(trustChainUrl.getFile()).getAbsolutePath()); @@ -292,7 +291,7 @@ public void getSubjectToken_trustChainOnlyLeaf_success() throws Exception { } @Test - public void getSubjectToken_trustChainFileNotFound_throwsIOException() { + 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); @@ -309,7 +308,7 @@ public void getSubjectToken_trustChainFileNotFound_throwsIOException() { } @Test - public void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws Exception { + 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(); @@ -342,7 +341,7 @@ public void getSubjectToken_trustChainInvalidFormat_throwsIOException() throws E } @Test - public void getSubjectToken_leafCertFileNotFound_throwsIOException() { + 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 +356,9 @@ 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()); + assertNotNull(exception.getCause(), "Exception should have a cause"); assertTrue( - "Cause should be NoSuchFileException", exception.getCause() instanceof NoSuchFileException); + 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); @@ -368,7 +367,7 @@ public void getSubjectToken_leafCertFileNotFound_throwsIOException() { } @Test - public void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exception { + void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exception { // Create a temporary file with invalid cert data. File invalidLeafFile = File.createTempFile("invalid_leaf", ".pem"); invalidLeafFile.deleteOnExit(); @@ -396,7 +395,7 @@ public void getSubjectToken_leafCertInvalidFormat_throwsIOException() throws Exc } @Test - public void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertificateException() + 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"); @@ -418,14 +417,14 @@ public void readTrustChain_whenFileIsNotEmptyButContainsNoPemBlocks_throwsCertif } @Test - public void readTrustChain_nullPath_returnsEmptyList() throws Exception { + 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 { + 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 d7a5ca015..c002cf7e4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java @@ -31,25 +31,23 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Unit tests for ClientId */ -@RunWith(JUnit4.class) -public class ClientIdTest { +class ClientIdTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @Test - public void constructor() { + void constructor() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); @@ -57,20 +55,22 @@ public void constructor() { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test(expected = NullPointerException.class) - public void constructor_nullClientId_throws() { - ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build(); + @Test + void constructor_nullClientId_throws() { + assertThrows( + NullPointerException.class, + () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); } @Test - public void constructor_nullClientSecret() { + void constructor_nullClientSecret() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).build(); assertEquals(CLIENT_ID, clientId.getClientId()); assertNull(clientId.getClientSecret()); } @Test - public void fromJson_web() throws IOException { + void fromJson_web() throws IOException { GenericJson json = writeClientIdJson("web", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -80,7 +80,7 @@ public void fromJson_web() throws IOException { } @Test - public void fromJson_installed() throws IOException { + void fromJson_installed() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -90,7 +90,7 @@ public void fromJson_installed() throws IOException { } @Test - public void fromJson_installedNoSecret() throws IOException { + void fromJson_installedNoSecret() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, null); ClientId clientId = ClientId.fromJson(json); @@ -99,42 +99,44 @@ public void fromJson_installedNoSecret() throws IOException { assertNull(clientId.getClientSecret()); } - @Test(expected = IOException.class) - public void fromJson_invalidType_throws() throws IOException { + @Test + void fromJson_invalidType_throws() 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 { + 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 { + void fromStream() throws IOException { String text = "{" + "\"web\": {" @@ -155,7 +157,7 @@ public void fromStream() throws IOException { } @Test - public void fromStream_invalidJson_doesNotThrow() throws IOException { + void fromStream_invalidJson_doesNotThrow() throws IOException { String invalidJson = "{" + "\"web\": {" diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java index e316df4d8..2f0dde620 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CloudShellCredentialsTest.java @@ -31,10 +31,10 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.util.Clock; import java.io.BufferedReader; @@ -43,16 +43,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 { +class CloudShellCredentialsTest extends BaseSerializationTest { @Test - public void refreshAccessToken() throws IOException { + void refreshAccessToken() throws IOException { final ServerSocket authSocket = new ServerSocket(0); try { Runnable serverTask = @@ -86,7 +83,7 @@ public void run() { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertTrue(credentials.equals(otherCredentials)); @@ -94,7 +91,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_authPort() throws IOException { + void equals_false_authPort() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(43).build(); assertFalse(credentials.equals(otherCredentials)); @@ -102,21 +99,21 @@ public void equals_false_authPort() throws IOException { } @Test - public void toString_containsFields() throws IOException { + 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 { + void hashCode_equals() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); assertEquals(credentials, deserializedCredentials); @@ -126,7 +123,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void toBuilder() { + 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 a3df59e1a..c41f7a770 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -33,15 +33,15 @@ 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 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 com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -69,14 +69,10 @@ 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.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"); @@ -129,7 +125,7 @@ public class ComputeEngineCredentialsTest extends BaseSerializationTest { .collect(Collectors.toMap(data -> data[0], data -> data[1])); @Test - public void buildTokenUrlWithScopes_null_scopes() { + void buildTokenUrlWithScopes_null_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); Collection scopes = credentials.getScopes(); @@ -140,7 +136,7 @@ public void buildTokenUrlWithScopes_null_scopes() { } @Test - public void buildTokenUrlWithScopes_empty_scopes() { + void buildTokenUrlWithScopes_empty_scopes() { ComputeEngineCredentials.Builder builder = ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); ComputeEngineCredentials credentials = builder.build(); @@ -153,7 +149,7 @@ public void buildTokenUrlWithScopes_empty_scopes() { } @Test - public void buildTokenUrlWithScopes_single_scope() { + void buildTokenUrlWithScopes_single_scope() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(Arrays.asList("foo")).build(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -165,7 +161,7 @@ public void buildTokenUrlWithScopes_single_scope() { } @Test - public void buildTokenUrlWithScopes_multiple_scopes() { + void buildTokenUrlWithScopes_multiple_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(Arrays.asList(null, "foo", "", "bar")) @@ -180,7 +176,7 @@ public void buildTokenUrlWithScopes_multiple_scopes() { } @Test - public void buildTokenUrlWithScopes_defaultScopes() { + void buildTokenUrlWithScopes_defaultScopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().build(); credentials = (ComputeEngineCredentials) @@ -195,7 +191,7 @@ public void buildTokenUrlWithScopes_defaultScopes() { } @Test - public void buildTokenUrl_nullTransport() { + void buildTokenUrl_nullTransport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(null) @@ -207,7 +203,7 @@ public void buildTokenUrl_nullTransport() { } @Test - public void buildTokenUrl_nullBindingEnforcement() { + void buildTokenUrl_nullBindingEnforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -219,7 +215,7 @@ public void buildTokenUrl_nullBindingEnforcement() { } @Test - public void buildTokenUrl_nullTransport_nullBindingEnforcement() { + void buildTokenUrl_nullTransport_nullBindingEnforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(null) @@ -231,7 +227,7 @@ public void buildTokenUrl_nullTransport_nullBindingEnforcement() { } @Test - public void buildTokenUrl_mtls_transport() { + void buildTokenUrl_mtls_transport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -242,7 +238,7 @@ public void buildTokenUrl_mtls_transport() { } @Test - public void buildTokenUrl_iam_enforcement() { + void buildTokenUrl_iam_enforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setBindingEnforcement(ComputeEngineCredentials.BindingEnforcement.IAM_POLICY) @@ -253,7 +249,7 @@ public void buildTokenUrl_iam_enforcement() { } @Test - public void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { + void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -265,7 +261,7 @@ public void buildTokenUrlSoftMtlsBound_mtls_transport_iam_enforcement() { } @Test - public void buildTokenUrl_always_enforced() { + void buildTokenUrl_always_enforced() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setBindingEnforcement(ComputeEngineCredentials.BindingEnforcement.ON) @@ -276,7 +272,7 @@ public void buildTokenUrl_always_enforced() { } @Test - public void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { + void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.MTLS) @@ -288,7 +284,7 @@ public void buildTokenUrlHardMtlsBound_mtls_transport_always_enforced() { } @Test - public void buildTokenUrlHardDirectPathBound_alts_transport() { + void buildTokenUrlHardDirectPathBound_alts_transport() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setGoogleAuthTransport(ComputeEngineCredentials.GoogleAuthTransport.ALTS) @@ -299,7 +295,7 @@ public void buildTokenUrlHardDirectPathBound_alts_transport() { } @Test - public void buildScoped_scopesPresent() throws IOException { + void buildScoped_scopesPresent() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials scopedCredentials = @@ -311,7 +307,7 @@ public void buildScoped_scopesPresent() throws IOException { } @Test - public void buildScoped_correctMargins() throws IOException { + void buildScoped_correctMargins() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials scopedCredentials = @@ -325,7 +321,7 @@ public void buildScoped_correctMargins() throws IOException { } @Test - public void buildScoped_explicitUniverse() throws IOException { + void buildScoped_explicitUniverse() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -339,7 +335,7 @@ public void buildScoped_explicitUniverse() throws IOException { } @Test - public void createScoped_defaultScopes() { + void createScoped_defaultScopes() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); Collection scopes = ((ComputeEngineCredentials) credentials).getScopes(); @@ -349,7 +345,7 @@ public void createScoped_defaultScopes() { } @Test - public void buildScoped_quotaProjectId() throws IOException { + void buildScoped_quotaProjectId() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -362,7 +358,7 @@ public void buildScoped_quotaProjectId() throws IOException { } @Test - public void buildDefaultScoped_explicitUniverse() throws IOException { + void buildDefaultScoped_explicitUniverse() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(null) @@ -376,7 +372,7 @@ public void buildDefaultScoped_explicitUniverse() throws IOException { } @Test - public void create_scoped_correctMargins() { + void create_scoped_correctMargins() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); @@ -386,7 +382,7 @@ public void create_scoped_correctMargins() { } @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + void getRequestMetadata_hasAccessToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); ComputeEngineCredentials credentials = @@ -402,7 +398,7 @@ public void getRequestMetadata_hasAccessToken() throws IOException { } @Test - public void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTokenFromRefresh() + void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTokenFromRefresh() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -423,7 +419,7 @@ public void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTo } @Test - public void getRequestMetadata_missingServiceAccount_throws() { + void getRequestMetadata_missingServiceAccount_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -441,7 +437,7 @@ public void getRequestMetadata_missingServiceAccount_throws() { } @Test - public void getRequestMetadata_serverError_throws() { + void getRequestMetadata_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -458,7 +454,7 @@ public void getRequestMetadata_serverError_throws() { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials explicitUniverseCredentials = ComputeEngineCredentials.newBuilder() @@ -480,7 +476,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_transportFactory() throws IOException { + void equals_false_transportFactory() throws IOException { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); @@ -495,7 +491,7 @@ public void equals_false_transportFactory() throws IOException { } @Test - public void toString_explicit_containsFields() throws IOException { + void toString_explicit_containsFields() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); String expectedToString = @@ -517,7 +513,7 @@ public void toString_explicit_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -532,7 +528,7 @@ public void hashCode_equals() throws IOException { } @Test - public void toBuilder() { + void toBuilder() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setHttpTransportFactory(new MockMetadataServerTransportFactory()) @@ -545,7 +541,7 @@ public void toBuilder() { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -566,7 +562,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -582,7 +578,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void getAccount_missing_throws() { + void getAccount_missing_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -618,7 +614,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void getAccount_emptyContent_throws() { + void getAccount_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -653,7 +649,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void sign_sameAs() { + void sign_sameAs() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -667,7 +663,7 @@ public void sign_sameAs() { } @Test - public void sign_getUniverseException() { + void sign_getUniverseException() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -676,16 +672,16 @@ 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() { + void sign_getAccountFails() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -694,13 +690,13 @@ 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() { + void sign_accessDenied_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -731,14 +727,14 @@ 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() { + void sign_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -769,14 +765,14 @@ 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() { + void refresh_503_retryable_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -797,15 +793,14 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - IOException exception = - Assert.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()); } @Test - public void refresh_non503_ioexception_throws() { + 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 +830,13 @@ 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 { + void getUniverseDomain_fromMetadata() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -868,7 +863,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void getUniverseDomain_fromMetadata_emptyBecomesDefault() throws IOException { + void getUniverseDomain_fromMetadata_emptyBecomesDefault() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -895,7 +890,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void getUniverseDomain_fromMetadata_404_default() throws IOException { + void getUniverseDomain_fromMetadata_404_default() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport = @@ -922,7 +917,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { + void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); @@ -939,7 +934,7 @@ public void getUniverseDomain_explicitSet_NoMdsCall() throws IOException { } @Test - public void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { + void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); @@ -956,7 +951,7 @@ public void getUniverseDomain_explicitGduSet_NoMdsCall() throws IOException { } @Test - public void getUniverseDomain_fromMetadata_non404error_throws() throws IOException { + void getUniverseDomain_fromMetadata_non404error_throws() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); MockMetadataServerTransport transport = transportFactory.transport; @@ -979,7 +974,7 @@ public void getUniverseDomain_fromMetadata_non404error_throws() throws IOExcepti } @Test - public void sign_emptyContent_throws() { + void sign_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -1009,14 +1004,14 @@ 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 { + void idTokenWithAudience_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(STANDARD_ID_TOKEN); ComputeEngineCredentials credentials = @@ -1037,7 +1032,7 @@ public void idTokenWithAudience_sameAs() throws IOException { } @Test - public void idTokenWithAudience_standard() throws IOException { + void idTokenWithAudience_standard() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -1056,7 +1051,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 +1065,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 +1077,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 +1093,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")); @@ -1108,7 +1103,7 @@ public void idTokenWithAudience_licenses() throws IOException { } @Test - public void idTokenWithAudience_404StatusCode() { + void idTokenWithAudience_404StatusCode() { int statusCode = HttpStatusCodes.STATUS_CODE_NOT_FOUND; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); @@ -1126,7 +1121,7 @@ public void idTokenWithAudience_404StatusCode() { } @Test - public void idTokenWithAudience_emptyContent() { + void idTokenWithAudience_emptyContent() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setEmptyContent(true); ComputeEngineCredentials credentials = @@ -1137,7 +1132,7 @@ public void idTokenWithAudience_emptyContent() { } @Test - public void idTokenWithAudience_503StatusCode() { + 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 ac042e065..0dee7011e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java @@ -31,25 +31,22 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.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 { +class CredentialAccessBoundaryTest { @Test - public void credentialAccessBoundary() { + void credentialAccessBoundary() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -92,7 +89,7 @@ public void credentialAccessBoundary() { } @Test - public void credentialAccessBoundary_nullRules_throws() { + void credentialAccessBoundary_nullRules_throws() { try { CredentialAccessBoundary.newBuilder().build(); fail("Should fail."); @@ -102,7 +99,7 @@ public void credentialAccessBoundary_nullRules_throws() { } @Test - public void credentialAccessBoundary_withoutRules_throws() { + void credentialAccessBoundary_withoutRules_throws() { try { CredentialAccessBoundary.newBuilder().setRules(new ArrayList()).build(); fail("Should fail."); @@ -112,7 +109,7 @@ public void credentialAccessBoundary_withoutRules_throws() { } @Test - public void credentialAccessBoundary_ruleCountExceeded_throws() { + void credentialAccessBoundary_ruleCountExceeded_throws() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -133,7 +130,7 @@ public void credentialAccessBoundary_ruleCountExceeded_throws() { } @Test - public void credentialAccessBoundary_toJson() { + void credentialAccessBoundary_toJson() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -172,7 +169,7 @@ public void credentialAccessBoundary_toJson() { } @Test - public void accessBoundaryRule_allFields() { + void accessBoundaryRule_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -192,7 +189,7 @@ public void accessBoundaryRule_allFields() { } @Test - public void accessBoundaryRule_requiredFields() { + void accessBoundaryRule_requiredFields() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -206,7 +203,7 @@ public void accessBoundaryRule_requiredFields() { } @Test - public void accessBoundaryRule_withEmptyAvailableResource_throws() { + void accessBoundaryRule_withEmptyAvailableResource_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("") @@ -219,7 +216,7 @@ public void accessBoundaryRule_withEmptyAvailableResource_throws() { } @Test - public void accessBoundaryRule_withoutAvailableResource_throws() { + void accessBoundaryRule_withoutAvailableResource_throws() { try { AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(); fail("Should fail."); @@ -229,7 +226,7 @@ public void accessBoundaryRule_withoutAvailableResource_throws() { } @Test - public void accessBoundaryRule_withoutAvailablePermissions_throws() { + void accessBoundaryRule_withoutAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(); fail("Should fail."); @@ -239,7 +236,7 @@ public void accessBoundaryRule_withoutAvailablePermissions_throws() { } @Test - public void accessBoundaryRule_withEmptyAvailablePermissions_throws() { + void accessBoundaryRule_withEmptyAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -252,7 +249,7 @@ public void accessBoundaryRule_withEmptyAvailablePermissions_throws() { } @Test - public void accessBoundaryRule_withNullAvailablePermissions_throws() { + void accessBoundaryRule_withNullAvailablePermissions_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -265,7 +262,7 @@ public void accessBoundaryRule_withNullAvailablePermissions_throws() { } @Test - public void accessBoundaryRule_withEmptyAvailablePermission_throws() { + void accessBoundaryRule_withEmptyAvailablePermission_throws() { try { AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -278,7 +275,7 @@ public void accessBoundaryRule_withEmptyAvailablePermission_throws() { } @Test - public void availabilityCondition_allFields() { + void availabilityCondition_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -292,7 +289,7 @@ public void availabilityCondition_allFields() { } @Test - public void availabilityCondition_expressionOnly() { + void availabilityCondition_expressionOnly() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -302,7 +299,7 @@ public void availabilityCondition_expressionOnly() { } @Test - public void availabilityCondition_nullExpression_throws() { + void availabilityCondition_nullExpression_throws() { try { AvailabilityCondition.newBuilder().setExpression(null).build(); fail("Should fail."); @@ -312,7 +309,7 @@ public void availabilityCondition_nullExpression_throws() { } @Test - public void availabilityCondition_emptyExpression_throws() { + 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 cb6f5a8cc..1852629ee 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; @@ -65,13 +65,10 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link DefaultCredentialsProvider}. */ -@RunWith(JUnit4.class) -public class DefaultCredentialsProviderTest { +class DefaultCredentialsProviderTest { private static final String USER_CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String USER_CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -106,7 +103,7 @@ public class DefaultCredentialsProviderTest { private static final String SMBIOS_PATH_LINUX = "/sys/class/dmi/id/product_name"; @Test - public void getDefaultCredentials_noCredentials_throws() { + void getDefaultCredentials_noCredentials_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -120,7 +117,7 @@ public void getDefaultCredentials_noCredentials_throws() { } @Test - public void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { + void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setFileSandbox(true); @@ -135,7 +132,7 @@ public void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { } @Test - public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { + void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -156,7 +153,7 @@ public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exc } @Test - public void getDefaultCredentials_noCredentials_singleGceTestRequest() { + void getDefaultCredentials_noCredentials_singleGceTestRequest() { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -183,7 +180,7 @@ public void getDefaultCredentials_noCredentials_singleGceTestRequest() { } @Test - public void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException { + void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "Linux"); String productFilePath = SMBIOS_PATH_LINUX; @@ -194,7 +191,7 @@ public void getDefaultCredentials_noCredentials_linuxNotGce() throws IOException } @Test - public void getDefaultCredentials_static_linux() throws IOException { + void getDefaultCredentials_static_linux() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "Linux"); String productFilePath = SMBIOS_PATH_LINUX; @@ -206,7 +203,7 @@ public void getDefaultCredentials_static_linux() throws IOException { } @Test - public void getDefaultCredentials_static_windows_configuredAsLinux_notGce() throws IOException { + void getDefaultCredentials_static_windows_configuredAsLinux_notGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "windows"); String productFilePath = SMBIOS_PATH_LINUX; @@ -217,7 +214,7 @@ public void getDefaultCredentials_static_windows_configuredAsLinux_notGce() thro } @Test - public void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOException { + void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOException { TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setProperty("os.name", "macos"); String productFilePath = SMBIOS_PATH_LINUX; @@ -228,7 +225,7 @@ public void getDefaultCredentials_static_unsupportedPlatform_notGce() throws IOE } @Test - public void checkGcpLinuxPlatformData() throws Exception { + void checkGcpLinuxPlatformData() throws Exception { BufferedReader reader; reader = new BufferedReader(new StringReader("HP Z440 Workstation")); assertFalse(ComputeEngineCredentials.checkProductNameOnLinux(reader)); @@ -241,7 +238,7 @@ public void checkGcpLinuxPlatformData() throws Exception { } @Test - public void getDefaultCredentials_caches() throws IOException { + void getDefaultCredentials_caches() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -253,7 +250,7 @@ public void getDefaultCredentials_caches() throws IOException { } @Test - public void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { + void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -270,7 +267,7 @@ public void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { } @Test - public void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { + void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -288,8 +285,7 @@ public void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoad } @Test - public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() - throws IOException { + void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -303,7 +299,7 @@ public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredenti } @Test - public void getDefaultCredentials_compute_providesToken() throws IOException { + void getDefaultCredentials_compute_providesToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail(SA_CLIENT_EMAIL); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -316,7 +312,7 @@ public void getDefaultCredentials_compute_providesToken() throws IOException { } @Test - public void getDefaultCredentials_cloudshell() throws IOException { + void getDefaultCredentials_cloudshell() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -328,7 +324,7 @@ public void getDefaultCredentials_cloudshell() throws IOException { } @Test - public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { + void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -340,7 +336,7 @@ public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() thro } @Test - public void getDefaultCredentials_envMissingFile_throws() { + void getDefaultCredentials_envMissingFile_throws() { final String invalidPath = "/invalid/path"; MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -357,7 +353,7 @@ public void getDefaultCredentials_envMissingFile_throws() { } @Test - public void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { + void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -377,7 +373,7 @@ public void getDefaultCredentials_envServiceAccount_providesToken() throws IOExc } @Test - public void getDefaultCredentials_envUser_providesToken() throws IOException { + void getDefaultCredentials_envUser_providesToken() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -390,7 +386,7 @@ public void getDefaultCredentials_envUser_providesToken() throws IOException { } @Test - public void getDefaultCredentials_GdchServiceAccount() throws IOException { + void getDefaultCredentials_GdchServiceAccount() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( @@ -433,7 +429,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); @@ -459,7 +455,7 @@ public void getDefaultCredentials_quota_project() throws IOException { } @Test - public void getDefaultCredentials_compute_quotaProject() throws IOException { + void getDefaultCredentials_compute_quotaProject() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv( @@ -477,7 +473,7 @@ public void getDefaultCredentials_compute_quotaProject() throws IOException { } @Test - public void getDefaultCredentials_cloudshell_quotaProject() throws IOException { + void getDefaultCredentials_cloudshell_quotaProject() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -491,7 +487,7 @@ public void getDefaultCredentials_cloudshell_quotaProject() throws IOException { } @Test - public void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { + void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -507,7 +503,7 @@ public void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOExceptio } @Test - public void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOException { + void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -527,7 +523,7 @@ public void getDefaultCredentials_linuxSetup_envNoGceCheck_noGce() throws IOExce } @Test - public void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { + void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -535,7 +531,7 @@ public void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { } @Test - public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { + void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -545,7 +541,7 @@ public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { } @Test - public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { + void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -560,7 +556,7 @@ public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOExce } @Test - public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { + void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File configDir = new File(homeDir, ".config"); File cloudConfigDir = new File(configDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); @@ -578,7 +574,7 @@ public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws } @Test - public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { + void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File cloudConfigDir = new File(homeDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); InputStream userStream = @@ -595,7 +591,7 @@ public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IO } @Test - public void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { + void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { final String refreshTokenEnv = "2/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; final String accessTokenEnv = "2/MkSJoj1xsli0AccessToken_NKPY2"; final String refreshTokenWkf = "3/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @@ -653,7 +649,7 @@ public void flush() {} } @Test - public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { + void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false, true); assertNotNull(message); assertEquals(Level.WARNING, message.getLevel()); @@ -662,13 +658,13 @@ public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOExc } @Test - public void getDefaultCredentials_wellKnownFile_noGcloudWarning() throws IOException { + void getDefaultCredentials_wellKnownFile_noGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false, false); assertNull(message); } @Test - public void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { + void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(true, true); assertNull(message); } @@ -744,7 +740,7 @@ public AccessToken refreshAccessToken() throws IOException { } @Test - public void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredentialInfo() + void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCredentialInfo() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); @@ -771,8 +767,7 @@ public void getDefaultCredentials_envVarSet_serviceAccountCredentials_correctCre } @Test - public 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); @@ -797,7 +792,7 @@ public void getDefaultCredentials_envVarSet_userCredential_correctCredentialInfo } @Test - public void getDefaultCredentials_wellKnownFile_userCredential_correctCredentialInfo() + void getDefaultCredentials_wellKnownFile_userCredential_correctCredentialInfo() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = @@ -824,7 +819,7 @@ public void getDefaultCredentials_wellKnownFile_userCredential_correctCredential } @Test - public void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correctCredentialInfo() + void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correctCredentialInfo() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -844,7 +839,7 @@ public void getDefaultCredentials_computeEngineCredentials_defaultMDSUrl_correct } @Test - public void getDefaultCredentials_computeEngineCredentials_customMDSUrl_correctCredentialInfo() + 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 5f452bfd7..114e27298 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DefaultPKCEProviderTest.java @@ -31,20 +31,17 @@ 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 { +final class DefaultPKCEProviderTest { @Test - public void testPkceExpected() throws NoSuchAlgorithmException { + void testPkceExpected() throws NoSuchAlgorithmException { PKCEProvider pkce = new DefaultPKCEProvider(); byte[] bytes = pkce.getCodeVerifier().getBytes(); @@ -61,7 +58,7 @@ public void testPkceExpected() throws NoSuchAlgorithmException { } @Test - public void testNoBase64Padding() throws NoSuchAlgorithmException { + 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 d054d7ee6..31c4e776e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -33,9 +33,9 @@ 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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.HttpTransport; import com.google.auth.TestUtils; @@ -43,13 +43,10 @@ import java.io.IOException; import java.util.Date; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Tests for {@link DownscopedCredentials}. */ -@RunWith(JUnit4.class) -public class DownscopedCredentialsTest { +class DownscopedCredentialsTest { private static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n" @@ -85,7 +82,7 @@ public HttpTransport create() { } @Test - public void refreshAccessToken() throws IOException { + void refreshAccessToken() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -116,7 +113,7 @@ public void refreshAccessToken() throws IOException { } @Test - public void refreshAccessToken_withCustomUniverseDomain() throws IOException { + void refreshAccessToken_withCustomUniverseDomain() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); String universeDomain = "foobar"; GoogleCredentials sourceCredentials = @@ -150,7 +147,7 @@ public void refreshAccessToken_withCustomUniverseDomain() throws IOException { } @Test - public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { + void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { // STS only returns expires_in if the source access token belongs to a service account. // For other source credential types, we can copy the source credentials expiration as // the generated downscoped token will always have the same expiration time as the source @@ -178,7 +175,7 @@ public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IO } @Test - public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { + void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -200,7 +197,7 @@ public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOEx } @Test - public void builder_noSourceCredential_throws() { + void builder_noSourceCredential_throws() { try { DownscopedCredentials.newBuilder() .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) @@ -213,7 +210,7 @@ public void builder_noSourceCredential_throws() { } @Test - public void builder_noCredentialAccessBoundary_throws() throws IOException { + void builder_noCredentialAccessBoundary_throws() throws IOException { try { DownscopedCredentials.newBuilder() .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) @@ -226,7 +223,7 @@ public void builder_noCredentialAccessBoundary_throws() throws IOException { } @Test - public void builder_noTransport_defaults() throws IOException { + void builder_noTransport_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = @@ -243,7 +240,7 @@ public void builder_noTransport_defaults() throws IOException { } @Test - public void builder_noUniverseDomain_defaults() throws IOException { + void builder_noUniverseDomain_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = @@ -262,7 +259,7 @@ public void builder_noUniverseDomain_defaults() throws IOException { } @Test - public void builder_universeDomainMismatch_throws() throws IOException { + void builder_universeDomainMismatch_throws() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); @@ -282,7 +279,7 @@ public void builder_universeDomainMismatch_throws() throws IOException { } @Test - public void builder_sourceUniverseDomainUnavailable_throws() throws IOException { + 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 e6991776d..da7ea8cc6 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java @@ -31,20 +31,20 @@ 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"; @@ -55,7 +55,7 @@ public class ExecutableResponseTest { private static final int EXPIRATION_DURATION = 3600; @Test - public void constructor_successOidcResponse() throws IOException { + void constructor_successOidcResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildOidcResponse()); assertTrue(response.isSuccessful()); @@ -68,8 +68,7 @@ public void constructor_successOidcResponse() throws IOException { } @Test - public void constructor_successOidcResponseMissingExpirationTimeField_notExpired() - throws IOException { + void constructor_successOidcResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("expiration_time"); @@ -85,7 +84,7 @@ public void constructor_successOidcResponseMissingExpirationTimeField_notExpired } @Test - public void constructor_successSamlResponse() throws IOException { + void constructor_successSamlResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildSamlResponse()); assertTrue(response.isSuccessful()); @@ -98,8 +97,7 @@ public void constructor_successSamlResponse() throws IOException { } @Test - public void constructor_successSamlResponseMissingExpirationTimeField_notExpired() - throws IOException { + void constructor_successSamlResponseMissingExpirationTimeField_notExpired() throws IOException { GenericJson jsonResponse = buildSamlResponse(); jsonResponse.remove("expiration_time"); @@ -115,7 +113,7 @@ public void constructor_successSamlResponseMissingExpirationTimeField_notExpired } @Test - public void constructor_validErrorResponse() throws IOException { + void constructor_validErrorResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildErrorResponse()); assertFalse(response.isSuccessful()); @@ -130,7 +128,7 @@ public void constructor_validErrorResponse() throws IOException { } @Test - public void constructor_errorResponseMissingCode_throws() throws IOException { + void constructor_errorResponseMissingCode_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; @@ -149,7 +147,7 @@ public void constructor_errorResponseMissingCode_throws() throws IOException { } @Test - public void constructor_errorResponseMissingMessage_throws() throws IOException { + void constructor_errorResponseMissingMessage_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; @@ -169,7 +167,7 @@ public void constructor_errorResponseMissingMessage_throws() throws IOException } @Test - public void constructor_successResponseMissingVersionField_throws() throws IOException { + void constructor_successResponseMissingVersionField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("version"); @@ -185,7 +183,7 @@ public void constructor_successResponseMissingVersionField_throws() throws IOExc } @Test - public void constructor_successResponseMissingSuccessField_throws() throws Exception { + void constructor_successResponseMissingSuccessField_throws() throws Exception { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("success"); @@ -201,7 +199,7 @@ public void constructor_successResponseMissingSuccessField_throws() throws Excep } @Test - public void constructor_successResponseMissingTokenTypeField_throws() throws IOException { + void constructor_successResponseMissingTokenTypeField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("token_type"); @@ -217,7 +215,7 @@ public void constructor_successResponseMissingTokenTypeField_throws() throws IOE } @Test - public void constructor_samlResponseMissingSubjectToken_throws() throws IOException { + void constructor_samlResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildSamlResponse(); Object[] values = new Object[] {null, ""}; @@ -237,7 +235,7 @@ public void constructor_samlResponseMissingSubjectToken_throws() throws IOExcept } @Test - public void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { + void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); Object[] values = new Object[] {null, ""}; @@ -257,7 +255,7 @@ public void constructor_oidcResponseMissingSubjectToken_throws() throws IOExcept } @Test - public void isExpired() throws IOException { + 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 8328ac54d..4913e5aec 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentialsTest.java @@ -32,13 +32,14 @@ package com.google.auth.oauth2; 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 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 com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -62,14 +63,11 @@ 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 +125,13 @@ public HttpTransport create() { } } - @Before - public void setup() { + @BeforeEach + void setup() { transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); } @Test - public void builder_allFields() throws IOException { + void builder_allFields() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -161,7 +159,7 @@ public void builder_allFields() throws IOException { } @Test - public void builder_minimumRequiredFieldsForRefresh() { + void builder_minimumRequiredFieldsForRefresh() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -182,7 +180,7 @@ public void builder_minimumRequiredFieldsForRefresh() { } @Test - public void builder_accessTokenOnly() { + void builder_accessTokenOnly() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAccessToken(AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build()) @@ -200,7 +198,7 @@ public void builder_accessTokenOnly() { } @Test - public void builder_credentialConstructor() { + void builder_credentialConstructor() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -226,7 +224,7 @@ public void builder_credentialConstructor() { } @Test - public void builder_accessTokenWithMissingRefreshFields() { + void builder_accessTokenWithMissingRefreshFields() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAccessToken(AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build()) @@ -247,7 +245,7 @@ public void builder_accessTokenWithMissingRefreshFields() { } @Test - public void builder_accessAndRefreshTokenNull_throws() { + void builder_accessAndRefreshTokenNull_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder().build(); fail("Should not be able to continue without exception."); @@ -261,7 +259,7 @@ public void builder_accessAndRefreshTokenNull_throws() { } @Test - public void builder_missingTokenUrl_throws() { + void builder_missingTokenUrl_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -279,7 +277,7 @@ public void builder_missingTokenUrl_throws() { } @Test - public void builder_missingClientId_throws() { + void builder_missingClientId_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -297,7 +295,7 @@ public void builder_missingClientId_throws() { } @Test - public void builder_missingClientSecret_throws() { + void builder_missingClientSecret_throws() { try { ExternalAccountAuthorizedUserCredentials.newBuilder() .setRefreshToken(REFRESH_TOKEN) @@ -315,7 +313,7 @@ public void builder_missingClientSecret_throws() { } @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + void builder_missingUniverseDomain_defaults() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -342,7 +340,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { } @Test - public void toBuilder_allFields() { + void toBuilder_allFields() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -363,7 +361,7 @@ public void toBuilder_allFields() { } @Test - public void toBuilder_missingUniverseDomain_defaults() throws IOException { + void toBuilder_missingUniverseDomain_defaults() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -384,7 +382,7 @@ public void toBuilder_missingUniverseDomain_defaults() throws IOException { } @Test - public void fromJson_allFields() throws IOException { + void fromJson_allFields() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson( buildJsonCredentials(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -401,7 +399,7 @@ public void fromJson_allFields() throws IOException { } @Test - public void fromJson_minimumRequiredFieldsForRefresh() throws IOException { + void fromJson_minimumRequiredFieldsForRefresh() throws IOException { GenericJson json = new GenericJson(); json.put("client_id", CLIENT_ID); json.put("client_secret", CLIENT_SECRET); @@ -423,7 +421,7 @@ public void fromJson_minimumRequiredFieldsForRefresh() throws IOException { } @Test - public void fromJson_accessTokenOnly_notSupported() throws IOException { + void fromJson_accessTokenOnly_notSupported() throws IOException { GenericJson json = new GenericJson(); json.put("access_token", ACCESS_TOKEN); @@ -440,7 +438,7 @@ public void fromJson_accessTokenOnly_notSupported() throws IOException { } @Test - public void fromJson_missingRefreshToken_throws() throws IOException { + void fromJson_missingRefreshToken_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("refresh_token"); @@ -456,7 +454,7 @@ public void fromJson_missingRefreshToken_throws() throws IOException { } @Test - public void fromJson_missingTokenUrl_throws() throws IOException { + void fromJson_missingTokenUrl_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("token_url"); @@ -472,7 +470,7 @@ public void fromJson_missingTokenUrl_throws() throws IOException { } @Test - public void fromJson_missingClientId_throws() throws IOException { + void fromJson_missingClientId_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_id"); @@ -488,7 +486,7 @@ public void fromJson_missingClientId_throws() throws IOException { } @Test - public void fromJson_missingClientSecret_throws() throws IOException { + void fromJson_missingClientSecret_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_secret"); @@ -504,7 +502,7 @@ public void fromJson_missingClientSecret_throws() throws IOException { } @Test - public void fromJson_missingUniverseDomain_defaults() throws IOException { + void fromJson_missingUniverseDomain_defaults() throws IOException { GenericJson json = buildJsonCredentials(); json.remove("universe_domain"); @@ -523,7 +521,7 @@ public void fromJson_missingUniverseDomain_defaults() throws IOException { } @Test - public void fromStream_allFields() throws IOException { + void fromStream_allFields() throws IOException { GenericJson json = buildJsonCredentials(); ExternalAccountAuthorizedUserCredentials credentials = @@ -540,7 +538,7 @@ public void fromStream_allFields() throws IOException { } @Test - public void fromStream_minimumRequiredFieldsForRefresh() throws IOException { + void fromStream_minimumRequiredFieldsForRefresh() throws IOException { GenericJson json = new GenericJson(); json.put( "type", GoogleCredentialsInfo.EXTERNAL_ACCOUNT_AUTHORIZED_USER_CREDENTIALS.getFileType()); @@ -564,7 +562,7 @@ public void fromStream_minimumRequiredFieldsForRefresh() throws IOException { } @Test - public void fromStream_accessTokenOnly_notSupported() throws IOException { + void fromStream_accessTokenOnly_notSupported() throws IOException { GenericJson json = new GenericJson(); json.put("access_token", ACCESS_TOKEN); json.put( @@ -582,7 +580,7 @@ public void fromStream_accessTokenOnly_notSupported() throws IOException { } @Test - public void fromStream_missingRefreshToken_throws() throws IOException { + void fromStream_missingRefreshToken_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("refresh_token"); @@ -598,7 +596,7 @@ public void fromStream_missingRefreshToken_throws() throws IOException { } @Test - public void fromStream_missingTokenUrl_throws() throws IOException { + void fromStream_missingTokenUrl_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("token_url"); @@ -614,7 +612,7 @@ public void fromStream_missingTokenUrl_throws() throws IOException { } @Test - public void fromStream_missingClientId_throws() throws IOException { + void fromStream_missingClientId_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_id"); @@ -630,7 +628,7 @@ public void fromStream_missingClientId_throws() throws IOException { } @Test - public void fromStream_missingClientSecret_throws() throws IOException { + void fromStream_missingClientSecret_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.remove("client_secret"); @@ -646,7 +644,7 @@ public void fromStream_missingClientSecret_throws() throws IOException { } @Test - public void fromStream_missingUniverseDomain_defaults() throws IOException { + void fromStream_missingUniverseDomain_defaults() throws IOException { GenericJson json = buildJsonCredentials(); json.remove("universe_domain"); @@ -665,7 +663,7 @@ public void fromStream_missingUniverseDomain_defaults() throws IOException { } @Test - public void fromStream_invalidInputStream_throws() throws IOException { + void fromStream_invalidInputStream_throws() throws IOException { try { GenericJson json = buildJsonCredentials(); json.put("audience", new HashMap<>()); @@ -677,7 +675,7 @@ public void fromStream_invalidInputStream_throws() throws IOException { } @Test - public void createScoped_noChange() { + void createScoped_noChange() { ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setTokenUrl(TOKEN_URL) @@ -691,7 +689,7 @@ public void createScoped_noChange() { } @Test - public void createScopedRequired_false() { + void createScopedRequired_false() { ExternalAccountAuthorizedUserCredentials externalAccountAuthorizedUserCredentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setTokenUrl(TOKEN_URL) @@ -703,7 +701,7 @@ public void createScopedRequired_false() { } @Test - public void getRequestMetadata() throws IOException { + void getRequestMetadata() throws IOException { GoogleCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -714,7 +712,7 @@ public void getRequestMetadata() throws IOException { } @Test - public void getRequestMetadata_withQuotaProjectId() throws IOException { + void getRequestMetadata_withQuotaProjectId() throws IOException { GoogleCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -729,7 +727,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_withAccessToken() throws IOException { + void getRequestMetadata_withAccessToken() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setHttpTransportFactory(transportFactory) @@ -742,7 +740,7 @@ public void getRequestMetadata_withAccessToken() throws IOException { } @Test - public void refreshAccessToken() throws IOException { + void refreshAccessToken() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -753,7 +751,7 @@ public void refreshAccessToken() throws IOException { } @Test - public void refreshAccessToken_withRefreshTokenRotation() throws IOException { + void refreshAccessToken_withRefreshTokenRotation() throws IOException { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.fromJson(buildJsonCredentials(), transportFactory); @@ -769,7 +767,7 @@ public void refreshAccessToken_withRefreshTokenRotation() throws IOException { } @Test - public void refreshAccessToken_genericAuthError_throws() throws IOException { + void refreshAccessToken_genericAuthError_throws() throws IOException { transportFactory.transport.addResponseErrorSequence( TestUtils.buildHttpResponseException( "invalid_request", "Invalid request.", /* errorUri= */ null)); @@ -786,18 +784,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 +805,11 @@ public void refreshAccessToken_missingRefreshFields_throws() throws IOException .setHttpTransportFactory(transportFactory) .build(); - credentials.refreshAccessToken(); + assertThrows(IllegalStateException.class, () -> credentials.refreshAccessToken()); } @Test - public void hashCode_sameCredentials() { + void hashCode_sameCredentials() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -844,7 +842,7 @@ public void hashCode_sameCredentials() { } @Test - public void hashCode_differentCredentials() { + void hashCode_differentCredentials() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -876,7 +874,7 @@ public void hashCode_differentCredentials() { } @Test - public void hashCode_differentCredentialsWithCredentialsFile() throws IOException { + 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"); @@ -898,7 +896,7 @@ public void hashCode_differentCredentialsWithCredentialsFile() throws IOExceptio } @Test - public void equals_differentCredentials() throws IOException { + void equals_differentCredentials() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -917,7 +915,7 @@ public void equals_differentCredentials() throws IOException { } @Test - public void equals_differentAudience() { + void equals_differentAudience() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -941,7 +939,7 @@ public void equals_differentAudience() { } @Test - public void equals_differentClientId() { + void equals_differentClientId() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -965,7 +963,7 @@ public void equals_differentClientId() { } @Test - public void equals_differentClientSecret() { + void equals_differentClientSecret() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -989,7 +987,7 @@ public void equals_differentClientSecret() { } @Test - public void equals_differentRefreshToken() { + void equals_differentRefreshToken() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1013,7 +1011,7 @@ public void equals_differentRefreshToken() { } @Test - public void equals_differentTokenUrl() { + void equals_differentTokenUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1037,7 +1035,7 @@ public void equals_differentTokenUrl() { } @Test - public void equals_differentTokenInfoUrl() { + void equals_differentTokenInfoUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1061,7 +1059,7 @@ public void equals_differentTokenInfoUrl() { } @Test - public void equals_differentRevokeUrl() { + void equals_differentRevokeUrl() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1085,7 +1083,7 @@ public void equals_differentRevokeUrl() { } @Test - public void equals_differentAccessToken() { + void equals_differentAccessToken() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1109,7 +1107,7 @@ public void equals_differentAccessToken() { } @Test - public void equals_differentQuotaProjectId() { + void equals_differentQuotaProjectId() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1133,7 +1131,7 @@ public void equals_differentQuotaProjectId() { } @Test - public void equals_differentTransportFactory() { + void equals_differentTransportFactory() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1157,7 +1155,7 @@ public void equals_differentTransportFactory() { } @Test - public void equals_differentUniverseDomain() { + void equals_differentUniverseDomain() { ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() .setAudience(AUDIENCE) @@ -1182,7 +1180,7 @@ public void equals_differentUniverseDomain() { } @Test - public void toString_expectedFormat() { + void toString_expectedFormat() { AccessToken accessToken = new AccessToken(ACCESS_TOKEN, new Date()); ExternalAccountAuthorizedUserCredentials credentials = ExternalAccountAuthorizedUserCredentials.newBuilder() @@ -1221,7 +1219,7 @@ public void toString_expectedFormat() { } @Test - public void serialize() throws IOException, ClassNotFoundException { + 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 497ead12a..d45979cfb 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -32,12 +32,12 @@ package com.google.auth.oauth2; 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 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 com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -56,14 +56,11 @@ 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 +85,13 @@ public HttpTransport create() { private MockExternalAccountCredentialsTransportFactory transportFactory; - @Before - public void setup() { + @BeforeEach + void setup() { transportFactory = new MockExternalAccountCredentialsTransportFactory(); } @Test - public void fromStream_identityPoolCredentials() throws IOException { + void fromStream_identityPoolCredentials() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); ExternalAccountCredentials credential = @@ -104,7 +101,7 @@ public void fromStream_identityPoolCredentials() throws IOException { } @Test - public void fromStream_awsCredentials() throws IOException { + void fromStream_awsCredentials() throws IOException { GenericJson json = buildJsonAwsCredential(); ExternalAccountCredentials credential = @@ -114,7 +111,7 @@ public void fromStream_awsCredentials() throws IOException { } @Test - public void fromStream_pluggableAuthCredentials() throws IOException { + void fromStream_pluggableAuthCredentials() throws IOException { GenericJson json = buildJsonPluggableAuthCredential(); ExternalAccountCredentials credential = @@ -124,7 +121,7 @@ public void fromStream_pluggableAuthCredentials() throws IOException { } @Test - public void fromStream_invalidStream_throws() throws IOException { + void fromStream_invalidStream_throws() throws IOException { GenericJson json = buildJsonAwsCredential(); json.put("audience", new HashMap<>()); @@ -138,7 +135,7 @@ public void fromStream_invalidStream_throws() throws IOException { } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() throws IOException { try { ExternalAccountCredentials.fromStream( new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); @@ -149,7 +146,7 @@ public void fromStream_nullTransport_throws() throws IOException { } @Test - public void fromStream_nullOptionalField() throws IOException { + void fromStream_nullOptionalField() throws IOException { ExternalAccountCredentials credentials = ExternalAccountCredentials.fromStream( new ByteArrayInputStream( @@ -167,7 +164,7 @@ public void fromStream_nullOptionalField() throws IOException { } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { try { ExternalAccountCredentials.fromStream( /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -178,7 +175,7 @@ public void fromStream_nullStream_throws() throws IOException { } @Test - public void fromStream_invalidWorkloadAudience_throws() throws IOException { + void fromStream_invalidWorkloadAudience_throws() throws IOException { try { GenericJson json = buildJsonIdentityPoolWorkforceCredential(); json.put("audience", "invalidAudience"); @@ -191,7 +188,7 @@ public void fromStream_invalidWorkloadAudience_throws() throws IOException { } @Test - public void fromJson_identityPoolCredentialsWorkload() throws IOException { + void fromJson_identityPoolCredentialsWorkload() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -208,7 +205,7 @@ public void fromJson_identityPoolCredentialsWorkload() throws IOException { } @Test - public void fromJson_identityPoolCredentialsWorkforce() throws IOException { + void fromJson_identityPoolCredentialsWorkforce() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -226,8 +223,7 @@ public void fromJson_identityPoolCredentialsWorkforce() throws IOException { } @Test - public void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() - throws IOException { + void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set( "service_account_impersonation", buildServiceAccountImpersonationOptions(2800)); @@ -249,7 +245,7 @@ public void fromJson_identityPoolCredentialsWithServiceAccountImpersonationOptio } @Test - public void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOException { + void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOException { GenericJson identityPoolCredentialJson = buildJsonIdentityPoolCredential(); identityPoolCredentialJson.set("universe_domain", "universeDomain"); @@ -269,7 +265,7 @@ public void fromJson_identityPoolCredentialsWithUniverseDomain() throws IOExcept } @Test - public void fromJson_awsCredentials() throws IOException { + void fromJson_awsCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonAwsCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -284,7 +280,7 @@ public void fromJson_awsCredentials() throws IOException { } @Test - public void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() throws IOException { + void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson awsCredentialJson = buildJsonAwsCredential(); awsCredentialJson.set( "service_account_impersonation", buildServiceAccountImpersonationOptions(2800)); @@ -303,7 +299,7 @@ public void fromJson_awsCredentialsWithServiceAccountImpersonationOptions() thro } @Test - public void fromJson_awsCredentialsWithUniverseDomain() throws IOException { + void fromJson_awsCredentialsWithUniverseDomain() throws IOException { GenericJson awsCredentialJson = buildJsonAwsCredential(); awsCredentialJson.set("universe_domain", "universeDomain"); @@ -320,7 +316,7 @@ public void fromJson_awsCredentialsWithUniverseDomain() throws IOException { } @Test - public void fromJson_pluggableAuthCredentials() throws IOException { + void fromJson_pluggableAuthCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -341,7 +337,7 @@ public void fromJson_pluggableAuthCredentials() throws IOException { } @Test - public void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { + void fromJson_pluggableAuthCredentialsWorkforce() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -367,7 +363,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). @@ -395,7 +391,7 @@ public void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() throws I } @Test - public void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOptions() + void fromJson_pluggableAuthCredentialsWithServiceAccountImpersonationOptions() throws IOException { GenericJson pluggableAuthCredentialJson = buildJsonPluggableAuthCredential(); pluggableAuthCredentialJson.set( @@ -423,7 +419,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"); @@ -453,7 +449,7 @@ public void fromJson_pluggableAuthCredentials_withUniverseDomain() throws IOExce } @Test - public void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOException { + void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOException { GenericJson pluggableAuthCredentialJson = buildJsonPluggableAuthCredential(); pluggableAuthCredentialJson.set("universe_domain", "universeDomain"); @@ -477,7 +473,7 @@ public void fromJson_pluggableAuthCredentialsWithUniverseDomain() throws IOExcep } @Test - public void fromJson_nullJson_throws() throws IOException { + void fromJson_nullJson_throws() throws IOException { try { ExternalAccountCredentials.fromJson(/* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); fail("Exception should be thrown."); @@ -487,7 +483,7 @@ public void fromJson_nullJson_throws() throws IOException { } @Test - public void fromJson_nullTransport_throws() throws IOException { + void fromJson_nullTransport_throws() throws IOException { try { ExternalAccountCredentials.fromJson( new HashMap(), /* transportFactory= */ null); @@ -498,7 +494,7 @@ public void fromJson_nullTransport_throws() throws IOException { } @Test - public void fromJson_invalidWorkforceAudiences_throws() throws IOException { + void fromJson_invalidWorkforceAudiences_throws() throws IOException { List invalidAudiences = Arrays.asList( "//iam.googleapis.com/locations/global/workloadIdentityPools/pool/providers/provider", @@ -527,7 +523,7 @@ public void fromJson_invalidWorkforceAudiences_throws() throws IOException { } @Test - public void constructor_builder() throws IOException { + void constructor_builder() throws IOException { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -567,7 +563,7 @@ public void constructor_builder() throws IOException { } @Test - public void constructor_builder_defaultTokenUrl() { + void constructor_builder_defaultTokenUrl() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -584,7 +580,7 @@ public void constructor_builder_defaultTokenUrl() { } @Test - public void constructor_builder_defaultTokenUrlwithUniverseDomain() { + void constructor_builder_defaultTokenUrlwithUniverseDomain() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -602,7 +598,7 @@ public void constructor_builder_defaultTokenUrlwithUniverseDomain() { } @Test - public void constructor_builder_subjectTokenTypeEnum() { + void constructor_builder_subjectTokenTypeEnum() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -620,7 +616,7 @@ public void constructor_builder_subjectTokenTypeEnum() { } @Test - public void constructor_builder_invalidTokenUrl() { + void constructor_builder_invalidTokenUrl() { try { ExternalAccountCredentials.Builder builder = TestExternalAccountCredentials.newBuilder() @@ -637,7 +633,7 @@ public void constructor_builder_invalidTokenUrl() { } @Test - public void constructor_builder_invalidServiceAccountImpersonationUrl() { + void constructor_builder_invalidServiceAccountImpersonationUrl() { try { ExternalAccountCredentials.Builder builder = TestExternalAccountCredentials.newBuilder() @@ -655,7 +651,7 @@ public void constructor_builder_invalidServiceAccountImpersonationUrl() { } @Test - public void constructor_builderWithInvalidWorkforceAudiences_throws() { + void constructor_builderWithInvalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -690,7 +686,7 @@ public void constructor_builderWithInvalidWorkforceAudiences_throws() { } @Test - public void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { + void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); // No exception should be thrown. @@ -705,7 +701,7 @@ public void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience } @Test - public void constructor_builder_invalidTokenLifetime_throws() { + void constructor_builder_invalidTokenLifetime_throws() { Map invalidOptionsMap = new HashMap(); invalidOptionsMap.put("token_lifetime_seconds", "thisIsAString"); @@ -737,7 +733,7 @@ public void constructor_builder_invalidTokenLifetime_throws() { } @Test - public void constructor_builder_stringTokenLifetime() { + void constructor_builder_stringTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", "2800"); @@ -764,7 +760,7 @@ public void constructor_builder_stringTokenLifetime() { } @Test - public void constructor_builder_bigDecimalTokenLifetime() { + void constructor_builder_bigDecimalTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", new BigDecimal("2800")); @@ -791,7 +787,7 @@ public void constructor_builder_bigDecimalTokenLifetime() { } @Test - public void constructor_builder_integerTokenLifetime() { + void constructor_builder_integerTokenLifetime() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", Integer.valueOf(2800)); @@ -818,7 +814,7 @@ public void constructor_builder_integerTokenLifetime() { } @Test - public void constructor_builder_lowTokenLifetime_throws() { + void constructor_builder_lowTokenLifetime_throws() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", 599); @@ -848,7 +844,7 @@ public void constructor_builder_lowTokenLifetime_throws() { } @Test - public void constructor_builder_highTokenLifetime_throws() { + void constructor_builder_highTokenLifetime_throws() { Map optionsMap = new HashMap(); optionsMap.put("token_lifetime_seconds", 43201); @@ -878,7 +874,7 @@ public void constructor_builder_highTokenLifetime_throws() { } @Test - public void exchangeExternalCredentialForAccessToken() throws IOException { + void exchangeExternalCredentialForAccessToken() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -902,7 +898,7 @@ public void exchangeExternalCredentialForAccessToken() throws IOException { } @Test - public void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { + void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -927,7 +923,7 @@ public void exchangeExternalCredentialForAccessToken_withInternalOptions() throw } @Test - public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() + void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() throws IOException { ExternalAccountCredentials identityPoolCredential = ExternalAccountCredentials.fromJson( @@ -961,9 +957,8 @@ public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserPro } @Test - public void - exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() - throws IOException { + void exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() + throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), transportFactory); @@ -988,7 +983,7 @@ public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserPro } @Test - public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() + void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -1025,7 +1020,7 @@ public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersona } @Test - public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOptions() + void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOptions() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -1061,7 +1056,7 @@ public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersona } @Test - public void exchangeExternalCredentialForAccessToken_throws() throws IOException { + void exchangeExternalCredentialForAccessToken_throws() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -1085,7 +1080,7 @@ public void exchangeExternalCredentialForAccessToken_throws() throws IOException } @Test - public void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredentialsThrows() + void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredentialsThrows() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); json.put("service_account_impersonation_url", "https://iamcredentials.googleapis.com"); @@ -1106,7 +1101,7 @@ public void exchangeExternalCredentialForAccessToken_invalidImpersonatedCredenti } @Test - public void getRequestMetadata_withQuotaProjectId() throws IOException { + void getRequestMetadata_withQuotaProjectId() throws IOException { TestExternalAccountCredentials testCredentials = (TestExternalAccountCredentials) TestExternalAccountCredentials.newBuilder() @@ -1125,7 +1120,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { Map impersonationOpts = new HashMap() { { @@ -1159,7 +1154,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void validateTokenUrl_validUrls() { + void validateTokenUrl_validUrls() { List validUrls = Arrays.asList( "https://sts.googleapis.com", @@ -1181,7 +1176,7 @@ public void validateTokenUrl_validUrls() { } @Test - public void validateTokenUrl_invalidUrls() { + void validateTokenUrl_invalidUrls() { List invalidUrls = Arrays.asList( "sts.googleapis.com", @@ -1204,7 +1199,7 @@ public void validateTokenUrl_invalidUrls() { } @Test - public void validateServiceAccountImpersonationUrls_validUrls() { + void validateServiceAccountImpersonationUrls_validUrls() { List validUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -1227,7 +1222,7 @@ public void validateServiceAccountImpersonationUrls_validUrls() { } @Test - public void validateServiceAccountImpersonationUrls_invalidUrls() { + 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 1dc05d06f..0774c6e7d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountSupplierContextTest.java @@ -31,15 +31,15 @@ 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() { + void constructor_builder() { String expectedAudience = "//iam.googleapis.com/locations/global/workloadPools/pool/providers/provider"; String expectedTokenType = SubjectTokenTypes.JWT.value; @@ -54,7 +54,7 @@ public void constructor_builder() { } @Test - public void constructor_builder_subjectTokenEnum() { + 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 bef50360c..b55514916 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTest.java @@ -31,13 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -54,13 +54,10 @@ 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 = @@ -88,7 +85,7 @@ public class GdchCredentialsTest extends BaseSerializationTest { private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); @Test - public void fromJSON_getProjectId() throws IOException { + void fromJSON_getProjectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -104,7 +101,7 @@ public void fromJSON_getProjectId() throws IOException { } @Test - public void fromJSON_getServiceIdentityName() throws IOException { + void fromJSON_getServiceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -120,7 +117,7 @@ public void fromJSON_getServiceIdentityName() throws IOException { } @Test - public void fromJSON_getCaCertPath() throws IOException { + void fromJSON_getCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -136,7 +133,7 @@ public void fromJSON_getCaCertPath() throws IOException { } @Test - public void fromJSON_getTokenServerUri() throws IOException { + void fromJSON_getTokenServerUri() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -152,7 +149,7 @@ public void fromJSON_getTokenServerUri() throws IOException { } @Test - public void fromJSON_nullFormatVersion() throws IOException { + void fromJSON_nullFormatVersion() throws IOException { GenericJson json = writeGdchServiceAccountJson( null, @@ -178,7 +175,7 @@ public void fromJSON_nullFormatVersion() throws IOException { } @Test - public void fromJSON_nullProjectId() throws IOException { + void fromJSON_nullProjectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -204,7 +201,7 @@ public void fromJSON_nullProjectId() throws IOException { } @Test - public void fromJSON_nullPrivateKeyId() throws IOException { + void fromJSON_nullPrivateKeyId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -230,7 +227,7 @@ public void fromJSON_nullPrivateKeyId() throws IOException { } @Test - public void fromJSON_nullPrivateKey() throws IOException { + void fromJSON_nullPrivateKey() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -256,7 +253,7 @@ public void fromJSON_nullPrivateKey() throws IOException { } @Test - public void fromJSON_nullServiceIdentityName() throws IOException { + void fromJSON_nullServiceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -282,7 +279,7 @@ public void fromJSON_nullServiceIdentityName() throws IOException { } @Test - public void fromJSON_nullCaCertPath() throws IOException { + void fromJSON_nullCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -297,7 +294,7 @@ public void fromJSON_nullCaCertPath() throws IOException { } @Test - public void fromJSON_nullTokenServerUri() throws IOException { + void fromJSON_nullTokenServerUri() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -323,7 +320,7 @@ public void fromJSON_nullTokenServerUri() throws IOException { } @Test - public void fromJSON_invalidFormatVersion() throws IOException { + void fromJSON_invalidFormatVersion() throws IOException { GenericJson json = writeGdchServiceAccountJson( "100", @@ -345,7 +342,7 @@ public void fromJSON_invalidFormatVersion() throws IOException { } @Test - public void fromJSON_invalidCaCertPath() throws IOException { + void fromJSON_invalidCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -365,7 +362,7 @@ public void fromJSON_invalidCaCertPath() throws IOException { } @Test - public void fromJSON_emptyCaCertPath() throws IOException { + void fromJSON_emptyCaCertPath() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -380,7 +377,7 @@ public void fromJSON_emptyCaCertPath() throws IOException { } @Test - public void fromJSON_transportFactoryForGdch() throws IOException { + void fromJSON_transportFactoryForGdch() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -397,7 +394,7 @@ public void fromJSON_transportFactoryForGdch() throws IOException { } @Test - public void fromJSON_hasAccessToken() throws IOException { + void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = writeGdchServiceAccountJson( @@ -418,7 +415,7 @@ public void fromJSON_hasAccessToken() throws IOException { } @Test - public void createWithGdchAudience_correct() throws IOException { + void createWithGdchAudience_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -446,7 +443,7 @@ public void createWithGdchAudience_correct() throws IOException { } @Test - public void createWithGdchAudience_nullApiAudience() throws IOException { + void createWithGdchAudience_nullApiAudience() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -467,7 +464,7 @@ public void createWithGdchAudience_nullApiAudience() throws IOException { } @Test - public void createAssertion_correct() throws IOException { + void createAssertion_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -495,7 +492,7 @@ public void createAssertion_correct() throws IOException { } @Test - public void refreshAccessToken_correct() throws IOException { + void refreshAccessToken_correct() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = @@ -532,7 +529,7 @@ public void refreshAccessToken_correct() throws IOException { } @Test - public void refreshAccessToken_nullApiAudience() throws IOException { + void refreshAccessToken_nullApiAudience() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = @@ -564,7 +561,7 @@ public void refreshAccessToken_nullApiAudience() throws IOException { } @Test - public void getIssuerSubjectValue_correct() throws IOException { + void getIssuerSubjectValue_correct() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -583,7 +580,7 @@ public void getIssuerSubjectValue_correct() throws IOException { } @Test - public void equals_same() throws IOException { + void equals_same() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -614,7 +611,7 @@ public void equals_same() throws IOException { } @Test - public void equals_false_projectId() throws IOException { + void equals_false_projectId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -645,7 +642,7 @@ public void equals_false_projectId() throws IOException { } @Test - public void equals_false_keyId() throws IOException { + void equals_false_keyId() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -676,7 +673,7 @@ public void equals_false_keyId() throws IOException { } @Test - public void equals_false_serviceIdentityName() throws IOException { + void equals_false_serviceIdentityName() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -707,7 +704,7 @@ public void equals_false_serviceIdentityName() throws IOException { } @Test - public void equals_false_caCertPath() throws IOException { + void equals_false_caCertPath() throws IOException { File tmpDirectory = Files.createTempDirectory("tmpDirectory").toFile(); File testCaCertFile = File.createTempFile("testCert", ".pem", tmpDirectory); GenericJson json = @@ -742,7 +739,7 @@ public void equals_false_caCertPath() throws IOException { } @Test - public void equals_false_tokenServer() throws IOException { + void equals_false_tokenServer() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -773,7 +770,7 @@ public void equals_false_tokenServer() throws IOException { } @Test - public void equals_false_apiAudience() throws IOException { + void equals_false_apiAudience() throws IOException { URI otherApiAudience = URI.create("https://foo1.com/bar"); GenericJson json = @@ -805,7 +802,7 @@ public void equals_false_apiAudience() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -832,7 +829,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { GenericJson json = writeGdchServiceAccountJson( FORMAT_VERSION, @@ -861,7 +858,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize_correct() throws IOException, ClassNotFoundException { + void serialize_correct() throws IOException, ClassNotFoundException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); GenericJson json = writeGdchServiceAccountJson( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java b/oauth2_http/javatests/com/google/auth/oauth2/GdchCredentialsTestUtil.java index 51880ddcc..76385a5e8 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, diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java index 4fd5da43e..7c883df0f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleAuthUtilsTest.java @@ -31,16 +31,16 @@ 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() { + 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 cd577bbf5..503c87d54 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -31,7 +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; @@ -52,13 +59,10 @@ 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"; @@ -96,7 +100,7 @@ public class GoogleCredentialsTest extends BaseSerializationTest { private static final String TPC_UNIVERSE = "foo.bar"; @Test - public void getApplicationDefault_nullTransport_throws() throws IOException { + void getApplicationDefault_nullTransport_throws() throws IOException { try { GoogleCredentials.getApplicationDefault(null); fail(); @@ -106,7 +110,7 @@ public void getApplicationDefault_nullTransport_throws() throws IOException { } @Test - public void fromStream_unknownType_throws() throws IOException { + void fromStream_unknownType_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); GenericJson json = new GenericJson(); json.put("type", "unsupported_credential"); @@ -125,7 +129,7 @@ public void fromStream_unknownType_throws() throws IOException { } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { GoogleCredentials.fromStream(stream, null); @@ -136,7 +140,7 @@ public void fromStream_nullTransport_throws() throws IOException { } @Test - public void fromStream_noType_throws() throws IOException { + void fromStream_noType_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); GenericJson json = ServiceAccountCredentialsTest.writeServiceAccountJson( @@ -153,13 +157,13 @@ public void fromStream_noType_throws() throws IOException { } @Test - public void fromStream_nullStream_throws() { + void fromStream_nullStream_throws() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); assertThrows(NullPointerException.class, () -> GoogleCredentials.parseJsonInputStream(null)); } @Test - public void fromStream_serviceAccount_noUniverse_providesToken() throws IOException { + void fromStream_serviceAccount_noUniverse_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -182,7 +186,7 @@ public void fromStream_serviceAccount_noUniverse_providesToken() throws IOExcept } @Test - public void fromStream_serviceAccount_Universe_noToken() throws IOException { + void fromStream_serviceAccount_Universe_noToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -201,7 +205,7 @@ public void fromStream_serviceAccount_Universe_noToken() throws IOException { } @Test - public void fromStream_serviceAccountNoClientId_throws() throws IOException { + void fromStream_serviceAccountNoClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -210,7 +214,7 @@ public void fromStream_serviceAccountNoClientId_throws() throws IOException { } @Test - public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { + void fromStream_serviceAccountNoClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -219,7 +223,7 @@ public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { } @Test - public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { + void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -228,7 +232,7 @@ public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { } @Test - public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { + void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -237,7 +241,7 @@ public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException } @Test - public void fromStream_gdchServiceAccount_correct() throws IOException { + void fromStream_gdchServiceAccount_correct() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( @@ -273,7 +277,7 @@ public void fromStream_gdchServiceAccount_correct() throws IOException { } @Test - public void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOException { + void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( null, @@ -288,7 +292,7 @@ public void fromStream_gdchServiceAccountNoFormatVersion_throws() throws IOExcep } @Test - public void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException { + void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -303,7 +307,7 @@ public void fromStream_gdchServiceAccountNoProjectId_throws() throws IOException } @Test - public void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOException { + void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -318,7 +322,7 @@ public void fromStream_gdchServiceAccountNoPrivateKeyId_throws() throws IOExcept } @Test - public void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOException { + void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -333,7 +337,7 @@ public void fromStream_gdchServiceAccountNoPrivateKey_throws() throws IOExceptio } @Test - public void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws IOException { + void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -348,7 +352,7 @@ public void fromStream_gdchServiceAccountNoServiceIdentityName_throws() throws I } @Test - public void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOException { + void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -363,7 +367,7 @@ public void fromStream_gdchServiceAccountNoTokenServerUri_throws() throws IOExce } @Test - public void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IOException { + void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( "100", @@ -380,7 +384,7 @@ public void fromStream_gdchServiceAccountInvalidFormatVersion_throws() throws IO } @Test - public void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOException { + void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -397,7 +401,7 @@ public void fromStream_gdchServiceAccountInvalidCaCertPath_throws() throws IOExc } @Test - public void fromStream_userCredentials_providesToken() throws IOException { + 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); @@ -413,7 +417,7 @@ public void fromStream_userCredentials_providesToken() throws IOException { } @Test - public void fromStream_userCredentials_defaultUniverse() throws IOException { + void fromStream_userCredentials_defaultUniverse() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -425,7 +429,7 @@ public void fromStream_userCredentials_defaultUniverse() throws IOException { } @Test - public void fromStream_userCredentials_NoClientId_throws() throws IOException { + void fromStream_userCredentials_NoClientId_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(null, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -433,7 +437,7 @@ public void fromStream_userCredentials_NoClientId_throws() throws IOException { } @Test - public void fromStream_userCredentials_NoClientSecret_throws() throws IOException { + void fromStream_userCredentials_NoClientSecret_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(USER_CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); @@ -441,7 +445,7 @@ public void fromStream_userCredentials_NoClientSecret_throws() throws IOExceptio } @Test - public void fromStream_userCredentials_NoRefreshToken_throws() throws IOException { + void fromStream_userCredentials_NoRefreshToken_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, null, QUOTA_PROJECT); @@ -450,7 +454,7 @@ public void fromStream_userCredentials_NoRefreshToken_throws() throws IOExceptio } @Test - public void fromStream_identityPoolCredentials_providesToken() throws IOException { + void fromStream_identityPoolCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -470,7 +474,7 @@ public void fromStream_identityPoolCredentials_providesToken() throws IOExceptio } @Test - public void fromStream_identityPoolCredentials_defaultUniverse() throws IOException { + void fromStream_identityPoolCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -487,7 +491,7 @@ public void fromStream_identityPoolCredentials_defaultUniverse() throws IOExcept } @Test - public void fromStream_awsCredentials_providesToken() throws IOException { + void fromStream_awsCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -507,7 +511,7 @@ public void fromStream_awsCredentials_providesToken() throws IOException { } @Test - public void fromStream_awsCredentials_defaultUniverse() throws IOException { + void fromStream_awsCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -524,7 +528,7 @@ public void fromStream_awsCredentials_defaultUniverse() throws IOException { } @Test - public void fromStream_pluggableAuthCredentials_providesToken() throws IOException { + void fromStream_pluggableAuthCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -547,7 +551,7 @@ public void fromStream_pluggableAuthCredentials_providesToken() throws IOExcepti } @Test - public void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { + void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -560,8 +564,7 @@ public void fromStream_pluggableAuthCredentials_defaultUniverse() throws IOExcep } @Test - public void fromStream_externalAccountAuthorizedUserCredentials_providesToken() - throws IOException { + void fromStream_externalAccountAuthorizedUserCredentials_providesToken() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); InputStream stream = @@ -575,8 +578,7 @@ public void fromStream_externalAccountAuthorizedUserCredentials_providesToken() } @Test - public void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() - throws IOException { + void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse() throws IOException { MockExternalAccountAuthorizedUserCredentialsTransportFactory transportFactory = new MockExternalAccountAuthorizedUserCredentialsTransportFactory(); @@ -590,7 +592,7 @@ public void fromStream_externalAccountAuthorizedUserCredentials_defaultUniverse( } @Test - public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { + void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -632,7 +634,7 @@ public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOE } @Test - public void fromStream_Impersonation_defaultUniverse() throws IOException { + void fromStream_Impersonation_defaultUniverse() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -657,7 +659,7 @@ public void fromStream_Impersonation_defaultUniverse() throws IOException { } @Test - public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { + void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -696,7 +698,7 @@ public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws } @Test - public void createScoped_overloadCallsImplementation() { + void createScoped_overloadCallsImplementation() { final AtomicReference> called = new AtomicReference<>(); final GoogleCredentials expectedScopedCredentials = new GoogleCredentials(); @@ -716,7 +718,7 @@ public GoogleCredentials createScoped(Collection scopes) { } @Test - public void create_withoutUniverse() throws IOException { + void create_withoutUniverse() throws IOException { AccessToken token = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); GoogleCredentials credentials = GoogleCredentials.create(token); @@ -725,7 +727,7 @@ public void create_withoutUniverse() throws IOException { } @Test - public void create_withUniverse() throws IOException { + void create_withUniverse() throws IOException { AccessToken token = AccessToken.newBuilder().setTokenValue(ACCESS_TOKEN).build(); GoogleCredentials credentials = GoogleCredentials.create("some-universe", token); @@ -734,7 +736,7 @@ public void create_withUniverse() throws IOException { } @Test - public void buildWithQuotaProject() { + void buildWithQuotaProject() { final GoogleCredentials googleCredentials = new GoogleCredentials.Builder().setQuotaProjectId("old_quota").build(); GoogleCredentials withUpdatedQuota = googleCredentials.createWithQuotaProject("new_quota"); @@ -750,7 +752,7 @@ public void buildWithQuotaProject() { } @Test - public void buildWithUniverseDomain() throws IOException { + void buildWithUniverseDomain() throws IOException { final GoogleCredentials original = new GoogleCredentials.Builder().setUniverseDomain("universe1").build(); GoogleCredentials updated = original.toBuilder().setUniverseDomain("universe2").build(); @@ -770,7 +772,7 @@ public void buildWithUniverseDomain() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final GoogleCredentials testCredentials = new GoogleCredentials.Builder().build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(testCredentials); assertEquals(testCredentials, deserializedCredentials); @@ -780,7 +782,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { String expectedToString = String.format( "GoogleCredentials{quotaProjectId=%s, universeDomain=%s, isExplicitUniverseDomain=%s}", @@ -791,7 +793,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { GoogleCredentials credentials = GoogleCredentials.newBuilder().setUniverseDomain("some-domain").build(); GoogleCredentials otherCredentials = @@ -800,7 +802,7 @@ public void hashCode_equals() throws IOException { } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { GoogleCredentials credentials = GoogleCredentials.newBuilder().setUniverseDomain("some-domain").build(); GoogleCredentials otherCredentials = @@ -821,7 +823,7 @@ private static void testFromStreamException(InputStream stream, String expectedM } @Test - public void getCredentialInfo_serviceAccountCredentials() throws IOException { + void getCredentialInfo_serviceAccountCredentials() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -835,7 +837,7 @@ public void getCredentialInfo_serviceAccountCredentials() throws IOException { } @Test - public void getCredentialInfo_userCredentials() throws IOException { + void getCredentialInfo_userCredentials() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, null); @@ -849,7 +851,7 @@ public void getCredentialInfo_userCredentials() throws IOException { } @Test - public void getCredentialInfo_gdchCredentials() throws IOException { + void getCredentialInfo_gdchCredentials() throws IOException { InputStream gdchServiceAccountStream = GdchCredentialsTest.writeGdchServiceAccountStream( GDCH_SA_FORMAT_VERSION, @@ -869,7 +871,7 @@ public void getCredentialInfo_gdchCredentials() throws IOException { } @Test - public void getCredentialInfo_externalAccount() throws IOException { + void getCredentialInfo_externalAccount() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -889,7 +891,7 @@ public void getCredentialInfo_externalAccount() throws IOException { } @Test - public void getCredentialInfo_externalAccountUserCredentials() throws IOException { + void getCredentialInfo_externalAccountUserCredentials() throws IOException { InputStream externalAccountUserCredentialStream = ExternalAccountAuthorizedUserCredentialsTest.writeExternalAccountUserCredentialStream( USER_CLIENT_ID, @@ -909,7 +911,7 @@ public void getCredentialInfo_externalAccountUserCredentials() throws IOExceptio } @Test - public void getCredentialInfo_impersonatedServiceAccount() throws IOException { + 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 bf7946164..2a04d7710 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -46,7 +46,7 @@ import com.google.auth.Credentials; import com.google.auth.http.HttpCredentialsAdapter; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Integration tests for Downscoping with Credential Access Boundaries via {@link @@ -56,7 +56,7 @@ * GOOGLE_APPLICATION_CREDENTIALS to point to the same service account configured in the setup * script (downscoping-with-cab-setup.sh). */ -public final class ITDownscopingTest { +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"; @@ -93,7 +93,7 @@ public final class ITDownscopingTest { * in the same bucket. */ @Test - public void downscoping_serviceAccountSourceWithRefresh() throws IOException { + void downscoping_serviceAccountSourceWithRefresh() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index 25982e544..d1574a06a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java @@ -31,8 +31,8 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -55,8 +55,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 +66,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 +79,8 @@ public final class ITWorkloadIdentityFederationTest { private String clientEmail; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { GenericJson keys = getServiceAccountKeyFileAsJson(); clientEmail = (String) keys.get("client_email"); } @@ -93,7 +93,7 @@ public void setup() throws IOException { * service account key. Retrieves the OIDC token from a file. */ @Test - public void identityPoolCredentials() throws IOException { + void identityPoolCredentials() throws IOException { IdentityPoolCredentials identityPoolCredentials = (IdentityPoolCredentials) ExternalAccountCredentials.fromJson( @@ -112,7 +112,7 @@ public void identityPoolCredentials() throws IOException { * service account key. */ @Test - public void awsCredentials() throws Exception { + void awsCredentials() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -163,7 +163,7 @@ public void awsCredentials() throws Exception { * to impersonate the original service account key. */ @Test - public void awsCredentials_withProgrammaticAuth() throws Exception { + void awsCredentials_withProgrammaticAuth() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -214,7 +214,7 @@ public void awsCredentials_withProgrammaticAuth() throws Exception { * service account key. Runs an executable to get the OIDC token. */ @Test - public void pluggableAuthCredentials() throws IOException { + void pluggableAuthCredentials() throws IOException { PluggableAuthCredentials pluggableAuthCredentials = (PluggableAuthCredentials) ExternalAccountCredentials.fromJson( @@ -228,7 +228,7 @@ public void pluggableAuthCredentials() throws IOException { * for token_lifetime_seconds and validates that the lifetime is used for the access token. */ @Test - public void identityPoolCredentials_withServiceAccountImpersonationOptions() throws IOException { + void identityPoolCredentials_withServiceAccountImpersonationOptions() throws IOException { GenericJson identityPoolCredentialConfig = buildIdentityPoolCredentialConfig(); Map map = new HashMap(); map.put("token_lifetime_seconds", 2800); @@ -255,7 +255,7 @@ public void identityPoolCredentials_withServiceAccountImpersonationOptions() thr * when get() is called. */ @Test - public void identityPoolCredentials_withProgrammaticAuth() throws IOException { + 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 54a3753e6..c9413c6cb 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -30,32 +30,29 @@ */ 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 @@ -65,7 +62,7 @@ public void setup() throws IOException { } @Test - public void sign_success_noRetry() { + void sign_success_noRetry() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -91,7 +88,7 @@ public void sign_success_noRetry() { // 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() { + void sign_retryTwoTimes_success() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -125,7 +122,7 @@ public void sign_retryTwoTimes_success() { // 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() { + void sign_retryThreeTimes_success() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -162,7 +159,7 @@ public void sign_retryThreeTimes_success() { // 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() { + void sign_retryThreeTimes_exception() { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockIAMCredentialsServiceTransportFactory transportFactory = @@ -207,7 +204,7 @@ public void sign_retryThreeTimes_exception() { } @Test - public void sign_4xxError_noRetry_exception() { + 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 7dbf770c3..e3dcec4b5 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java @@ -31,19 +31,16 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link IdTokenCredentials}. */ -@RunWith(JUnit4.class) -public class IdTokenCredentialsTest extends BaseSerializationTest { +class IdTokenCredentialsTest extends BaseSerializationTest { @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -69,7 +66,7 @@ public void hashCode_equals() throws IOException { } @Test - public void toString_equals() throws IOException { + void toString_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -95,7 +92,7 @@ public void toString_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java index a8831a21b..52fa2c008 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"; @@ -54,14 +51,14 @@ public class IdTokenTest extends BaseSerializationTest { private static final Date EXPIRATION_DATE = new Date((long) 1565391138 * 1000); @Test - public void constructor() throws IOException { + void constructor() throws IOException { IdToken idToken = IdToken.create(TOKEN_1); assertEquals(TOKEN_1, idToken.getTokenValue()); assertEquals(EXPIRATION_DATE, idToken.getExpirationTime()); } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertTrue(accessToken.equals(otherAccessToken)); @@ -69,7 +66,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_token() throws IOException { + void equals_false_token() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_2); assertFalse(accessToken.equals(otherAccessToken)); @@ -77,7 +74,7 @@ public void equals_false_token() throws IOException { } @Test - public void toString_test() throws IOException { + void toString_test() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); String expectedToString = String.format( @@ -87,14 +84,14 @@ public void toString_test() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); @@ -103,7 +100,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void token_with_0x20() throws IOException { + 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 2ee80c3d3..aecd82f94 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsSourceTest.java @@ -31,21 +31,22 @@ 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 { +class IdentityPoolCredentialsSourceTest { @Test - public void constructor_certificateConfig() { + void constructor_certificateConfig() { Map certificateMap = new HashMap<>(); certificateMap.put("certificate_config_location", "/path/to/certificate"); @@ -64,7 +65,7 @@ public void constructor_certificateConfig() { } @Test - public void constructor_certificateConfig_useDefault() { + void constructor_certificateConfig_useDefault() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); @@ -80,7 +81,7 @@ public void constructor_certificateConfig_useDefault() { } @Test - public void constructor_certificateConfig_missingRequiredFields_throws() { + 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"); @@ -98,7 +99,7 @@ public void constructor_certificateConfig_missingRequiredFields_throws() { } @Test - public void constructor_certificateConfig_bothFieldsSet_throws() { + void constructor_certificateConfig_bothFieldsSet_throws() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); certificateMap.put("certificate_config_location", "/path/to/certificate"); @@ -117,7 +118,7 @@ public void constructor_certificateConfig_bothFieldsSet_throws() { } @Test - public void constructor_certificateConfig_trustChainPath() { + void constructor_certificateConfig_trustChainPath() { Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", true); certificateMap.put("trust_chain_path", "path/to/trust/chain"); @@ -135,7 +136,7 @@ public void constructor_certificateConfig_trustChainPath() { } @Test - public void constructor_certificateConfig_invalidType_throws() { + 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 cce03e085..6997c79b0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java @@ -34,7 +34,12 @@ 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.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 org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -59,13 +64,13 @@ 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"; @@ -73,7 +78,7 @@ public class IdentityPoolCredentialsTest extends BaseSerializationTest { (ExternalAccountSupplierContext context) -> "testSubjectToken"; @Test - public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + void createdScoped_clonedCredentialWithAddedScopes() throws IOException { IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder(createBaseFileSourcedCredentials()) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -104,7 +109,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { } @Test - public void retrieveSubjectToken_fileSourced() throws IOException { + void retrieveSubjectToken_fileSourced() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -130,7 +135,7 @@ public void retrieveSubjectToken_fileSourced() throws IOException { } @Test - public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { + void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -171,7 +176,7 @@ public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException } @Test - public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { + void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -192,7 +197,7 @@ public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOExc } @Test - public void retrieveSubjectToken_noFile_throws() { + void retrieveSubjectToken_noFile_throws() { Map credentialSourceMap = new HashMap<>(); String path = "badPath"; credentialSourceMap.put("file", path); @@ -215,7 +220,7 @@ public void retrieveSubjectToken_noFile_throws() { } @Test - public void retrieveSubjectToken_urlSourced() throws IOException { + void retrieveSubjectToken_urlSourced() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -232,7 +237,7 @@ public void retrieveSubjectToken_urlSourced() throws IOException { } @Test - public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { + void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -257,7 +262,7 @@ public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { } @Test - public void retrieveSubjectToken_urlSourcedCredential_throws() { + void retrieveSubjectToken_urlSourcedCredential_throws() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -283,7 +288,7 @@ public void retrieveSubjectToken_urlSourcedCredential_throws() { } @Test - public void retrieveSubjectToken_provider() throws IOException { + void retrieveSubjectToken_provider() throws IOException { ExternalAccountSupplierContext emptyContext = ExternalAccountSupplierContext.newBuilder().setAudience("").setSubjectTokenType("").build(); IdentityPoolCredentials credentials = @@ -298,7 +303,7 @@ public void retrieveSubjectToken_provider() throws IOException { } @Test - public void retrieveSubjectToken_providerThrowsError() throws IOException { + void retrieveSubjectToken_providerThrowsError() throws IOException { IOException testException = new IOException("test"); IdentityPoolSubjectTokenSupplier errorProvider = @@ -320,7 +325,7 @@ public void retrieveSubjectToken_providerThrowsError() throws IOException { } @Test - public void retrieveSubjectToken_supplierPassesContext() throws IOException { + void retrieveSubjectToken_supplierPassesContext() throws IOException { ExternalAccountSupplierContext expectedContext = ExternalAccountSupplierContext.newBuilder() .setAudience(createBaseFileSourcedCredentials().getAudience()) @@ -343,7 +348,7 @@ public void retrieveSubjectToken_supplierPassesContext() throws IOException { } @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -371,7 +376,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc } @Test - public void refreshAccessToken_internalOptionsSet() throws IOException { + void refreshAccessToken_internalOptionsSet() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -404,7 +409,7 @@ public void refreshAccessToken_internalOptionsSet() throws IOException { } @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -435,7 +440,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept } @Test - public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -476,7 +481,7 @@ public void refreshAccessToken_withServiceAccountImpersonationOptions() throws I } @Test - public void refreshAccessToken_Provider() throws IOException { + void refreshAccessToken_Provider() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -503,7 +508,7 @@ public void refreshAccessToken_Provider() throws IOException { } @Test - public void refreshAccessToken_providerWithServiceAccountImpersonation() throws IOException { + void refreshAccessToken_providerWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -533,7 +538,7 @@ public void refreshAccessToken_providerWithServiceAccountImpersonation() throws } @Test - public void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { + void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -568,8 +573,7 @@ public void refreshAccessToken_workforceWithServiceAccountImpersonation() throws } @Test - public void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() - throws IOException { + void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -604,7 +608,7 @@ public void refreshAccessToken_workforceWithServiceAccountImpersonationOptions() } @Test - public void identityPoolCredentialSource_validFormats() { + void identityPoolCredentialSource_validFormats() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -647,7 +651,7 @@ public void identityPoolCredentialSource_validFormats() { } @Test - public void identityPoolCredentialSource_caseInsensitive() { + void identityPoolCredentialSource_caseInsensitive() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -690,7 +694,7 @@ public void identityPoolCredentialSource_caseInsensitive() { } @Test - public void identityPoolCredentialSource_invalidSourceType() { + void identityPoolCredentialSource_invalidSourceType() { try { new IdentityPoolCredentialSource(new HashMap<>()); fail("Should not be able to continue without exception."); @@ -702,7 +706,7 @@ public void identityPoolCredentialSource_invalidSourceType() { } @Test - public void identityPoolCredentialSource_invalidFormatType() { + void identityPoolCredentialSource_invalidFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -719,7 +723,7 @@ public void identityPoolCredentialSource_invalidFormatType() { } @Test - public void identityPoolCredentialSource_nullFormatType() { + void identityPoolCredentialSource_nullFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -736,7 +740,7 @@ public void identityPoolCredentialSource_nullFormatType() { } @Test - public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { + void identityPoolCredentialSource_subjectTokenFieldNameUnset() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -755,7 +759,7 @@ public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { } @Test - public void builder_allFields() throws IOException { + void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentialSource credentialSource = createFileCredentialSource(); @@ -791,7 +795,7 @@ public void builder_allFields() throws IOException { } @Test - public void builder_subjectTokenSupplier() { + void builder_subjectTokenSupplier() { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -813,7 +817,7 @@ public void builder_subjectTokenSupplier() { } @Test - public void builder_invalidWorkforceAudiences_throws() { + void builder_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -848,7 +852,7 @@ public void builder_invalidWorkforceAudiences_throws() { } @Test - public void builder_emptyWorkforceUserProjectWithWorkforceAudience() { + void builder_emptyWorkforceUserProjectWithWorkforceAudience() { // No exception should be thrown. IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder() @@ -867,7 +871,7 @@ public void builder_emptyWorkforceUserProjectWithWorkforceAudience() { } @Test - public void builder_supplierAndCredSourceThrows() { + void builder_supplierAndCredSourceThrows() { try { IdentityPoolCredentials credentials = IdentityPoolCredentials.newBuilder() @@ -887,7 +891,7 @@ public void builder_supplierAndCredSourceThrows() { } @Test - public void builder_noSupplierOrCredSourceThrows() throws IOException { + void builder_noSupplierOrCredSourceThrows() throws IOException { try { IdentityPoolCredentials credentials = @@ -905,7 +909,7 @@ public void builder_noSupplierOrCredSourceThrows() throws IOException { } @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentialSource credentialSource = createFileCredentialSource(); @@ -940,7 +944,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { } @Test - public void newBuilder_allFields() throws IOException { + void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -982,7 +986,7 @@ public void newBuilder_allFields() throws IOException { } @Test - public void newBuilder_noUniverseDomain_defaults() throws IOException { + void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -1023,7 +1027,7 @@ public void newBuilder_noUniverseDomain_defaults() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { IdentityPoolCredentials testCredentials = IdentityPoolCredentials.newBuilder(createBaseFileSourcedCredentials()) .setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL) @@ -1041,7 +1045,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void build_withCertificateSourceAndCustomX509Provider_success() + 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,15 +1074,15 @@ 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(); @@ -1086,7 +1090,7 @@ public void build_withCertificateSourceAndCustomX509Provider_success() } @Test - public void build_withDefaultCertificate_throwsOnTransportInitFailure() { + void build_withDefaultCertificate_throwsOnTransportInitFailure() { // Setup credential source to use default certificate config. Map certificateMap = new HashMap<>(); certificateMap.put("use_default_certificate_config", false); @@ -1112,7 +1116,7 @@ public void build_withDefaultCertificate_throwsOnTransportInitFailure() { } @Test - public void build_withCustomProvider_throwsOnGetKeyStore() + 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. @@ -1142,7 +1146,7 @@ public void build_withCustomProvider_throwsOnGetKeyStore() } @Test - public void build_withCustomProvider_throwsOnGetCertificatePath() + 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 1cfde9cf8..d85f2db80 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,11 @@ 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 +154,8 @@ 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(); } @@ -181,7 +178,7 @@ static GoogleCredentials getSourceCredentials() throws IOException { } @Test() - public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { + void fromJson_userAsSource_WithQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -204,7 +201,7 @@ public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { } @Test() - public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { + void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -227,7 +224,7 @@ public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { } @Test() - public void fromJson_userAsSource_MissingDelegatesField() throws IOException { + void fromJson_userAsSource_MissingDelegatesField() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, @@ -251,7 +248,7 @@ public void fromJson_userAsSource_MissingDelegatesField() throws IOException { } @Test() - public void fromJson_ServiceAccountAsSource() throws IOException { + void fromJson_ServiceAccountAsSource() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_OVERRIDE_URL, DELEGATES, QUOTA_PROJECT_ID, IMMUTABLE_SCOPES_LIST); @@ -268,7 +265,7 @@ public void fromJson_ServiceAccountAsSource() throws IOException { } @Test() - public void fromJson_InvalidFormat() throws IOException { + void fromJson_InvalidFormat() throws IOException { GenericJson json = buildInvalidCredentialsJson(); try { ImpersonatedCredentials.fromJson(json, mockTransportFactory); @@ -279,7 +276,7 @@ public void fromJson_InvalidFormat() throws IOException { } @Test() - public void createScopedRequired_True() { + void createScopedRequired_True() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -292,7 +289,7 @@ public void createScopedRequired_True() { } @Test() - public void createScopedRequired_False() { + void createScopedRequired_False() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -305,7 +302,7 @@ public void createScopedRequired_False() { } @Test - public void createScoped() { + void createScoped() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -328,7 +325,7 @@ public void createScoped() { } @Test - public void createScoped_existingAccessTokenInvalidated() throws IOException { + void createScoped_existingAccessTokenInvalidated() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -353,7 +350,7 @@ public void createScoped_existingAccessTokenInvalidated() throws IOException { } @Test - public void createScopedWithImmutableScopes() { + void createScopedWithImmutableScopes() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -376,7 +373,7 @@ public void createScopedWithImmutableScopes() { } @Test - public void createScopedWithIamEndpointOverride() { + void createScopedWithIamEndpointOverride() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -395,7 +392,7 @@ public void createScopedWithIamEndpointOverride() { } @Test - public void refreshAccessToken_unauthorized() throws IOException { + void refreshAccessToken_unauthorized() throws IOException { String expectedMessage = "The caller does not have permission"; mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory @@ -424,7 +421,7 @@ public void refreshAccessToken_unauthorized() throws IOException { } @Test() - public void refreshAccessToken_malformedTarget() throws IOException { + void refreshAccessToken_malformedTarget() throws IOException { String invalidTargetEmail = "foo"; String expectedMessage = "Request contains an invalid argument"; @@ -454,7 +451,7 @@ public void refreshAccessToken_malformedTarget() throws IOException { } @Test() - public void credential_with_zero_lifetime() throws IllegalStateException { + void credential_with_zero_lifetime() throws IllegalStateException { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, IMMUTABLE_SCOPES_LIST, 0); @@ -462,7 +459,7 @@ public void credential_with_zero_lifetime() throws IllegalStateException { } @Test() - public void credential_with_invalid_lifetime() throws IOException, IllegalStateException { + void credential_with_invalid_lifetime() throws IOException, IllegalStateException { try { ImpersonatedCredentials targetCredentials = @@ -483,7 +480,7 @@ public void credential_with_invalid_lifetime() throws IOException, IllegalStateE } @Test() - public void credential_with_invalid_scope() throws IOException, IllegalStateException { + void credential_with_invalid_scope() throws IOException, IllegalStateException { assertThrows( NullPointerException.class, () -> @@ -492,7 +489,7 @@ public void credential_with_invalid_scope() throws IOException, IllegalStateExce } @Test() - public void refreshAccessToken_success() throws IOException, IllegalStateException { + void refreshAccessToken_success() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -518,7 +515,7 @@ public void refreshAccessToken_success() throws IOException, IllegalStateExcepti } @Test() - public void refreshAccessToken_success_SSJflow() throws IOException, IllegalStateException { + void refreshAccessToken_success_SSJflow() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -544,7 +541,7 @@ public void refreshAccessToken_success_SSJflow() throws IOException, IllegalStat } @Test() - public void refreshAccessToken_success_nonGDU() throws IOException, IllegalStateException { + void refreshAccessToken_success_nonGDU() throws IOException, IllegalStateException { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(TEST_UNIVERSE_DOMAIN); transportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -572,7 +569,7 @@ public void refreshAccessToken_success_nonGDU() throws IOException, IllegalState } @Test - public void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { + void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -596,7 +593,7 @@ public void refreshAccessToken_endpointOverride() throws IOException, IllegalSta } @Test() - public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { + void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -619,7 +616,7 @@ public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalS } @Test() - public void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { + void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -638,7 +635,7 @@ public void getRequestMetadata_withoutQuotaProjectId() throws IOException, Illeg } @Test() - public void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { + void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -657,8 +654,7 @@ public void refreshAccessToken_delegates_success() throws IOException, IllegalSt } @Test - public void refreshAccessToken_GMT_dateParsedCorrectly() - throws IOException, IllegalStateException { + void refreshAccessToken_GMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -684,8 +680,7 @@ public void refreshAccessToken_GMT_dateParsedCorrectly() } @Test - public void refreshAccessToken_nonGMT_dateParsedCorrectly() - throws IOException, IllegalStateException { + void refreshAccessToken_nonGMT_dateParsedCorrectly() throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -711,7 +706,7 @@ public void refreshAccessToken_nonGMT_dateParsedCorrectly() } @Test - public void refreshAccessToken_invalidDate() throws IllegalStateException { + void refreshAccessToken_invalidDate() throws IllegalStateException { String expectedMessage = "Unparseable date"; mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken("foo"); @@ -735,7 +730,7 @@ public void refreshAccessToken_invalidDate() throws IllegalStateException { } @Test - public void getAccount_sameAs() { + void getAccount_sameAs() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -752,7 +747,7 @@ public void getAccount_sameAs() { } @Test - public void sign_sameAs() { + void sign_sameAs() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -775,7 +770,7 @@ public void sign_sameAs() { } @Test - public void sign_requestIncludesDelegates() throws IOException { + void sign_requestIncludesDelegates() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -807,7 +802,7 @@ public void sign_requestIncludesDelegates() throws IOException { } @Test - public void sign_usesSourceCredentials() { + void sign_usesSourceCredentials() { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date expiry = c.getTime(); @@ -841,7 +836,7 @@ public void sign_usesSourceCredentials() { } @Test - public void sign_accessDenied_throws() { + void sign_accessDenied_throws() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -874,7 +869,7 @@ public void sign_accessDenied_throws() { } @Test - public void sign_serverError_throws() { + void sign_serverError_throws() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -907,7 +902,7 @@ public void sign_serverError_throws() { } @Test - public void sign_sameAs_nonGDU() { + void sign_sameAs_nonGDU() { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory("test.com"); @@ -939,7 +934,7 @@ public void sign_sameAs_nonGDU() { } @Test - public void sign_universeDomainException() throws IOException { + 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. @@ -965,7 +960,7 @@ public void sign_universeDomainException() throws IOException { } @Test - public void idTokenWithAudience_sameAs() throws IOException { + void idTokenWithAudience_sameAs() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -997,7 +992,7 @@ public void idTokenWithAudience_sameAs() throws IOException { } @Test - public void idTokenWithAudience_withEmail() throws IOException { + void idTokenWithAudience_withEmail() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1034,7 +1029,7 @@ public void idTokenWithAudience_withEmail() throws IOException { } @Test - public void idTokenWithAudience_sameAs_nonGDU() throws IOException { + void idTokenWithAudience_sameAs_nonGDU() throws IOException { MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory("test.com"); transportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -1073,7 +1068,7 @@ public void idTokenWithAudience_sameAs_nonGDU() throws IOException { } @Test - public void idToken_withServerError() { + void idToken_withServerError() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1107,7 +1102,7 @@ public void idToken_withServerError() { } @Test - public void idToken_withOtherError() { + void idToken_withOtherError() { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1141,7 +1136,7 @@ public void idToken_withOtherError() { } @Test - public void universeDomain_defaultUniverse() throws IOException { + void universeDomain_defaultUniverse() throws IOException { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -1155,7 +1150,7 @@ public void universeDomain_defaultUniverse() throws IOException { } @Test - public void universeDomain_getFromSourceCredentials() throws IOException { + void universeDomain_getFromSourceCredentials() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); ImpersonatedCredentials impersonatedCredentials = @@ -1174,7 +1169,7 @@ public void universeDomain_getFromSourceCredentials() throws IOException { } @Test - public void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws IOException { + void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); IllegalStateException illegalStateException = @@ -1197,7 +1192,7 @@ public void universeDomain_whenExplicit_notAllowedIfNotMatchToSourceUD() throws } @Test - public void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOException { + void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOException { GoogleCredentials sourceCredentialsNonGDU = sourceCredentials.toBuilder().setUniverseDomain("source.domain.xyz").build(); ImpersonatedCredentials impersonatedCredentials = @@ -1218,7 +1213,7 @@ public void universeDomain_whenExplicit_AllowedIfMatchesSourceUD() throws IOExce } @Test - public void scopes_userConfigured() { + void scopes_userConfigured() { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.newBuilder().setScopes(IMMUTABLE_SCOPES_LIST).build(); assertArrayEquals( @@ -1226,7 +1221,7 @@ public void scopes_userConfigured() { } @Test - public void scopes_fromJson() throws IOException { + void scopes_fromJson() throws IOException { ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.fromJson( buildImpersonationCredentialsJson( @@ -1240,7 +1235,7 @@ public void scopes_fromJson() throws IOException { // From the ADC flow, the json is parsed and the credential is returned back // to the user @Test - public void scopes_userConfiguredAndFromJson() throws IOException { + void scopes_userConfiguredAndFromJson() throws IOException { List userConfiguredScopes = ImmutableList.of("nonsense-scopes"); ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.fromJson( @@ -1254,7 +1249,7 @@ public void scopes_userConfiguredAndFromJson() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { mockTransportFactory.getTransport().setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.getTransport().setAccessToken(ACCESS_TOKEN); mockTransportFactory.getTransport().setExpireTime(getDefaultExpireTime()); @@ -1281,7 +1276,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + 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 f95bd4cab..28b98cdb8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/InternalAwsSecurityCredentialsSupplierTest.java @@ -32,21 +32,18 @@ package com.google.auth.oauth2; import static com.google.auth.oauth2.AwsCredentialsTest.buildAwsImdsv2CredentialSource; -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 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 { +class InternalAwsSecurityCredentialsSupplierTest { @Test - public void shouldUseMetadataServer_withRequiredEnvironmentVariables() { + void shouldUseMetadataServer_withRequiredEnvironmentVariables() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -69,7 +66,7 @@ public void shouldUseMetadataServer_withRequiredEnvironmentVariables() { } @Test - public void shouldUseMetadataServer_missingRegion() { + void shouldUseMetadataServer_missingRegion() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -86,7 +83,7 @@ public void shouldUseMetadataServer_missingRegion() { } @Test - public void shouldUseMetadataServer_missingAwsAccessKeyId() { + void shouldUseMetadataServer_missingAwsAccessKeyId() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -108,7 +105,7 @@ public void shouldUseMetadataServer_missingAwsAccessKeyId() { } @Test - public void shouldUseMetadataServer_missingAwsSecretAccessKey() { + void shouldUseMetadataServer_missingAwsSecretAccessKey() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -130,7 +127,7 @@ public void shouldUseMetadataServer_missingAwsSecretAccessKey() { } @Test - public void shouldUseMetadataServer_missingAwsSecurityCreds() { + void shouldUseMetadataServer_missingAwsSecurityCreds() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -151,7 +148,7 @@ public void shouldUseMetadataServer_missingAwsSecurityCreds() { } @Test - public void shouldUseMetadataServer_noEnvironmentVars() { + 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 dff076658..8c81a7707 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java @@ -31,22 +31,19 @@ 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() { + void testMergeOverwritesFields() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -67,7 +64,7 @@ public void testMergeOverwritesFields() { } @Test - public void testMergeDefaultValues() { + void testMergeDefaultValues() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -83,7 +80,7 @@ public void testMergeDefaultValues() { } @Test - public void testMergeNull() { + void testMergeNull() { JwtClaims claims1 = JwtClaims.newBuilder().build(); JwtClaims claims2 = JwtClaims.newBuilder().build(); JwtClaims merged = claims1.merge(claims2); @@ -96,7 +93,7 @@ public void testMergeNull() { } @Test - public void testEquals() { + void testEquals() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -114,14 +111,14 @@ public void testEquals() { } @Test - public void testAdditionalClaimsDefaults() { + void testAdditionalClaimsDefaults() { JwtClaims claims = JwtClaims.newBuilder().build(); assertNotNull(claims.getAdditionalClaims()); assertTrue(claims.getAdditionalClaims().isEmpty()); } @Test - public void testMergeAdditionalClaims() { + void testMergeAdditionalClaims() { JwtClaims claims1 = JwtClaims.newBuilder().setAdditionalClaims(Collections.singletonMap("foo", "bar")).build(); JwtClaims claims2 = @@ -141,7 +138,7 @@ public void testMergeAdditionalClaims() { } @Test - public void testIsComplete() { + void testIsComplete() { // Test JwtClaim is complete if audience is not set but scope is provided. JwtClaims claims = JwtClaims.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java index 900245492..95a4e3f4d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; @@ -47,12 +47,9 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class JwtCredentialsTest extends BaseSerializationTest { +class JwtCredentialsTest extends BaseSerializationTest { private static final String PRIVATE_KEY_ID = "d84a4fefcf50791d4a90f2d7af17469d6282df9d"; private static final String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" @@ -80,7 +77,7 @@ static PrivateKey getPrivateKey() { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -102,7 +99,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void builder_requiresPrivateKey() { + void builder_requiresPrivateKey() { try { JwtClaims claims = JwtClaims.newBuilder() @@ -118,7 +115,7 @@ public void builder_requiresPrivateKey() { } @Test - public void builder_requiresClaims() { + void builder_requiresClaims() { try { JwtCredentials.newBuilder() .setPrivateKeyId(PRIVATE_KEY_ID) @@ -131,7 +128,7 @@ public void builder_requiresClaims() { } @Test - public void builder_requiresCompleteClaims() { + void builder_requiresCompleteClaims() { try { JwtClaims claims = JwtClaims.newBuilder().build(); JwtCredentials.newBuilder() @@ -146,7 +143,7 @@ public void builder_requiresCompleteClaims() { } @Test - public void jwtWithClaims_overwritesClaims() throws IOException { + void jwtWithClaims_overwritesClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -171,7 +168,7 @@ public void jwtWithClaims_overwritesClaims() throws IOException { } @Test - public void jwtWithClaims_defaultsClaims() throws IOException { + void jwtWithClaims_defaultsClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -191,7 +188,7 @@ public void jwtWithClaims_defaultsClaims() throws IOException { } @Test - public void getRequestMetadata_hasJwtAccess() throws IOException { + void getRequestMetadata_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -210,7 +207,7 @@ public void getRequestMetadata_hasJwtAccess() throws IOException { } @Test - public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { + void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -236,7 +233,7 @@ public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOExce } @Test - public void privateKeyIdNull() throws IOException { + void privateKeyIdNull() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -255,7 +252,7 @@ public void privateKeyIdNull() throws IOException { } @Test - public void privateKeyIdNotSpecified() throws IOException { + void privateKeyIdNotSpecified() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -295,15 +292,15 @@ private void verifyJwtAccess( throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull("Authorization headers not found", authorizations); + assertNotNull(authorizations, "Authorization headers not found"); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull("Multiple bearer assertions found", assertion); + assertNull(assertion, "Multiple bearer assertions found"); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull("Bearer assertion not found", assertion); + assertNotNull(assertion, "Bearer assertion not found"); JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion); assertEquals(expectedIssuer, signature.getPayload().getIssuer()); assertEquals(expectedSubject, signature.getPayload().getSubject()); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java index 631547349..8be16a89a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java @@ -46,9 +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.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -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.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,8 +83,8 @@ 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"); @@ -92,8 +92,7 @@ public static void setup() { } @Test - public 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); @@ -155,7 +154,7 @@ boolean isValidJson(String jsonString) { } @Test - public void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws IOException { + void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(ServiceAccountCredentials.class); GoogleCredentials credentials = ServiceAccountCredentialsTest.createDefaultBuilderWithToken(ACCESS_TOKEN) @@ -201,7 +200,7 @@ public void serviceAccountCredentials_getRequestMetadata_hasAccessToken() throws } @Test - public void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() + void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { TestAppender testAppender = setupTestLogger(ServiceAccountCredentials.class); String nonGDU = "test.com"; @@ -260,7 +259,7 @@ public void serviceAccountCredentials_idTokenWithAudience_iamFlow_targetAudience } @Test() - public void impersonatedCredentials_refreshAccessToken_success() + void impersonatedCredentials_refreshAccessToken_success() throws IOException, IllegalStateException { TestAppender testAppender = setupTestLogger(ImpersonatedCredentials.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = @@ -313,7 +312,7 @@ public void impersonatedCredentials_refreshAccessToken_success() } @Test - public void idTokenWithAudience_withEmail() throws IOException { + void idTokenWithAudience_withEmail() throws IOException { TestAppender testAppender = setupTestLogger(IamUtils.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); @@ -374,7 +373,7 @@ public void idTokenWithAudience_withEmail() throws IOException { } @Test - public void sign_sameAs() throws IOException { + void sign_sameAs() throws IOException { TestAppender testAppender = setupTestLogger(IamUtils.class); MockIAMCredentialsServiceTransportFactory mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); @@ -431,7 +430,7 @@ public void sign_sameAs() throws IOException { } @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + void getRequestMetadata_hasAccessToken() throws IOException { TestAppender testAppender = setupTestLogger(ComputeEngineCredentials.class); MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setServiceAccountEmail("SA_CLIENT_EMAIL"); @@ -473,7 +472,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 +487,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")); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java index abad61f32..c746a19de 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/LoggingUtilsTest.java @@ -31,23 +31,23 @@ 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.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class LoggingUtilsTest { +class LoggingUtilsTest { private TestEnvironmentProvider testEnvironmentProvider; - @Before - public void setup() { + @BeforeEach + void setup() { testEnvironmentProvider = new TestEnvironmentProvider(); } @Test - public void testIsLoggingEnabled_true() { + void testIsLoggingEnabled_true() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); assertTrue(LoggingUtils.isLoggingEnabled()); @@ -60,7 +60,7 @@ public void testIsLoggingEnabled_true() { } @Test - public void testIsLoggingEnabled_defaultToFalse() { + 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 eb035d09c..2a602b153 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MetricsUtilsTest.java @@ -31,17 +31,15 @@ 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 +51,19 @@ 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() { + void getLanguageAndAuthLibraryVersionsTest() { String version = MetricsUtils.getLanguageAndAuthLibraryVersions(); assertPatterns(version, VERSION_PATTERN); } @Test - public void getGoogleCredentialsMetricsHeaderTest() { + void getGoogleCredentialsMetricsHeaderTest() { String metricsStringNoRequestType = MetricsUtils.getGoogleCredentialsMetricsHeader( RequestType.UNTRACKED, CredentialTypeForMetrics.USER_CREDENTIALS); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java index d1bfdaecf..fc9f8ba3e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java index 5b1b3fded..cdb0a068e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java @@ -31,8 +31,8 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.LowLevelHttpRequest; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java index 62aa08225..a54765abc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java @@ -32,14 +32,14 @@ package com.google.auth.oauth2; import static java.util.concurrent.TimeUnit.HOURS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.util.Clock; import com.google.auth.TestClock; @@ -70,17 +70,13 @@ 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; /** 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 +86,25 @@ public class OAuth2CredentialsTest extends BaseSerializationTest { private ExecutorService realExecutor; - @Before - public void setUp() { + @BeforeEach + void setUp() { realExecutor = Executors.newCachedThreadPool(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { realExecutor.shutdown(); } @Test - public void constructor_storesAccessToken() { + void constructor_storesAccessToken() { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); } @Test - public void constructor_overrideMargin() throws Throwable { + void constructor_overrideMargin() throws Throwable { Duration staleMargin = Duration.ofMinutes(3); Duration expirationMargin = Duration.ofMinutes(2); @@ -189,7 +185,7 @@ public AccessToken refreshAccessToken() throws IOException { } @Test - public void getAuthenticationType_returnsOAuth2() { + void getAuthenticationType_returnsOAuth2() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -200,7 +196,7 @@ public void getAuthenticationType_returnsOAuth2() { } @Test - public void hasRequestMetadata_returnsTrue() { + void hasRequestMetadata_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -211,7 +207,7 @@ public void hasRequestMetadata_returnsTrue() { } @Test - public void hasRequestMetadataOnly_returnsTrue() { + void hasRequestMetadataOnly_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -222,7 +218,7 @@ public void hasRequestMetadataOnly_returnsTrue() { } @Test - public void addChangeListener_notifiesOnRefresh() throws IOException { + void addChangeListener_notifiesOnRefresh() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -260,7 +256,7 @@ public void addChangeListener_notifiesOnRefresh() throws IOException { } @Test - public void removeChangeListener_unregisters_observer() throws IOException { + void removeChangeListener_unregisters_observer() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -297,7 +293,7 @@ public void removeChangeListener_unregisters_observer() throws IOException { } @Test - public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { + void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -351,7 +347,7 @@ public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException } @Test - public void getRequestMetadata_async() throws IOException { + void getRequestMetadata_async() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -421,8 +417,7 @@ public void getRequestMetadata_async() throws IOException { } @Test - public void getRequestMetadata_async_refreshRace() - throws ExecutionException, InterruptedException { + void getRequestMetadata_async_refreshRace() throws ExecutionException, InterruptedException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -480,7 +475,7 @@ public Map> call() throws Exception { } @Test - public void getRequestMetadata_temporaryToken_hasToken() throws IOException { + void getRequestMetadata_temporaryToken_hasToken() throws IOException { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); @@ -490,7 +485,7 @@ public void getRequestMetadata_temporaryToken_hasToken() throws IOException { } @Test - public void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { + void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); @@ -560,7 +555,7 @@ public AccessToken refreshAccessToken() { } @Test - public void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { + void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -629,7 +624,7 @@ public AccessToken refreshAccessToken() { } @Test - public void getRequestMetadata_singleFlightErrorSharing() { + void getRequestMetadata_singleFlightErrorSharing() { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -673,32 +668,17 @@ public Map> call() throws Exception { // Get the error that getRequestMetadata(uri) created Throwable actualBlockingError = - assertThrows( - ExecutionException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - blockingCall.get(); - } - }) - .getCause(); + assertThrows(ExecutionException.class, () -> blockingCall.get()).getCause(); assertEquals(error, actualBlockingError); RuntimeException actualAsyncError = - assertThrows( - RuntimeException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - callback1.awaitResult(); - } - }); + assertThrows(RuntimeException.class, () -> callback1.awaitResult()); assertEquals(error, actualAsyncError); } @Test - public void getRequestMetadata_syncErrorsIncludeCallingStackframe() { + void getRequestMetadata_syncErrorsIncludeCallingStackframe() { final OAuth2Credentials creds = new OAuth2Credentials() { @Override @@ -729,7 +709,7 @@ public AccessToken refreshAccessToken() { } @Test - public void refresh_refreshesToken() throws IOException { + void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -765,7 +745,7 @@ public void refresh_refreshesToken() throws IOException { } @Test - public void refreshIfExpired_refreshesToken() throws IOException { + void refreshIfExpired_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -808,15 +788,15 @@ 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 { + void equals_true() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken1, null)).build(); @@ -827,7 +807,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_accessToken() throws IOException { + void equals_false_accessToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = @@ -839,7 +819,7 @@ public void equals_false_accessToken() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken("1/MkSJoj1xsli0AccessToken_NKPY2", null); OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); @@ -854,7 +834,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -864,7 +844,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -876,8 +856,8 @@ 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); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java index 1e636f813..2c285c549 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -33,8 +33,8 @@ 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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.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() { + void builder() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -73,7 +70,7 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_withRefreshAndExpirationMargins() { + void builder_withRefreshAndExpirationMargins() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -101,7 +98,7 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_onlyRefreshMarginSet() { + void builder_onlyRefreshMarginSet() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -127,7 +124,7 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_onlyExpirationMarginSet() { + void builder_onlyExpirationMarginSet() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -152,7 +149,7 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_noAccessToken() { + void builder_noAccessToken() { OAuth2CredentialsWithRefresh.newBuilder() .setRefreshHandler( new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @@ -165,7 +162,7 @@ public AccessToken refreshAccessToken() { } @Test - public void builder_noRefreshHandler_throws() { + void builder_noRefreshHandler_throws() { try { OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(); fail("Should fail as a refresh handler must be provided."); @@ -175,7 +172,7 @@ public void builder_noRefreshHandler_throws() { } @Test - public void builder_noExpirationTimeInAccessToken_throws() { + void builder_noExpirationTimeInAccessToken_throws() { try { OAuth2CredentialsWithRefresh.newBuilder() .setAccessToken(new AccessToken("accessToken", null)) @@ -187,7 +184,7 @@ public void builder_noExpirationTimeInAccessToken_throws() { } @Test - public void refreshAccessToken_delegateToRefreshHandler() throws IOException { + void refreshAccessToken_delegateToRefreshHandler() throws IOException { final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = OAuth2CredentialsWithRefresh.newBuilder() @@ -207,7 +204,7 @@ public AccessToken refreshAccessToken() { } @Test - public void getRequestMetadata() throws IOException { + 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 20f831917..f540ac41d 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2UtilsTest.java @@ -32,16 +32,16 @@ package com.google.auth.oauth2; import static com.google.auth.oauth2.OAuth2Utils.generateBasicAuthHeader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests for {@link OAuth2Utils}. */ -public class OAuth2UtilsTest { +class OAuth2UtilsTest { @Test - public void testValidCredentials() { + void testValidCredentials() { String username = "testUser"; String password = "testPassword"; String expectedHeader = "Basic dGVzdFVzZXI6dGVzdFBhc3N3b3Jk"; @@ -52,7 +52,7 @@ public void testValidCredentials() { } @Test - public void testEmptyUsername_throws() { + void testEmptyUsername_throws() { String username = ""; String password = "testPassword"; @@ -64,7 +64,7 @@ public void testEmptyUsername_throws() { } @Test - public void testEmptyPassword_throws() { + void testEmptyPassword_throws() { String username = "testUser"; String password = ""; @@ -76,7 +76,7 @@ public void testEmptyPassword_throws() { } @Test - public void testNullUsername_throws() { + void testNullUsername_throws() { String username = null; String password = "testPassword"; @@ -88,7 +88,7 @@ public void testNullUsername_throws() { } @Test - public void testNullPassword_throws() { + 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 84e522a73..e70ba6851 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.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 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() { + void getMessage_fullFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", "errorUri"); assertEquals("errorCode", e.getErrorCode()); @@ -62,7 +59,7 @@ public void getMessage_fullFormat() { } @Test - public void getMessage_descriptionFormat() { + void getMessage_descriptionFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", /* errorUri= */ null); assertEquals("errorCode", e.getErrorCode()); @@ -75,7 +72,7 @@ public void getMessage_descriptionFormat() { } @Test - public void getMessage_baseFormat() { + void getMessage_baseFormat() { OAuthException e = new OAuthException("errorCode", /* errorDescription= */ null, /* errorUri= */ null); @@ -88,7 +85,7 @@ public void getMessage_baseFormat() { } @Test - public void createFromHttpResponseException() throws IOException { + void createFromHttpResponseException() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException("errorCode", "errorDescription", "errorUri")); @@ -103,7 +100,7 @@ public void createFromHttpResponseException() throws IOException { } @Test - public void createFromHttpResponseException_descriptionFormat() throws IOException { + void createFromHttpResponseException_descriptionFormat() throws IOException { OAuthException e = OAuthException.createFromHttpResponseException( TestUtils.buildHttpResponseException( @@ -119,7 +116,7 @@ public void createFromHttpResponseException_descriptionFormat() throws IOExcepti } @Test - public void createFromHttpResponseException_baseFormat() throws IOException { + 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 cd321daf3..9832c7821 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java @@ -33,7 +33,10 @@ 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 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 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). @@ -85,7 +88,7 @@ public HttpTransport create() { } @Test - public void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { + void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { PluggableAuthCredentials credential = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -95,7 +98,7 @@ public void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { } @Test - public void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { + void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { String command = "/path/to/executable"; String timeout = "5000"; String outputFile = "/path/to/output/file"; @@ -137,7 +140,7 @@ public void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOExcept } @Test - public void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { + void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { String command = "/path/to/executable"; final ExecutableOptions[] providedOptions = {null}; @@ -175,7 +178,7 @@ public void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOEx } @Test - public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -204,7 +207,7 @@ public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOExc } @Test - public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -245,7 +248,7 @@ public void refreshAccessToken_withServiceAccountImpersonation() throws IOExcept } @Test - public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { + void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -291,7 +294,7 @@ public void refreshAccessToken_withServiceAccountImpersonationOptions() throws I } @Test - public void pluggableAuthCredentialSource_allFields() { + void pluggableAuthCredentialSource_allFields() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -307,7 +310,7 @@ public void pluggableAuthCredentialSource_allFields() { } @Test - public void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { + void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -320,7 +323,7 @@ public void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { } @Test - public void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { + void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -346,7 +349,7 @@ public void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { } @Test - public void pluggableAuthCredentialSource_validTimeoutProvided() { + void pluggableAuthCredentialSource_validTimeoutProvided() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -366,7 +369,7 @@ public void pluggableAuthCredentialSource_validTimeoutProvided() { } @Test - public void pluggableAuthCredentialSource_missingExecutableField_throws() { + void pluggableAuthCredentialSource_missingExecutableField_throws() { try { new PluggableAuthCredentialSource(new HashMap<>()); fail("Should not be able to continue without exception."); @@ -377,7 +380,7 @@ public void pluggableAuthCredentialSource_missingExecutableField_throws() { } @Test - public void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { + void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -393,7 +396,7 @@ public void pluggableAuthCredentialSource_missingExecutableCommandField_throws() } @Test - public void builder_allFields() throws IOException { + void builder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -433,7 +436,7 @@ public void builder_allFields() throws IOException { } @Test - public void builder_missingUniverseDomain_defaults() throws IOException { + void builder_missingUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -472,7 +475,7 @@ public void builder_missingUniverseDomain_defaults() throws IOException { } @Test - public void newBuilder_allFields() throws IOException { + void newBuilder_allFields() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -514,7 +517,7 @@ public void newBuilder_allFields() throws IOException { } @Test - public void newBuilder_noUniverseDomain_defaults() throws IOException { + void newBuilder_noUniverseDomain_defaults() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); PluggableAuthCredentialSource source = buildCredentialSource(); @@ -555,7 +558,7 @@ public void newBuilder_noUniverseDomain_defaults() throws IOException { } @Test - public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { + void createdScoped_clonedCredentialWithAddedScopes() throws IOException { PluggableAuthCredentials credentials = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -588,7 +591,7 @@ public void createdScoped_clonedCredentialWithAddedScopes() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + 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 bf4d0eea7..f924d4137 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java @@ -31,34 +31,39 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +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() { + 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() { + 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 88d5312a5..c31266d27 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; @@ -57,14 +57,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.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +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"; @@ -100,7 +100,7 @@ public String getOutputFilePath() { }; @Test - public void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { + void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -144,7 +144,7 @@ public void retrieveTokenFromExecutable_oidcResponse() throws IOException, Inter } @Test - public void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { + void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -189,8 +189,7 @@ public void retrieveTokenFromExecutable_samlResponse() throws IOException, Inter } @Test - public 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"); @@ -222,7 +221,7 @@ public void retrieveTokenFromExecutable_errorResponse_throws() } @Test - public void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() + void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -280,7 +279,7 @@ public void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFiel } @Test - public void + void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFieldWithOutputFileSpecified_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -355,9 +354,8 @@ public String getOutputFilePath() { } @Test - public 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"); @@ -431,7 +429,7 @@ public String getOutputFilePath() { } @Test - public void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() + void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -487,7 +485,7 @@ public String getOutputFilePath() { } @Test - public void retrieveTokenFromExecutable_withInvalidOutputFile_throws() + void retrieveTokenFromExecutable_withInvalidOutputFile_throws() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -541,7 +539,7 @@ public String getOutputFilePath() { } @Test - public void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() + void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -608,7 +606,7 @@ public String getOutputFilePath() { } @Test - public void retrieveTokenFromExecutable_expiredResponse_throws() + void retrieveTokenFromExecutable_expiredResponse_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -641,7 +639,7 @@ public void retrieveTokenFromExecutable_expiredResponse_throws() } @Test - public void retrieveTokenFromExecutable_invalidVersion_throws() + void retrieveTokenFromExecutable_invalidVersion_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -680,7 +678,7 @@ public void retrieveTokenFromExecutable_invalidVersion_throws() } @Test - public void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws IOException { + 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(); @@ -701,7 +699,7 @@ public void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() throws } @Test - public void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { + void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -753,7 +751,7 @@ public void getExecutableResponse_oidcResponse() throws IOException, Interrupted } @Test - public void getExecutableResponse_samlResponse() throws IOException, InterruptedException { + void getExecutableResponse_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -807,7 +805,7 @@ public void getExecutableResponse_samlResponse() throws IOException, Interrupted } @Test - public void getExecutableResponse_errorResponse() throws IOException, InterruptedException { + void getExecutableResponse_errorResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -855,8 +853,7 @@ public void getExecutableResponse_errorResponse() throws IOException, Interrupte } @Test - public 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"); @@ -886,8 +883,7 @@ public void getExecutableResponse_timeoutExceeded_throws() } @Test - public 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"); @@ -920,8 +916,7 @@ public void getExecutableResponse_nonZeroExitCode_throws() } @Test - public 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"); @@ -953,8 +948,7 @@ public void getExecutableResponse_processInterrupted_throws() } @Test - public 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"); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java index 30345d17a..b9249517c 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentConfigTest.java @@ -30,21 +30,18 @@ */ 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 org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +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() { + void createS2AConfig_success() { SecureSessionAgentConfig config = SecureSessionAgentConfig.createBuilder() .setPlaintextAddress(S2A_PLAINTEXT_ADDRESS) @@ -55,7 +52,7 @@ public void createS2AConfig_success() { } @Test - public void createEmptyS2AConfig_success() { + 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 eb6f92a23..8f66a90b8 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/SecureSessionAgentTest.java @@ -30,26 +30,23 @@ */ 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() { + void getS2AAddress_validAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -69,7 +66,7 @@ public void getS2AAddress_validAddress() { } @Test - public void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { + void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -89,7 +86,7 @@ public void getS2AAddress_queryEndpointResponseErrorCode_emptyAddress() { } @Test - public void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { + void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -110,7 +107,7 @@ public void getS2AAddress_queryEndpointResponseEmpty_emptyAddress() { } @Test - public void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintextEmptyAddress() { + void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintextEmptyAddress() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setS2AContentMap( ImmutableMap.of( @@ -130,7 +127,7 @@ public void getS2AAddress_queryEndpointResponseInvalidPlaintextJsonKey_plaintext } @Test - public void getS2AAddress_queryEndpointResponseInvalidMtlsJsonKey_mtlsEmptyAddress() { + 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 1561bb341..2c516a9b2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -31,16 +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; @@ -80,13 +80,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ -@RunWith(JUnit4.class) -public class ServiceAccountCredentialsTest extends BaseSerializationTest { +class ServiceAccountCredentialsTest extends BaseSerializationTest { static final String CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -161,7 +158,7 @@ static ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcepti } @Test - public void setLifetime() throws IOException { + void setLifetime() throws IOException { ServiceAccountCredentials.Builder builder = createDefaultBuilder(); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.getLifetime()); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); @@ -175,7 +172,7 @@ public void setLifetime() throws IOException { } @Test - public void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { + void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { try { createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(); fail( @@ -188,14 +185,14 @@ public void setLifetime_invalid_lifetime() throws IOException, IllegalStateExcep } @Test - public void createWithCustomLifetime() throws IOException { + void createWithCustomLifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); credentials = credentials.createWithCustomLifetime(4000); assertEquals(4000, credentials.getLifetime()); } @Test - public void createdScoped_clones() throws IOException { + void createdScoped_clones() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilderWithKey(privateKey) @@ -221,7 +218,7 @@ public void createdScoped_clones() throws IOException { } @Test - public void createdDelegated_clones() throws IOException { + void createdDelegated_clones() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilderWithKey(privateKey) @@ -246,7 +243,7 @@ public void createdDelegated_clones() throws IOException { } @Test - public void createAssertion_correct() throws IOException { + void createAssertion_correct() throws IOException { List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = createDefaultBuilderWithScopes(scopes); ServiceAccountCredentials credentials = builder.setServiceAccountUser(USER).build(); @@ -266,7 +263,7 @@ public void createAssertion_correct() throws IOException { } @Test - public void createAssertion_defaultScopes_correct() throws IOException { + void createAssertion_defaultScopes_correct() throws IOException { List defaultScopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = createDefaultBuilder(); builder.setScopes(null, defaultScopes).setServiceAccountUser(USER); @@ -289,7 +286,7 @@ public void createAssertion_defaultScopes_correct() throws IOException { } @Test - public void createAssertion_custom_lifetime() throws IOException { + void createAssertion_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -302,7 +299,7 @@ public void createAssertion_custom_lifetime() throws IOException { } @Test - public void createAssertionForIdToken_correct() throws IOException { + void createAssertionForIdToken_correct() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = createDefaultBuilder() @@ -326,7 +323,7 @@ public void createAssertionForIdToken_correct() throws IOException { } @Test - public void createAssertionForIdToken_custom_lifetime() throws IOException { + void createAssertionForIdToken_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -340,7 +337,7 @@ public void createAssertionForIdToken_custom_lifetime() throws IOException { } @Test - public void createAssertionForIdToken_incorrect() throws IOException { + void createAssertionForIdToken_incorrect() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -368,8 +365,7 @@ public void createAssertionForIdToken_incorrect() throws IOException { } @Test - public 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. @@ -378,8 +374,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); @@ -390,7 +386,7 @@ public void createdScoped_withAud_noUniverse_jwtWithScopesDisabled_accessToken() } @Test - public void createdScoped_withUniverse_selfSignedJwt() throws IOException { + void createdScoped_withUniverse_selfSignedJwt() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setUniverseDomain("foo.bar").build(); @@ -399,8 +395,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"); @@ -430,7 +426,7 @@ public void createdScoped_withUniverse_selfSignedJwt() throws IOException { } @Test - public void noScopes_withUniverse_selfSignedJwt() throws IOException { + void noScopes_withUniverse_selfSignedJwt() throws IOException { GoogleCredentials credentials = createDefaultBuilder().setUniverseDomain("foo.bar").build(); try { @@ -438,8 +434,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); @@ -448,7 +444,7 @@ public void noScopes_withUniverse_selfSignedJwt() throws IOException { } @Test - public void createdScoped_defaultScopes() throws IOException { + void createdScoped_defaultScopes() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -486,7 +482,7 @@ public void createdScoped_defaultScopes() throws IOException { } @Test - public void createScopedRequired_emptyScopes() throws IOException { + void createScopedRequired_emptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, EMPTY_SCOPES); @@ -495,7 +491,7 @@ public void createScopedRequired_emptyScopes() throws IOException { } @Test - public void createScopedRequired_nonEmptyScopes() throws IOException { + void createScopedRequired_nonEmptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, SCOPES); @@ -504,7 +500,7 @@ public void createScopedRequired_nonEmptyScopes() throws IOException { } @Test - public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { + void createScopedRequired_nonEmptyDefaultScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null, SCOPES); @@ -513,7 +509,7 @@ public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { } @Test - public void fromJSON_getProjectId() throws IOException { + void fromJSON_getProjectId() throws IOException { GenericJson json = writeServiceAccountJson(PROJECT_ID, null, null); ServiceAccountCredentials credentials = @@ -523,7 +519,7 @@ public void fromJSON_getProjectId() throws IOException { } @Test - public void fromJSON_Universe_getUniverseDomain() throws IOException { + void fromJSON_Universe_getUniverseDomain() throws IOException { GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "foo.bar"); ServiceAccountCredentials credentials = @@ -532,7 +528,7 @@ public void fromJSON_Universe_getUniverseDomain() throws IOException { } @Test - public void fromJSON_getProjectIdNull() throws IOException { + void fromJSON_getProjectIdNull() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(null, null, null); @@ -543,7 +539,7 @@ public void fromJSON_getProjectIdNull() throws IOException { } @Test - public void fromJSON_hasAccessToken() throws IOException { + void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, null, null); @@ -556,7 +552,7 @@ public void fromJSON_hasAccessToken() throws IOException { } @Test - public void fromJSON_withUniverse_selfSignedJwt() throws IOException { + 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"); @@ -569,7 +565,7 @@ public void fromJSON_withUniverse_selfSignedJwt() throws IOException { } @Test - public void fromJSON_tokenServerUri() throws IOException { + void fromJSON_tokenServerUri() throws IOException { final String tokenServerUri = "https://foo.com/bar"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -581,7 +577,7 @@ public void fromJSON_tokenServerUri() throws IOException { } @Test - public void fromJson_hasQuotaProjectId() throws IOException { + void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = writeServiceAccountJson(PROJECT_ID, QUOTA_PROJECT, null); @@ -597,7 +593,7 @@ public void fromJson_hasQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_hasAccessToken() throws IOException { + void getRequestMetadata_hasAccessToken() throws IOException { GoogleCredentials credentials = createDefaultBuilderWithToken(ACCESS_TOKEN).setScopes(SCOPES).build(); Map> metadata = credentials.getRequestMetadata(CALL_URI); @@ -605,7 +601,7 @@ public void getRequestMetadata_hasAccessToken() throws IOException { } @Test - public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { final URI TOKEN_SERVER = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -627,13 +623,13 @@ public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOExcep } @Test - public void getUniverseDomain_defaultUniverse() throws IOException { + void getUniverseDomain_defaultUniverse() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); } @Test - public void refreshAccessToken_refreshesToken() throws IOException { + void refreshAccessToken_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -649,7 +645,7 @@ public void refreshAccessToken_refreshesToken() throws IOException { } @Test - public void refreshAccessToken_tokenExpiry() throws IOException { + void refreshAccessToken_tokenExpiry() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -669,7 +665,7 @@ public void refreshAccessToken_tokenExpiry() throws IOException { } @Test - public void refreshAccessToken_IOException_Retry() throws IOException { + void refreshAccessToken_IOException_Retry() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -688,7 +684,7 @@ public void refreshAccessToken_IOException_Retry() throws IOException { } @Test - public void refreshAccessToken_retriesServerErrors() throws IOException { + void refreshAccessToken_retriesServerErrors() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -708,7 +704,7 @@ public void refreshAccessToken_retriesServerErrors() throws IOException { } @Test - public void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { + void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -728,7 +724,7 @@ public void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { } @Test - public void refreshAccessToken_defaultRetriesDisabled() throws IOException { + void refreshAccessToken_defaultRetriesDisabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -759,7 +755,7 @@ public void refreshAccessToken_defaultRetriesDisabled() throws IOException { } @Test - public void refreshAccessToken_maxRetries_maxDelay() throws IOException { + void refreshAccessToken_maxRetries_maxDelay() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = @@ -792,7 +788,7 @@ public void refreshAccessToken_maxRetries_maxDelay() throws IOException { } @Test - public void refreshAccessToken_RequestFailure_retried() throws IOException { + void refreshAccessToken_RequestFailure_retried() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; ServiceAccountCredentials credentials = @@ -826,7 +822,7 @@ public void refreshAccessToken_RequestFailure_retried() throws IOException { } @Test - public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -856,7 +852,7 @@ public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { } @Test - public void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOException { + void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -893,8 +889,7 @@ public void idTokenWithAudience_oauthFlow_targetAudienceMatchesAudClaim() throws } @Test - public 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; @@ -919,7 +914,7 @@ public void idTokenWithAudience_oauthFlow_targetAudienceDoesNotMatchAudClaim() } @Test - public void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { + void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws IOException { String nonGDU = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(nonGDU); @@ -950,7 +945,7 @@ public void idTokenWithAudience_iamFlow_targetAudienceMatchesAudClaim() throws I } @Test - public void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { + void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() throws IOException { String nonGDU = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(nonGDU); @@ -979,7 +974,7 @@ public void idTokenWithAudience_iamFlow_targetAudienceDoesNotMatchAudClaim() thr } @Test - public void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOException { + void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.setError(new IOException("404 Not Found")); ServiceAccountCredentials credentials = @@ -997,7 +992,7 @@ public void idTokenWithAudience_oauthEndpoint_non2XXStatusCode() throws IOExcept } @Test - public void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOException { + void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOException { String universeDomain = "test.com"; MockIAMCredentialsServiceTransportFactory transportFactory = new MockIAMCredentialsServiceTransportFactory(universeDomain); @@ -1026,7 +1021,7 @@ public void idTokenWithAudience_iamEndpoint_non2XXStatusCode() throws IOExceptio } @Test - public void getScopes_nullReturnsEmpty() throws IOException { + void getScopes_nullReturnsEmpty() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); Collection scopes = credentials.getScopes(); @@ -1035,13 +1030,13 @@ public void getScopes_nullReturnsEmpty() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); assertEquals(CLIENT_EMAIL, credentials.getAccount()); } @Test - public void sign_sameAs() + void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] toSign = {0xD, 0xE, 0xA, 0xD}; ServiceAccountCredentials credentials = createDefaultBuilder().build(); @@ -1055,7 +1050,7 @@ public void sign_sameAs() } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1081,7 +1076,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_clientId() throws IOException { + void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1107,7 +1102,7 @@ public void equals_false_clientId() throws IOException { } @Test - public void equals_false_email() throws IOException { + void equals_false_email() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1133,7 +1128,7 @@ public void equals_false_email() throws IOException { } @Test - public void equals_false_super() throws IOException { + void equals_false_super() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1162,7 +1157,7 @@ public void equals_false_super() throws IOException { } @Test - public void equals_false_keyId() throws IOException { + void equals_false_keyId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1188,7 +1183,7 @@ public void equals_false_keyId() throws IOException { } @Test - public void equals_false_scopes() throws IOException { + void equals_false_scopes() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1214,7 +1209,7 @@ public void equals_false_scopes() throws IOException { } @Test - public void equals_false_transportFactory() throws IOException { + void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1241,7 +1236,7 @@ public void equals_false_transportFactory() throws IOException { } @Test - public void equals_false_tokenServer() throws IOException { + void equals_false_tokenServer() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); final URI tokenServer2 = URI.create("https://foo2.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1268,7 +1263,7 @@ public void equals_false_tokenServer() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1303,7 +1298,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1336,7 +1331,7 @@ public void hashCode_equals() throws IOException { } @Test - public void hashCode_not_equals_quota() throws IOException { + void hashCode_not_equals_quota() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1362,7 +1357,7 @@ public void hashCode_not_equals_quota() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -1391,7 +1386,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { ServiceAccountCredentials.fromStream(stream, null); @@ -1402,7 +1397,7 @@ public void fromStream_nullTransport_throws() throws IOException { } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); @@ -1413,7 +1408,7 @@ public void fromStream_nullStream_throws() throws IOException { } @Test - public void fromStream_providesToken() throws IOException { + void fromStream_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -1429,7 +1424,7 @@ public void fromStream_providesToken() throws IOException { } @Test - public void fromStream_noClientId_throws() throws IOException { + void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(null, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); @@ -1437,7 +1432,7 @@ public void fromStream_noClientId_throws() throws IOException { } @Test - public void fromStream_noClientEmail_throws() throws IOException { + void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, null, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); @@ -1445,7 +1440,7 @@ public void fromStream_noClientEmail_throws() throws IOException { } @Test - public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { + void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.setError(new IOException("Invalid grant: Account not found")); @@ -1470,7 +1465,7 @@ public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOExcep } @Test - public void fromStream_noPrivateKey_throws() throws IOException { + void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, null, PRIVATE_KEY_ID); @@ -1478,7 +1473,7 @@ public void fromStream_noPrivateKey_throws() throws IOException { } @Test - public void fromStream_noPrivateKeyId_throws() throws IOException { + void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, null); @@ -1486,7 +1481,7 @@ public void fromStream_noPrivateKeyId_throws() throws IOException { } @Test - public void getUriForSelfSignedJWT() { + void getUriForSelfSignedJWT() { assertNull(ServiceAccountCredentials.getUriForSelfSignedJWT(null)); URI uri = URI.create("https://compute.googleapis.com/compute/v1/projects/"); @@ -1495,21 +1490,21 @@ public void getUriForSelfSignedJWT() { } @Test - public void getUriForSelfSignedJWT_noHost() { + void getUriForSelfSignedJWT_noHost() { URI uri = URI.create("file:foo"); URI expected = URI.create("file:foo"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } @Test - public void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { + void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { URI uri = URI.create("compute.googleapis.com"); URI expected = URI.create("compute.googleapis.com"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } @Test - public void getRequestMetadata_setsQuotaProjectId() throws IOException { + void getRequestMetadata_setsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1536,7 +1531,7 @@ public void getRequestMetadata_setsQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_noQuotaProjectId() throws IOException { + void getRequestMetadata_noQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1559,7 +1554,7 @@ public void getRequestMetadata_noQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_withCallback() throws IOException { + 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 +1590,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void getRequestMetadata_withScopes_withUniverseDomain_SelfSignedJwt() throws IOException { + 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 +1630,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { + void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1665,7 +1660,7 @@ public void getRequestMetadata_withScopes_selfSignedJWT() throws IOException { } @Test - public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { + void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1701,7 +1696,7 @@ public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() thr } @Test - public void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { + void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1719,7 +1714,7 @@ public void getRequestMetadata_withAudience_selfSignedJWT() throws IOException { } @Test - public void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOException { + void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1738,7 +1733,7 @@ public void getRequestMetadata_withDefaultScopes_selfSignedJWT() throws IOExcept } @Test - public void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { + void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1774,11 +1769,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void createScopes_existingAccessTokenInvalidated() throws IOException { + 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 +1801,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()); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index 2f6533195..8d6966631 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -32,15 +32,15 @@ package com.google.auth.oauth2; 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 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 com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -65,13 +65,10 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ -@RunWith(JUnit4.class) -public class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { +class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { private static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -98,7 +95,7 @@ public class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTes private static final String QUOTA_PROJECT = "sample-quota-project-id"; @Test - public void constructor_allParameters_constructs() throws IOException { + void constructor_allParameters_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -118,7 +115,7 @@ public void constructor_allParameters_constructs() throws IOException { } @Test - public void constructor_noClientId_constructs() throws IOException { + void constructor_noClientId_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) @@ -128,7 +125,7 @@ public void constructor_noClientId_constructs() throws IOException { } @Test - public void constructor_noPrivateKeyId_constructs() throws IOException { + void constructor_noPrivateKeyId_constructs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -138,7 +135,7 @@ public void constructor_noPrivateKeyId_constructs() throws IOException { } @Test - public void constructor_noEmail_throws() throws IOException { + void constructor_noEmail_throws() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); try { ServiceAccountJwtAccessCredentials.newBuilder() @@ -153,7 +150,7 @@ public void constructor_noEmail_throws() throws IOException { } @Test - public void constructor_noPrivateKey_throws() { + void constructor_noPrivateKey_throws() { try { ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -167,7 +164,7 @@ public void constructor_noPrivateKey_throws() { } @Test - public void getAuthenticationType_returnsJwtAccess() throws IOException { + void getAuthenticationType_returnsJwtAccess() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -175,7 +172,7 @@ public void getAuthenticationType_returnsJwtAccess() throws IOException { } @Test - public void hasRequestMetadata_returnsTrue() throws IOException { + void hasRequestMetadata_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -183,7 +180,7 @@ public void hasRequestMetadata_returnsTrue() throws IOException { } @Test - public void hasRequestMetadataOnly_returnsTrue() throws IOException { + void hasRequestMetadataOnly_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -191,7 +188,7 @@ public void hasRequestMetadataOnly_returnsTrue() throws IOException { } @Test - public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { + void getRequestMetadata_blocking_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -207,7 +204,7 @@ public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { } @Test - public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { + void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -224,7 +221,7 @@ public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOExcep } @Test - public void getRequestMetadata_blocking_noURI_throws() throws IOException { + void getRequestMetadata_blocking_noURI_throws() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -243,7 +240,7 @@ public void getRequestMetadata_blocking_noURI_throws() throws IOException { } @Test - public void getRequestMetadata_blocking_cached() throws IOException { + void getRequestMetadata_blocking_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -268,7 +265,7 @@ public void getRequestMetadata_blocking_cached() throws IOException { } @Test - public void getRequestMetadata_blocking_cache_expired() throws IOException { + void getRequestMetadata_blocking_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -293,7 +290,7 @@ public void getRequestMetadata_blocking_cache_expired() throws IOException { } @Test - public void getRequestMetadata_async_hasJwtAccess() throws IOException { + void getRequestMetadata_async_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -312,7 +309,7 @@ public void getRequestMetadata_async_hasJwtAccess() throws IOException { } @Test - public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { + void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -332,7 +329,7 @@ public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOExceptio } @Test - public void getRequestMetadata_async_noURI_exception() throws IOException { + void getRequestMetadata_async_noURI_exception() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -350,7 +347,7 @@ public void getRequestMetadata_async_noURI_exception() throws IOException { } @Test - public void getRequestMetadata_async_cache_expired() throws IOException { + void getRequestMetadata_async_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -378,7 +375,7 @@ public void getRequestMetadata_async_cache_expired() throws IOException { } @Test - public void getRequestMetadata_async_cached() throws IOException { + void getRequestMetadata_async_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -406,7 +403,7 @@ public void getRequestMetadata_async_cached() throws IOException { } @Test - public void getRequestMetadata_contains_quotaProjectId() throws IOException { + void getRequestMetadata_contains_quotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -426,7 +423,7 @@ public void getRequestMetadata_contains_quotaProjectId() throws IOException { } @Test - public void getAccount_sameAs() throws IOException { + void getAccount_sameAs() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -439,7 +436,7 @@ public void getAccount_sameAs() throws IOException { } @Test - public void sign_sameAs() + void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); byte[] toSign = {0xD, 0xE, 0xA, 0xD}; @@ -458,7 +455,7 @@ public void sign_sameAs() } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -481,7 +478,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_clientId() throws IOException { + void equals_false_clientId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -504,7 +501,7 @@ public void equals_false_clientId() throws IOException { } @Test - public void equals_false_email() throws IOException { + void equals_false_email() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -527,7 +524,7 @@ public void equals_false_email() throws IOException { } @Test - public void equals_false_keyId() throws IOException { + void equals_false_keyId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -550,7 +547,7 @@ public void equals_false_keyId() throws IOException { } @Test - public void equals_false_callUri() throws IOException { + 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 = @@ -574,7 +571,7 @@ public void equals_false_callUri() throws IOException { } @Test - public void toString_containsFields() throws IOException { + void toString_containsFields() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -594,7 +591,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -616,7 +613,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -637,7 +634,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); @@ -648,7 +645,7 @@ public void fromStream_nullStream_throws() throws IOException { } @Test - public void fromStream_hasJwtAccess() throws IOException { + void fromStream_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -661,7 +658,7 @@ public void fromStream_hasJwtAccess() throws IOException { } @Test - public void fromStream_defaultURI_hasJwtAccess() throws IOException { + void fromStream_defaultURI_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -675,7 +672,7 @@ public void fromStream_defaultURI_hasJwtAccess() throws IOException { } @Test - public void fromStream_noClientId_throws() throws IOException { + void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -684,7 +681,7 @@ public void fromStream_noClientId_throws() throws IOException { } @Test - public void fromStream_noClientEmail_throws() throws IOException { + void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -693,7 +690,7 @@ public void fromStream_noClientEmail_throws() throws IOException { } @Test - public void fromStream_noPrivateKey_throws() throws IOException { + void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -702,7 +699,7 @@ public void fromStream_noPrivateKey_throws() throws IOException { } @Test - public void fromStream_noPrivateKeyId_throws() throws IOException { + void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -711,7 +708,7 @@ public void fromStream_noPrivateKeyId_throws() throws IOException { } @Test - public void jwtWithClaims_overrideAudience() throws IOException { + void jwtWithClaims_overrideAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -729,7 +726,7 @@ public void jwtWithClaims_overrideAudience() throws IOException { } @Test - public void jwtWithClaims_noAudience() throws IOException { + void jwtWithClaims_noAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -747,7 +744,7 @@ public void jwtWithClaims_noAudience() throws IOException { } @Test - public void jwtWithClaims_defaultAudience() throws IOException { + void jwtWithClaims_defaultAudience() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -764,7 +761,7 @@ public void jwtWithClaims_defaultAudience() throws IOException { } @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + void getRequestMetadataSetsQuotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -784,7 +781,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + void getRequestMetadataNoQuotaProjectId() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -800,7 +797,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataWithCallback() throws IOException { + void getRequestMetadataWithCallback() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -830,11 +827,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void fromJSON_noUniverseDomain() throws IOException { + void fromJSON_noUniverseDomain() throws IOException { GenericJson json = writeServiceAccountJson( SA_CLIENT_ID, @@ -855,7 +852,7 @@ public void fromJSON_noUniverseDomain() throws IOException { } @Test - public void fromJSON_UniverseDomainSet() throws IOException { + void fromJSON_UniverseDomainSet() throws IOException { GenericJson json = writeServiceAccountJson( SA_CLIENT_ID, @@ -876,7 +873,7 @@ public void fromJSON_UniverseDomainSet() throws IOException { } @Test - public void fromPkcs8_NoUniverseDomain() throws IOException { + void fromPkcs8_NoUniverseDomain() throws IOException { ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -889,7 +886,7 @@ public void fromPkcs8_NoUniverseDomain() throws IOException { } @Test - public void fromPkcs8_CustomUniverseDomain() throws IOException { + void fromPkcs8_CustomUniverseDomain() throws IOException { ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, @@ -908,7 +905,7 @@ public void fromPkcs8_CustomUniverseDomain() throws IOException { } @Test - public void builder_defaultUniverseDomain() throws IOException { + void builder_defaultUniverseDomain() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -922,7 +919,7 @@ public void builder_defaultUniverseDomain() throws IOException { } @Test - public void builder_customUniverseDomain() throws IOException { + void builder_customUniverseDomain() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -944,15 +941,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()); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsLogbackTest.java index 68d1edc96..fd8ad94af 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,27 @@ 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() { + void testLogWithMDC_slf4jLogger() { TestAppender testAppender = setupTestLogger(); @@ -91,7 +91,7 @@ public void testLogWithMDC_slf4jLogger() { } @Test - public void testLogWithMDC_INFO() { + void testLogWithMDC_INFO() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.INFO, new HashMap<>(), "test message"); @@ -101,7 +101,7 @@ public void testLogWithMDC_INFO() { } @Test - public void testLogWithMDC_TRACE_notEnabled() { + void testLogWithMDC_TRACE_notEnabled() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.TRACE, new HashMap<>(), "test message"); @@ -110,7 +110,7 @@ public void testLogWithMDC_TRACE_notEnabled() { } @Test - public void testLogWithMDC_WARN() { + void testLogWithMDC_WARN() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.WARN, new HashMap<>(), "test message"); @@ -120,7 +120,7 @@ public void testLogWithMDC_WARN() { } @Test - public void testLogWithMDC_ERROR() { + void testLogWithMDC_ERROR() { TestAppender testAppender = setupTestLogger(); Slf4jUtils.logWithMDC(LOGGER, Level.ERROR, new HashMap<>(), "test message"); @@ -130,7 +130,7 @@ public void testLogWithMDC_ERROR() { } @Test - public void testLogGenericData() { + void testLogGenericData() { // mimic GOOGLE_SDK_JAVA_LOGGING = true testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); @@ -149,17 +149,16 @@ public void testLogGenericData() { List keyValuePairs = testAppender.events.get(0).getKeyValuePairs(); assertEquals(2, keyValuePairs.size()); for (KeyValuePair kvp : keyValuePairs) { - assertTrue( - "Key should be either 'key1' or 'token'", - kvp.key.equals("key1") || kvp.key.equals("token")); + kvp.key.equals("key1") || kvp.key.equals("token"), + "Key should be either 'key1' or 'token'"); } testAppender.stop(); } @Test - public void testLogRequest() throws IOException { + 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 97a215f56..c3ee5b872 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/Slf4jUtilsTest.java @@ -31,31 +31,35 @@ 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() { + void testGetLogger_loggingDisabled_shouldGetNOPLogger() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "false"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); Logger logger = Slf4jUtils.getLogger(Slf4jUtilsTest.class); @@ -67,7 +71,7 @@ public void testGetLogger_loggingDisabled_shouldGetNOPLogger() { // This test require binding (e.g. logback) be present @Test - public void testGetLogger_loggingEnabled_slf4jBindingPresent() { + void testGetLogger_loggingEnabled_slf4jBindingPresent() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); Logger logger = Slf4jUtils.getLogger(LoggingUtilsTest.class); @@ -76,7 +80,7 @@ public void testGetLogger_loggingEnabled_slf4jBindingPresent() { } @Test - public void testGetLogger_loggingEnabled_noBinding() { + void testGetLogger_loggingEnabled_noBinding() { testEnvironmentProvider.setEnv(LoggingUtils.GOOGLE_SDK_JAVA_LOGGING, "true"); LoggingUtils.setEnvironmentProvider(testEnvironmentProvider); // Create a mock LoggerFactoryProvider @@ -94,13 +98,13 @@ public void testGetLogger_loggingEnabled_noBinding() { } @Test - public void testCheckIfClazzAvailable() { + void testCheckIfClazzAvailable() { assertFalse(Slf4jUtils.checkIfClazzAvailable("fake.class.should.not.be.in.classpath")); assertTrue(Slf4jUtils.checkIfClazzAvailable("org.slf4j.event.KeyValuePair")); } @Test - public void testMatchLevelSevere() { + 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 e91558fa7..6607403a4 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.api.client.http.HttpHeaders; import com.google.api.client.testing.http.MockLowLevelHttpRequest; @@ -45,15 +45,11 @@ 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; /** 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 +59,13 @@ public final class StsRequestHandlerTest { private MockStsTransport transport; - @Before - public void setup() { + @BeforeEach + void setup() { transport = new MockStsTransport(); } @Test - public void exchangeToken() throws IOException { + void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType") .setScopes(Collections.singletonList(OAuth2Utils.CLOUD_PLATFORM_SCOPE)) @@ -103,7 +99,7 @@ public void exchangeToken() throws IOException { } @Test - public void exchangeToken_withOptionalParams() throws IOException { + void exchangeToken_withOptionalParams() throws IOException { // Return optional params scope and the refresh_token. transport.addScopeSequence(Arrays.asList("scope1", "scope2", "scope3")); transport.addRefreshTokenSequence("refreshToken"); @@ -167,7 +163,7 @@ public void exchangeToken_withOptionalParams() throws IOException { } @Test - public void exchangeToken_throwsException() throws IOException { + void exchangeToken_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -180,15 +176,7 @@ public void exchangeToken_throwsException() throws IOException { TestUtils.buildHttpResponseException( "invalidRequest", /* errorDescription= */ null, /* errorUri= */ null)); - OAuthException e = - assertThrows( - OAuthException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + OAuthException e = assertThrows(OAuthException.class, () -> requestHandler.exchangeToken()); assertEquals("invalidRequest", e.getErrorCode()); assertNull(e.getErrorDescription()); @@ -196,7 +184,7 @@ public void run() throws Throwable { } @Test - public void exchangeToken_withOptionalParams_throwsException() throws IOException { + void exchangeToken_withOptionalParams_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -208,15 +196,7 @@ public void exchangeToken_withOptionalParams_throwsException() throws IOExceptio transport.addResponseErrorSequence( TestUtils.buildHttpResponseException("invalidRequest", "errorDescription", "errorUri")); - OAuthException e = - assertThrows( - OAuthException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + OAuthException e = assertThrows(OAuthException.class, () -> requestHandler.exchangeToken()); assertEquals("invalidRequest", e.getErrorCode()); assertEquals("errorDescription", e.getErrorDescription()); @@ -224,7 +204,7 @@ public void run() throws Throwable { } @Test - public void exchangeToken_ioException() { + void exchangeToken_ioException() { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -237,19 +217,12 @@ public void exchangeToken_ioException() { transport.addResponseErrorSequence(e); IOException thrownException = - assertThrows( - IOException.class, - new ThrowingRunnable() { - @Override - public void run() throws Throwable { - requestHandler.exchangeToken(); - } - }); + assertThrows(IOException.class, () -> requestHandler.exchangeToken()); assertEquals(e, thrownException); } @Test - public void exchangeToken_noExpiresInReturned() throws IOException { + void exchangeToken_noExpiresInReturned() throws IOException { // Don't return expires in. This happens in the CAB flow when the subject token does not belong // to a service account. transport.setReturnExpiresIn(/* returnExpiresIn= */ false); @@ -276,7 +249,7 @@ public void exchangeToken_noExpiresInReturned() throws IOException { } @Test - public void exchangeToken_withAccessBoundarySessionKey() throws IOException { + void exchangeToken_withAccessBoundarySessionKey() throws IOException { transport.setReturnAccessBoundarySessionKey(/* returnAccessBoundarySessionKey= */ true); StsTokenExchangeRequest stsTokenExchangeRequest = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java b/oauth2_http/javatests/com/google/auth/oauth2/TestAppender.java index 66fd046fd..aef72daa7 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 diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java b/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java index 99af8c106..4efc138bb 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TestUtils.java @@ -31,13 +31,13 @@ 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)); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index 5168cb90e..6872214f0 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java @@ -30,10 +30,10 @@ */ package com.google.auth.oauth2; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; @@ -51,13 +51,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"; @@ -84,7 +81,7 @@ public long currentTimeMillis() { }; @Test - public void verifyExpiredToken() { + void verifyExpiredToken() { for (String token : ALL_TOKENS) { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build(); try { @@ -97,7 +94,7 @@ public void verifyExpiredToken() { } @Test - public void verifyExpectedAudience() { + void verifyExpectedAudience() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setAudience("expected audience").build(); for (String token : ALL_TOKENS) { @@ -111,7 +108,7 @@ public void verifyExpectedAudience() { } @Test - public void verifyExpectedIssuer() { + void verifyExpectedIssuer() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build(); for (String token : ALL_TOKENS) { try { @@ -124,7 +121,7 @@ public void verifyExpectedIssuer() { } @Test - public void verifyEs256Token404CertificateUrl() { + void verifyEs256Token404CertificateUrl() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -164,7 +161,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void verifyEs256TokenPublicKeyMismatch() { + void verifyEs256TokenPublicKeyMismatch() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -201,7 +198,7 @@ public LowLevelHttpResponse execute() throws IOException { } @Test - public void verifyPublicKeyStoreIntermittentError() throws VerificationException, IOException { + void verifyPublicKeyStoreIntermittentError() throws VerificationException, IOException { // mock responses MockLowLevelHttpResponse response404 = new MockLowLevelHttpResponse() @@ -251,7 +248,7 @@ public void verifyPublicKeyStoreIntermittentError() throws VerificationException } @Test - public void verifyEs256Token() throws VerificationException, IOException { + void verifyEs256Token() throws VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.gstatic.com/iap/verify/public_key-jwk", @@ -265,7 +262,7 @@ public void verifyEs256Token() throws VerificationException, IOException { } @Test - public void verifyRs256Token() throws VerificationException, IOException { + void verifyRs256Token() throws VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.googleapis.com/oauth2/v3/certs", @@ -279,7 +276,7 @@ public void verifyRs256Token() throws VerificationException, IOException { } @Test - public void verifyRs256TokenWithLegacyCertificateUrlFormat() + void verifyRs256TokenWithLegacyCertificateUrlFormat() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( @@ -294,8 +291,8 @@ public void verifyRs256TokenWithLegacyCertificateUrlFormat() } @Test - @Ignore - public void verifyServiceAccountRs256Token() throws VerificationException { + @Disabled + void verifyServiceAccountRs256Token() throws VerificationException { final Clock clock = new Clock() { @Override diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java index 4f2a8173e..050a9d199 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java @@ -33,14 +33,14 @@ 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 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.auth.TestUtils; import com.google.auth.http.HttpTransportFactory; @@ -55,13 +55,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** 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"; @@ -85,7 +82,7 @@ public class UserAuthorizerTest { private static final PKCEProvider pkce = new DefaultPKCEProvider(); @Test - public void constructorMinimum() { + void constructorMinimum() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -105,7 +102,7 @@ public void constructorMinimum() { } @Test - public void constructorCommon() { + void constructorCommon() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -128,7 +125,7 @@ public void constructorCommon() { } @Test - public void constructorWithClientAuthenticationTypeNone() { + void constructorWithClientAuthenticationTypeNone() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -148,18 +145,26 @@ 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() { + void getCallbackUri_relativeToBase() { final URI callbackURI = URI.create("/bar"); final URI expectedCallbackURI = URI.create("http://example.com/bar"); UserAuthorizer authorizer = @@ -175,7 +180,7 @@ public void getCallbackUri_relativeToBase() { } @Test - public void getAuthorizationUrl() throws IOException { + void getAuthorizationUrl() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -211,7 +216,7 @@ public void getAuthorizationUrl() throws IOException { } @Test - public void getAuthorizationUrl_additionalParameters() throws IOException { + void getAuthorizationUrl_additionalParameters() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -255,7 +260,7 @@ public void getAuthorizationUrl_additionalParameters() throws IOException { } @Test - public void getCredentials_noCredentials_returnsNull() throws IOException { + void getCredentials_noCredentials_returnsNull() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -269,7 +274,7 @@ public void getCredentials_noCredentials_returnsNull() throws IOException { } @Test - public void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() throws IOException { + void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode( @@ -297,7 +302,7 @@ public void testGetTokenResponseFromAuthCodeExchange_convertsCodeToTokens() thro } @Test - public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationClientAuthBasic() + void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationClientAuthBasic() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -339,7 +344,7 @@ public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederation } @Test - public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationNoClientAuth() + void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederationNoClientAuth() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -374,7 +379,7 @@ public void testGetTokenResponseFromAuthCodeExchange_workforceIdentityFederation } @Test - public void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { + void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { UserAuthorizer authorizer = UserAuthorizer.newBuilder().setClientId(CLIENT_ID).setScopes(DUMMY_SCOPES).build(); @@ -387,8 +392,7 @@ public void testGetTokenResponseFromAuthCodeExchange_missingAuthCode_throws() { } @Test - public 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. @@ -420,7 +424,7 @@ public void testGetTokenResponseFromAuthCodeExchange_missingAccessToken_throws() } @Test - public void getCredentials_storedCredentials_returnsStored() throws IOException { + void getCredentials_storedCredentials_returnsStored() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserCredentials initialCredentials = @@ -447,8 +451,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 +461,11 @@ public void getCredentials_nullUserId_throws() throws IOException { .setTokenStore(tokenStore) .build(); - authorizer.getCredentials(null); + assertThrows(NullPointerException.class, () -> authorizer.getCredentials(null)); } @Test - public void getCredentials_refreshedToken_stored() throws IOException { + void getCredentials_refreshedToken_stored() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; AccessToken accessToken1 = @@ -516,7 +520,7 @@ public void getCredentials_refreshedToken_stored() throws IOException { } @Test - public void getCredentials_refreshedToken_different_granted_scopes() throws IOException { + 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"); @@ -571,7 +575,7 @@ public void getCredentials_refreshedToken_different_granted_scopes() throws IOEx } @Test - public void getCredentialsFromCode_convertsCodeToTokens() throws IOException { + void getCredentialsFromCode_convertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode( @@ -593,7 +597,7 @@ public void getCredentialsFromCode_convertsCodeToTokens() throws IOException { } @Test - public void getCredentialsFromCode_additionalParameters() throws IOException { + void getCredentialsFromCode_additionalParameters() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -638,8 +642,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 +651,12 @@ public void getCredentialsFromCode_nullCode_throws() throws IOException { .setTokenStore(new MemoryTokensStorage()) .build(); - authorizer.getCredentialsFromCode(null, BASE_URI); + assertThrows( + NullPointerException.class, () -> authorizer.getCredentialsFromCode(null, BASE_URI)); } @Test - public void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { + void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -689,8 +694,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 +703,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 +717,13 @@ public void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOExceptio .setTokenStore(new MemoryTokensStorage()) .build(); - authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI); + assertThrows( + NullPointerException.class, + () -> authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI)); } @Test - public void revokeAuthorization_revokesAndClears() throws IOException { + void revokeAuthorization_revokesAndClears() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -757,8 +766,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 +786,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 +817,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 +848,19 @@ 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() { + void testTokenResponseWithConfig() { String clientId = "testClientId"; String clientSecret = "testClientSecret"; String refreshToken = "testRefreshToken"; @@ -871,7 +887,7 @@ public void testTokenResponseWithConfig() { } @Test - public void testTokenResponseWithConfig_noRefreshToken() { + 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 f6ead0294..e5a6c658a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -31,15 +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; @@ -64,13 +64,10 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; /** Test case for {@link UserCredentials}. */ -@RunWith(JUnit4.class) -public class UserCredentialsTest extends BaseSerializationTest { +class UserCredentialsTest extends BaseSerializationTest { static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -86,13 +83,19 @@ public class UserCredentialsTest extends BaseSerializationTest { + "aXNzIjoiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAyMTAxNTUwODM0MjAwNzA4NTY4In0" + ".redacted"; - @Test(expected = IllegalStateException.class) - public void constructor_accessAndRefreshTokenNull_throws() { - UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); + @Test + void constructor_accessAndRefreshTokenNull_throws() { + assertThrows( + IllegalStateException.class, + () -> + UserCredentials.newBuilder() + .setClientId(CLIENT_ID) + .setClientSecret(CLIENT_SECRET) + .build()); } @Test - public void constructor() { + void constructor() { UserCredentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -107,7 +110,7 @@ public void constructor() { } @Test - public void createScoped_same() { + void createScoped_same() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -118,7 +121,7 @@ public void createScoped_same() { } @Test - public void createScopedRequired_false() { + void createScopedRequired_false() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -129,7 +132,7 @@ public void createScopedRequired_false() { } @Test - public void fromJson_hasAccessToken() throws IOException { + void fromJson_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -142,7 +145,7 @@ public void fromJson_hasAccessToken() throws IOException { } @Test - public void fromJson_hasTokenUri() throws IOException { + void fromJson_hasTokenUri() throws IOException { String tokenUrl = "token.url.xyz"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -154,7 +157,7 @@ public void fromJson_hasTokenUri() throws IOException { } @Test - public void fromJson_emptyTokenUri() throws IOException { + void fromJson_emptyTokenUri() throws IOException { String tokenUrl = ""; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -166,7 +169,7 @@ public void fromJson_emptyTokenUri() throws IOException { } @Test - public void fromJson_hasQuotaProjectId() throws IOException { + void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -182,7 +185,7 @@ public void fromJson_hasQuotaProjectId() throws IOException { } @Test - public void getRequestMetadata_initialToken_hasAccessToken() throws IOException { + void getRequestMetadata_initialToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -200,7 +203,7 @@ public void getRequestMetadata_initialToken_hasAccessToken() throws IOException } @Test - public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { + void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -221,7 +224,7 @@ public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException } @Test - public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { + void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -239,7 +242,7 @@ public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOExcept } @Test - public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { final URI TOKEN_SERVER = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -260,7 +263,7 @@ public void getRequestMetadata_customTokenServer_hasAccessToken() throws IOExcep } @Test - public void equals_true() throws IOException { + void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -289,7 +292,7 @@ public void equals_true() throws IOException { } @Test - public void equals_false_clientId() throws IOException { + void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -316,7 +319,7 @@ public void equals_false_clientId() throws IOException { } @Test - public void equals_false_clientSecret() throws IOException { + 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(); @@ -343,7 +346,7 @@ public void equals_false_clientSecret() throws IOException { } @Test - public void equals_false_refreshToken() throws IOException { + 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(); @@ -370,7 +373,7 @@ public void equals_false_refreshToken() throws IOException { } @Test - public void equals_false_accessToken() throws IOException { + 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); @@ -399,7 +402,7 @@ public void equals_false_accessToken() throws IOException { } @Test - public void equals_false_transportFactory() throws IOException { + void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); @@ -427,7 +430,7 @@ public void equals_false_transportFactory() throws IOException { } @Test - public void equals_false_tokenServer() throws IOException { + void equals_false_tokenServer() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); final URI tokenServer2 = URI.create("https://foo2.com/bar"); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -455,7 +458,7 @@ public void equals_false_tokenServer() throws IOException { } @Test - public void equals_false_quotaProjectId() throws IOException { + 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); @@ -483,7 +486,7 @@ public void equals_false_quotaProjectId() throws IOException { } @Test - public void toString_containsFields() throws IOException { + 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(); @@ -515,7 +518,7 @@ public void toString_containsFields() throws IOException { } @Test - public void hashCode_equals() throws IOException { + void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -543,7 +546,7 @@ public void hashCode_equals() throws IOException { } @Test - public void serialize() throws IOException, ClassNotFoundException { + void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -564,7 +567,7 @@ public void serialize() throws IOException, ClassNotFoundException { } @Test - public void fromStream_nullTransport_throws() throws IOException { + void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { UserCredentials.fromStream(stream, null); @@ -575,7 +578,7 @@ public void fromStream_nullTransport_throws() throws IOException { } @Test - public void fromStream_nullStream_throws() throws IOException { + void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { UserCredentials.fromStream(null, transportFactory); @@ -586,7 +589,7 @@ public void fromStream_nullStream_throws() throws IOException { } @Test - public void fromStream_user_providesToken() throws IOException { + void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -601,28 +604,28 @@ public void fromStream_user_providesToken() throws IOException { } @Test - public void fromStream_userNoClientId_throws() throws IOException { + void fromStream_userNoClientId_throws() throws IOException { InputStream userStream = writeUserStream(null, CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_id"); } @Test - public void fromStream_userNoClientSecret_throws() throws IOException { + void fromStream_userNoClientSecret_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_secret"); } @Test - public void fromStream_userNoRefreshToken_throws() throws IOException { + void fromStream_userNoRefreshToken_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, CLIENT_SECRET, null, QUOTA_PROJECT); testFromStreamException(userStream, "refresh_token"); } @Test - public void saveUserCredentials_saved_throws() throws IOException { + void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -637,7 +640,7 @@ public void saveUserCredentials_saved_throws() throws IOException { } @Test - public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { + void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -662,7 +665,7 @@ public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOExcep } @Test - public void getRequestMetadataSetsQuotaProjectId() throws IOException { + void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -684,7 +687,7 @@ public void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataNoQuotaProjectId() throws IOException { + void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -702,7 +705,7 @@ public void getRequestMetadataNoQuotaProjectId() throws IOException { } @Test - public void getRequestMetadataWithCallback() throws IOException { + void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -733,11 +736,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue("Should have run onSuccess() callback", success.get()); + assertTrue(success.get(), "Should have run onSuccess() callback"); } @Test - public void IdTokenCredentials_WithUserEmailScope_success() throws IOException { + void IdTokenCredentials_WithUserEmailScope_success() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -775,7 +778,7 @@ public void IdTokenCredentials_WithUserEmailScope_success() throws IOException { } @Test - public void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { + void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -816,7 +819,7 @@ public void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOExcepti } @Test - public void idTokenWithAudience_non2xxError() throws IOException { + 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; @@ -831,7 +834,7 @@ public void idTokenWithAudience_non2xxError() throws IOException { } @Test - public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -859,7 +862,7 @@ public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { } @Test - public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -886,7 +889,7 @@ public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { } @Test - public void userCredentials_toBuilder_copyEveryAttribute() { + 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 3d88cff7a..1a27d3cdc 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTComputeEngineCredentialsTest.java @@ -31,10 +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; @@ -45,14 +45,14 @@ 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 { + void RefreshCredentials() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); AccessToken accessToken = credentials.refreshAccessToken(); @@ -62,7 +62,7 @@ public void RefreshCredentials() throws Exception { } @Test - public void DefaultCredentials() throws Exception { + void DefaultCredentials() throws Exception { final GoogleCredentials defaultCredential = GoogleCredentials.getApplicationDefault().createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE); @@ -72,7 +72,7 @@ public void DefaultCredentials() throws Exception { } @Test - public void IdTokenFromMetadata() throws Exception { + void IdTokenFromMetadata() throws Exception { final ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); IdToken idToken = credentials.idTokenWithAudience(computeUrl, null); assertNotNull(idToken); @@ -84,7 +84,7 @@ public void IdTokenFromMetadata() throws Exception { } @Test - public void FetchIdToken() throws Exception { + 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 8449919e4..034507e07 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,24 @@ 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 { + 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 { + 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 82a38e3df..ca0ec4fc1 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/functional/FTServiceAccountCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -52,9 +52,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 = @@ -65,19 +65,19 @@ public final class FTServiceAccountCredentialsTest { "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; @Test - public void NoScopeNoAudienceComputeTest() throws Exception { + void NoScopeNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(computeUrl); assertEquals(200, response.getStatusCode()); } @Test - public void NoScopeNoAudienceBigQueryTest() throws Exception { + void NoScopeNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(bigQueryUrl); assertEquals(200, response.getStatusCode()); } @Test - public void NoScopeNoAudienceOnePlatformTest() throws Exception { + void NoScopeNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(cloudTasksUrl); assertEquals(200, response.getStatusCode()); } @@ -85,7 +85,7 @@ public void NoScopeNoAudienceOnePlatformTest() throws Exception { // TODO: add Storage case @Test - public void AudienceSetNoScopeTest() throws Exception { + void AudienceSetNoScopeTest() throws Exception { final GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); IdTokenCredentials tokenCredential = @@ -106,14 +106,14 @@ public void AudienceSetNoScopeTest() throws Exception { } @Test - public void ScopeSetNoAudienceStorageTest() throws Exception { + void ScopeSetNoAudienceStorageTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(storageUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } @Test - public void ScopeSetNoAudienceComputeTest() throws Exception { + void ScopeSetNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(computeUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); @@ -121,36 +121,36 @@ public void ScopeSetNoAudienceComputeTest() throws Exception { } @Test - public void ScopeSetNoAudienceBigQueryTest() throws Exception { + void ScopeSetNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(bigQueryUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } @Test - public void ScopeSetNoAudienceOnePlatformTest() throws Exception { + void ScopeSetNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(cloudTasksUrl, OAuth2Utils.CLOUD_PLATFORM_SCOPE); assertEquals(200, response.getStatusCode()); } @Test - public void WrongScopeComputeTest() throws Exception { + void WrongScopeComputeTest() throws Exception { executeRequestWrongScope(computeUrl); } @Test - public void WrongScopeStorageTest() throws Exception { + void WrongScopeStorageTest() throws Exception { executeRequestWrongScope(storageUrl); } @Test - public void WrongScopeBigQueryTest() throws Exception { + void WrongScopeBigQueryTest() throws Exception { executeRequestWrongScope(bigQueryUrl); } @Test - public void WrongScopeOnePlatformTest() throws Exception { + void WrongScopeOnePlatformTest() throws Exception { executeRequestWrongScope(cloudTasksUrl); } diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index a09ff65ce..92bdc6a94 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -22,36 +22,6 @@ - - junit47 - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - - - **/IT*.java - **/functional/*.java - - sponge_log - - - - org.apache.maven.surefire - surefire-junit47 - ${surefire.version} - - - - - - native-test @@ -193,14 +163,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 @@ -234,7 +196,14 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.3 + ${surefire.version} + + + org.apache.maven.surefire + surefire-junit-platform + ${surefire.version} + + 1200 sponge_log @@ -329,21 +298,32 @@ com.google.api api-common + + junit junit + 4.13.2 test - org.hamcrest - hamcrest-core - 1.3 + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine test org.mockito mockito-core - 4.11.0 + test + + + org.mockito + mockito-junit-jupiter test diff --git a/pom.xml b/pom.xml index 22297dda7..4da5388cb 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,10 +151,11 @@ ${project.findbugs.version} - junit - junit + org.junit + junit-bom ${project.junit.version} - test + pom + import com.google.appengine @@ -280,7 +293,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.2 + ${surefire.version} sponge_log @@ -391,6 +404,20 @@ maven-resources-plugin 3.3.1 + + org.apache.maven.plugins + maven-dependency-plugin + + + + + + junit:junit + + org.junit.jupiter:junit-jupiter-engine + + +