diff --git a/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java b/appengine/javatests/com/google/auth/appengine/AppEngineCredentialsTest.java index 41b52384a..e1c3d5201 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.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import 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 com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; @@ -51,10 +51,13 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Unit tests for AppEngineCredentials */ -class AppEngineCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class AppEngineCredentialsTest extends BaseSerializationTest { private static Collection SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope1", "scope2")); @@ -62,7 +65,7 @@ class AppEngineCredentialsTest extends BaseSerializationTest { private static final String EXPECTED_ACCOUNT = "serviceAccount"; @Test - void constructor_usesAppIdentityService() throws IOException { + public void constructor_usesAppIdentityService() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -80,7 +83,7 @@ void constructor_usesAppIdentityService() throws IOException { } @Test - void refreshAccessToken_sameAs() throws IOException { + public void refreshAccessToken_sameAs() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -97,7 +100,7 @@ void refreshAccessToken_sameAs() throws IOException { } @Test - void getAccount_sameAs() { + public void getAccount_sameAs() throws IOException { MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setServiceAccountName(EXPECTED_ACCOUNT); AppEngineCredentials credentials = @@ -109,7 +112,7 @@ void getAccount_sameAs() { } @Test - void sign_sameAs() { + public void sign_sameAs() throws IOException { byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; MockAppIdentityService appIdentity = new MockAppIdentityService(); appIdentity.setSignature(expectedSignature); @@ -122,7 +125,7 @@ void sign_sameAs() { } @Test - void createScoped_clonesWithScopes() throws IOException { + public void createScoped_clonesWithScopes() throws IOException { String expectedAccessToken = "ExpectedAccessToken"; Collection emptyScopes = Collections.emptyList(); @@ -135,10 +138,11 @@ void createScoped_clonesWithScopes() throws IOException { .setAppIdentityService(appIdentity) .build(); assertTrue(credentials.createScopedRequired()); - assertThrows( - Exception.class, - () -> credentials.getRequestMetadata(CALL_URI), - "Should not be able to use credential without scopes."); + try { + credentials.getRequestMetadata(CALL_URI); + fail("Should not be able to use credential without scopes."); + } catch (Exception expected) { + } assertEquals(0, appIdentity.getGetAccessTokenCallCount()); GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); @@ -151,7 +155,7 @@ void createScoped_clonesWithScopes() throws IOException { } @Test - void equals_true() { + public void equals_true() throws IOException { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -171,7 +175,7 @@ void equals_true() { } @Test - void equals_false_scopes() { + public void equals_false_scopes() throws IOException { Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); @@ -191,7 +195,7 @@ void equals_false_scopes() { } @Test - void toString_containsFields() { + public void toString_containsFields() throws IOException { String expectedToString = String.format( "AppEngineCredentials{scopes=[%s], scopesRequired=%b, appIdentityServiceClassName=%s}", @@ -209,7 +213,7 @@ void toString_containsFields() { } @Test - void hashCode_equals() { + public void hashCode_equals() throws IOException { Collection emptyScopes = Collections.emptyList(); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -226,7 +230,7 @@ void hashCode_equals() { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { Collection scopes = Collections.singleton("SomeScope"); MockAppIdentityService appIdentity = new MockAppIdentityService(); AppEngineCredentials credentials = @@ -245,7 +249,7 @@ private static void assertContainsBearerToken(Map> metadata assertNotNull(token); String expectedValue = "Bearer " + token; List authorizations = metadata.get("Authorization"); - assertNotNull(authorizations, "Authorization headers not found"); - assertTrue(authorizations.contains(expectedValue), "Bearer token not found"); + assertNotNull("Authorization headers not found", authorizations); + assertTrue("Bearer token not found", authorizations.contains(expectedValue)); } } diff --git a/appengine/pom.xml b/appengine/pom.xml index ecadff5a3..5ed3d4033 100644 --- a/appengine/pom.xml +++ b/appengine/pom.xml @@ -68,8 +68,8 @@ guava - org.junit.jupiter - junit-jupiter-api + junit + junit test diff --git a/credentials/javatests/com/google/auth/SigningExceptionTest.java b/credentials/javatests/com/google/auth/SigningExceptionTest.java index e498924a3..0d7aa48c5 100644 --- a/credentials/javatests/com/google/auth/SigningExceptionTest.java +++ b/credentials/javatests/com/google/auth/SigningExceptionTest.java @@ -31,28 +31,29 @@ package com.google.auth; -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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import com.google.auth.ServiceAccountSigner.SigningException; -import org.junit.jupiter.api.Test; +import java.io.IOException; +import org.junit.Test; -class SigningExceptionTest { +public class SigningExceptionTest { private static final String EXPECTED_MESSAGE = "message"; private static final RuntimeException EXPECTED_CAUSE = new RuntimeException(); @Test - void constructor() { + public void constructor() { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); assertEquals(EXPECTED_MESSAGE, signingException.getMessage()); assertSame(EXPECTED_CAUSE, signingException.getCause()); } @Test - void equals_true() { + public 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)); @@ -60,7 +61,7 @@ void equals_true() { } @Test - void equals_false_message() { + public 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)); @@ -68,7 +69,7 @@ void equals_false_message() { } @Test - void equals_false_cause() { + public void equals_false_cause() throws IOException { SigningException signingException = new SigningException(EXPECTED_MESSAGE, EXPECTED_CAUSE); SigningException otherSigningException = new SigningException("otherMessage", new RuntimeException()); @@ -77,7 +78,7 @@ void equals_false_cause() { } @Test - void hashCode_equals() { + public 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 6048dc662..a5c969958 100644 --- a/credentials/pom.xml +++ b/credentials/pom.xml @@ -50,8 +50,8 @@ - org.junit.jupiter - junit-jupiter-api + junit + junit test diff --git a/oauth2_http/javatests/com/google/auth/TestUtils.java b/oauth2_http/javatests/com/google/auth/TestUtils.java index d2218092e..f7c53c9f9 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.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponseException; @@ -46,8 +46,8 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @@ -64,31 +64,35 @@ public class TestUtils { public static void assertContainsBearerToken(Map> metadata, String token) { assertNotNull(metadata); assertNotNull(token); - assertTrue(hasBearerToken(metadata, token), "Bearer token not found"); + assertTrue("Bearer token not found", hasBearerToken(metadata, token)); } public static void assertNotContainsBearerToken( Map> metadata, String token) { assertNotNull(metadata); assertNotNull(token); - assertFalse(hasBearerToken(metadata, token), "Bearer token found"); + assertFalse("Bearer token found", hasBearerToken(metadata, token)); } private static boolean hasBearerToken(Map> metadata, String token) { String expectedValue = AuthHttpConstants.BEARER + " " + token; List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull(authorizations, "Authorization headers not found"); + assertNotNull("Authorization headers not found", authorizations); return authorizations.contains(expectedValue); } public static InputStream jsonToInputStream(GenericJson json) throws IOException { json.setFactory(JSON_FACTORY); String text = json.toPrettyString(); - return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); + return new ByteArrayInputStream(text.getBytes("UTF-8")); } public static InputStream stringToInputStream(String text) { - return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); + try { + return new ByteArrayInputStream(text.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("Unexpected encoding exception", e); + } } public static Map parseQuery(String query) throws IOException { diff --git a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java index 96673b787..723cec837 100644 --- a/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java +++ b/oauth2_http/javatests/com/google/auth/http/HttpCredentialsAdapterTest.java @@ -32,8 +32,8 @@ package com.google.auth.http; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; @@ -47,17 +47,20 @@ import com.google.auth.oauth2.OAuth2Credentials; import com.google.auth.oauth2.UserCredentials; import java.io.IOException; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link HttpCredentialsAdapter}. */ -class HttpCredentialsAdapterTest { +@RunWith(JUnit4.class) +public 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 - void initialize_populatesOAuth2Credentials() throws IOException { + public void initialize_populatesOAuth2Credentials() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -84,7 +87,7 @@ void initialize_populatesOAuth2Credentials() throws IOException { } @Test - void initialize_populatesOAuth2Credentials_handle401() throws IOException { + public void initialize_populatesOAuth2Credentials_handle401() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; @@ -122,7 +125,7 @@ void initialize_populatesOAuth2Credentials_handle401() throws IOException { } @Test - void initialize_noURI() throws IOException { + public void initialize_noURI() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken; MockTokenServerTransportFactory tokenServerTransportFactory = @@ -151,7 +154,7 @@ void initialize_noURI() throws IOException { } @Test - void getCredentials() { + public void getCredentials() { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java index 12aef9fbc..58a9d0501 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AccessTokenTest.java @@ -31,22 +31,25 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Date; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Unit tests for AccessToken */ -class AccessTokenTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class AccessTokenTest extends BaseSerializationTest { private static final String TOKEN = "AccessToken"; private static final Date EXPIRATION_DATE = new Date(); @Test - void constructor() { + public void constructor() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(TOKEN, accessToken.getTokenValue()); assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); @@ -54,7 +57,7 @@ void constructor() { } @Test - void equals_true() { + public void equals_true() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertTrue(accessToken.equals(otherAccessToken)); @@ -62,7 +65,7 @@ void equals_true() { } @Test - void equals_false_token() { + public void equals_false_token() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken("otherToken", EXPIRATION_DATE); assertFalse(accessToken.equals(otherAccessToken)); @@ -70,7 +73,7 @@ void equals_false_token() { } @Test - void equals_false_expirationDate() { + public void equals_false_expirationDate() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, new Date(EXPIRATION_DATE.getTime() + 42)); assertFalse(accessToken.equals(otherAccessToken)); @@ -78,7 +81,7 @@ void equals_false_expirationDate() { } @Test - void toString_containsFields() { + public void toString_containsFields() { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); String expectedToString = String.format( @@ -88,14 +91,14 @@ void toString_containsFields() { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken otherAccessToken = new AccessToken(TOKEN, EXPIRATION_DATE); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { AccessToken accessToken = new AccessToken(TOKEN, EXPIRATION_DATE); AccessToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java index 6ba82ef75..82b76d879 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AppEngineCredentialsTest.java @@ -31,12 +31,12 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import 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 com.google.common.collect.ImmutableMap; import java.io.IOException; @@ -47,9 +47,12 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -class AppEngineCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class AppEngineCredentialsTest extends BaseSerializationTest { private static final String EXPECTED_ACCESS_TOKEN = "ExpectedAccessToken"; private static final Date EXPECTED_EXPIRATION_DATE = @@ -63,7 +66,7 @@ class AppEngineCredentialsTest extends BaseSerializationTest { Collections.unmodifiableCollection(Arrays.asList("scope3")); @Test - void constructor_usesAppIdentityService() throws IOException { + public void constructor_usesAppIdentityService() throws IOException { Collection scopes = Collections.singleton("SomeScope"); TestAppEngineCredentials credentials = new TestAppEngineCredentials(scopes); List forNameArgs = credentials.getForNameArgs(); @@ -75,24 +78,23 @@ void constructor_usesAppIdentityService() throws IOException { } @Test - void constructor_noAppEngineRuntime_throwsHelpfulLoadError() { - IOException exception = - assertThrows( - IOException.class, - TestAppEngineCredentialsNoSdk::new, - "Credential expected to fail to load if credential class not present."); - String message = exception.getMessage(); - assertTrue(message.contains("Check that the App Engine SDK is deployed.")); - assertTrue(exception.getCause() instanceof ClassNotFoundException); - assertTrue( - exception - .getCause() - .getMessage() - .contains(AppEngineCredentials.APP_IDENTITY_SERVICE_FACTORY_CLASS)); + public void constructor_noAppEngineRuntime_throwsHelpfulLoadError() throws IOException { + try { + new TestAppEngineCredentialsNoSdk(); + fail("Credential expected to fail to load if credential class not present."); + } catch (IOException e) { + String message = e.getMessage(); + assertTrue(message.contains("Check that the App Engine SDK is deployed.")); + assertTrue(e.getCause() instanceof ClassNotFoundException); + assertTrue( + e.getCause() + .getMessage() + .contains(AppEngineCredentials.APP_IDENTITY_SERVICE_FACTORY_CLASS)); + } } @Test - void refreshAccessToken_sameAs() throws IOException { + public void refreshAccessToken_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); AccessToken accessToken = credentials.refreshAccessToken(); assertEquals(EXPECTED_ACCESS_TOKEN, accessToken.getTokenValue()); @@ -100,25 +102,27 @@ void refreshAccessToken_sameAs() throws IOException { } @Test - void getAccount_sameAs() throws IOException { + public void getAccount_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(EXPECTED_ACCOUNT, credentials.getAccount()); } @Test - void sign_sameAs() throws IOException { + public void sign_sameAs() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertArrayEquals(EXPECTED_SIGNATURE, credentials.sign("Bytes to sign".getBytes())); } @Test - void createScoped_clonesWithScopes() throws IOException { + public void createScoped_clonesWithScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); - assertThrows( - Exception.class, - credentials::refreshAccessToken, - "Should not be able to use credential without scopes."); + try { + credentials.refreshAccessToken(); + fail("Should not be able to use credential without scopes."); + } catch (Exception expected) { + // Expected + } GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); assertNotSame(credentials, scopedCredentials); @@ -129,7 +133,7 @@ void createScoped_clonesWithScopes() throws IOException { } @Test - void createScoped_defaultScopes() throws IOException { + public void createScoped_defaultScopes() throws IOException { TestAppEngineCredentials credentials = new TestAppEngineCredentials(null); assertTrue(credentials.createScopedRequired()); @@ -148,7 +152,7 @@ void createScoped_defaultScopes() throws IOException { } @Test - void equals_true() throws IOException { + public void equals_true() throws IOException { GoogleCredentials credentials = new TestAppEngineCredentials(SCOPES); GoogleCredentials otherCredentials = new TestAppEngineCredentials(SCOPES); assertTrue(credentials.equals(credentials)); @@ -157,7 +161,7 @@ void equals_true() throws IOException { } @Test - void equals_false_scopes() throws IOException { + public void equals_false_scopes() throws IOException { final Collection emptyScopes = Collections.emptyList(); Collection scopes = Collections.singleton("SomeScope"); AppEngineCredentials credentials = new TestAppEngineCredentials(emptyScopes); @@ -167,7 +171,7 @@ void equals_false_scopes() throws IOException { } @Test - void toString_containsFields() throws IOException { + public void toString_containsFields() throws IOException { String expectedToString = String.format( "TestAppEngineCredentials{scopes=[%s], scopesRequired=%b}", "SomeScope", false); @@ -177,13 +181,13 @@ void toString_containsFields() throws IOException { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { AppEngineCredentials credentials = new TestAppEngineCredentials(SCOPES); assertEquals(credentials.hashCode(), credentials.hashCode()); } @Test - void serialize() throws IOException, ClassNotFoundException { + public 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 e52365c80..942f6183f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/AwsCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonParser; @@ -52,10 +52,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link AwsCredentials}. */ -class AwsCredentialsTest { +@RunWith(JUnit4.class) +public class AwsCredentialsTest { private static final String STS_URL = "https://sts.googleapis.com"; private static final String AWS_CREDENTIALS_URL = "https://www.aws-credentials.com"; @@ -99,7 +102,7 @@ class AwsCredentialsTest { .build(); @Test - void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -117,7 +120,7 @@ void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException } @Test - void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -140,7 +143,7 @@ void refreshAccessToken_withServiceAccountImpersonation() throws IOException { } @Test - void retrieveSubjectToken() throws IOException { + public void retrieveSubjectToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -184,7 +187,7 @@ void retrieveSubjectToken() throws IOException { } @Test - void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { + public void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -255,7 +258,7 @@ void retrieveSubjectTokenWithSessionTokenUrl() throws IOException { } @Test - void retrieveSubjectToken_noRegion_expectThrows() { + public void retrieveSubjectToken_noRegion_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -269,10 +272,12 @@ void retrieveSubjectToken_noRegion_expectThrows() { .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); - IOException exception = - assertThrows( - IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); - assertEquals("Failed to retrieve AWS region.", exception.getMessage()); + try { + awsCredential.retrieveSubjectToken(); + fail("Should not be able to use credential without exception."); + } catch (IOException exception) { + assertEquals("Failed to retrieve AWS region.", exception.getMessage()); + } List requests = transportFactory.transport.getRequests(); assertEquals(1, requests.size()); @@ -282,7 +287,7 @@ void retrieveSubjectToken_noRegion_expectThrows() { } @Test - void retrieveSubjectToken_noRole_expectThrows() { + public void retrieveSubjectToken_noRole_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -297,10 +302,12 @@ void retrieveSubjectToken_noRole_expectThrows() { .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); - IOException exception = - assertThrows( - IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); - assertEquals("Failed to retrieve AWS IAM role.", exception.getMessage()); + try { + awsCredential.retrieveSubjectToken(); + fail("Should not be able to use credential without exception."); + } catch (IOException exception) { + assertEquals("Failed to retrieve AWS IAM role.", exception.getMessage()); + } List requests = transportFactory.transport.getRequests(); assertEquals(2, requests.size()); @@ -313,7 +320,7 @@ void retrieveSubjectToken_noRole_expectThrows() { } @Test - void retrieveSubjectToken_noCredentials_expectThrows() { + public void retrieveSubjectToken_noCredentials_expectThrows() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -328,10 +335,12 @@ void retrieveSubjectToken_noCredentials_expectThrows() { .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); - IOException exception = - assertThrows( - IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); - assertEquals("Failed to retrieve AWS credentials.", exception.getMessage()); + try { + awsCredential.retrieveSubjectToken(); + fail("Should not be able to use credential without exception."); + } catch (IOException exception) { + assertEquals("Failed to retrieve AWS credentials.", exception.getMessage()); + } List requests = transportFactory.transport.getRequests(); assertEquals(3, requests.size()); @@ -347,7 +356,7 @@ void retrieveSubjectToken_noCredentials_expectThrows() { } @Test - void retrieveSubjectToken_noRegionUrlProvided() { + public void retrieveSubjectToken_noRegionUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -362,13 +371,15 @@ void retrieveSubjectToken_noRegionUrlProvided() { .setCredentialSource(new AwsCredentialSource(credentialSource)) .build(); - IOException exception = - assertThrows( - IOException.class, awsCredential::retrieveSubjectToken, "Exception should be thrown."); - assertEquals( - "Unable to determine the AWS region. The credential source does not " - + "contain the region URL.", - exception.getMessage()); + try { + awsCredential.retrieveSubjectToken(); + fail("Should not be able to use credential without exception."); + } catch (IOException exception) { + assertEquals( + "Unable to determine the AWS region. The credential source does not " + + "contain the region URL.", + exception.getMessage()); + } // No requests because the credential source does not contain region URL. List requests = transportFactory.transport.getRequests(); @@ -376,7 +387,7 @@ void retrieveSubjectToken_noRegionUrlProvided() { } @Test - void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { + public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -397,7 +408,7 @@ void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOExcept } @Test - void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { + public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider .setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId") @@ -419,7 +430,7 @@ void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOExce } @Test - void getAwsSecurityCredentials_fromMetadataServer() throws IOException { + public void getAwsSecurityCredentials_fromMetadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -448,7 +459,7 @@ void getAwsSecurityCredentials_fromMetadataServer() throws IOException { } @Test - void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { + public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -463,16 +474,14 @@ void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { .setCredentialSource(new AwsCredentialSource(credentialSource)) .build(); - IOException exception = - assertThrows( - IOException.class, - () -> { - awsCredential.getAwsSecurityCredentials(EMPTY_METADATA_HEADERS); - }, - "Exception should be thrown."); - assertEquals( - "Unable to determine the AWS IAM role name. The credential source does not contain the url field.", - exception.getMessage()); + try { + awsCredential.getAwsSecurityCredentials(EMPTY_METADATA_HEADERS); + fail("Should not be able to use credential without exception."); + } catch (IOException exception) { + assertEquals( + "Unable to determine the AWS IAM role name. The credential source does not contain the url field.", + exception.getMessage()); + } // No requests because url field is not present in credential source. List requests = transportFactory.transport.getRequests(); @@ -480,7 +489,7 @@ void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() { } @Test - void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { + public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_REGION", "region"); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -507,7 +516,7 @@ void getAwsRegion_awsRegionEnvironmentVariable() throws IOException { } @Test - void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { + public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion"); @@ -533,7 +542,7 @@ void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException { } @Test - void getAwsRegion_metadataServer() throws IOException { + public void getAwsRegion_metadataServer() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredentials = @@ -561,7 +570,7 @@ void getAwsRegion_metadataServer() throws IOException { } @Test - void createdScoped_clonedCredentialWithAddedScopes() { + public void createdScoped_clonedCredentialWithAddedScopes() { AwsCredentials credentials = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) @@ -590,46 +599,47 @@ void createdScoped_clonedCredentialWithAddedScopes() { } @Test - void credentialSource_invalidAwsEnvironmentId() { + public void credentialSource_invalidAwsEnvironmentId() { Map credentialSource = new HashMap<>(); credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "azure1"); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new AwsCredentialSource(credentialSource), - "Exception should be thrown."); - assertEquals("Invalid AWS environment ID.", exception.getMessage()); + try { + new AwsCredentialSource(credentialSource); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals("Invalid AWS environment ID.", e.getMessage()); + } } @Test - void credentialSource_invalidAwsEnvironmentVersion() { + public void credentialSource_invalidAwsEnvironmentVersion() { Map credentialSource = new HashMap<>(); int environmentVersion = 2; credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL); credentialSource.put("environment_id", "aws" + environmentVersion); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new AwsCredentialSource(credentialSource), - "Exception should be thrown."); - assertEquals( - String.format("AWS version %s is not supported in the current build.", environmentVersion), - exception.getMessage()); + try { + new AwsCredentialSource(credentialSource); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals( + String.format( + "AWS version %s is not supported in the current build.", environmentVersion), + e.getMessage()); + } } @Test - void credentialSource_missingRegionalCredVerificationUrl() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new AwsCredentialSource(new HashMap<>()), - "Exception should be thrown."); - assertEquals( - "A regional_cred_verification_url representing the GetCallerIdentity action URL must be specified.", - exception.getMessage()); + public void credentialSource_missingRegionalCredVerificationUrl() { + try { + new AwsCredentialSource(new HashMap()); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals( + "A regional_cred_verification_url representing the GetCallerIdentity action URL must be specified.", + e.getMessage()); + } } @Test diff --git a/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/AwsRequestSignerTest.java index e43bb1dd9..fd2c26d12 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.jupiter.api.Assertions.assertEquals; +import static org.junit.Assert.assertEquals; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -42,8 +42,8 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.Before; +import org.junit.Test; /** * Tests for {@link AwsRequestSigner}. @@ -51,7 +51,7 @@ *

Examples of sigv4 signed requests: * https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html */ -class AwsRequestSignerTest { +public class AwsRequestSignerTest { private static final String DATE = "Mon, 09 Sep 2011 23:36:00 GMT"; private static final String X_AMZ_DATE = "20200811T065522Z"; @@ -62,15 +62,15 @@ class AwsRequestSignerTest { private AwsSecurityCredentials awsSecurityCredentials; - @BeforeEach - void setUp() throws IOException { + @Before + public void setUp() throws IOException { awsSecurityCredentials = retrieveAwsSecurityCredentials(); } // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.req // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-vanilla.sreq @Test - void sign_getHost() { + public void sign_getHost() { String url = "https://host.foo.com"; Map headers = new HashMap<>(); @@ -101,7 +101,7 @@ 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 - void sign_getHostRelativePath() { + public void sign_getHostRelativePath() { String url = "https://host.foo.com/foo/bar/../.."; Map headers = new HashMap<>(); @@ -132,7 +132,7 @@ 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 - void sign_getHostInvalidPath() { + public void sign_getHostInvalidPath() { String url = "https://host.foo.com/./"; Map headers = new HashMap<>(); @@ -163,7 +163,7 @@ 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 - void sign_getHostDotPath() { + public void sign_getHostDotPath() { String url = "https://host.foo.com/./foo"; Map headers = new HashMap<>(); @@ -194,7 +194,7 @@ 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 - void sign_getHostUtf8Path() { + public void sign_getHostUtf8Path() { String url = "https://host.foo.com/%E1%88%B4"; Map headers = new HashMap<>(); @@ -225,7 +225,7 @@ 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 - void sign_getHostDuplicateQueryParam() { + public void sign_getHostDuplicateQueryParam() { String url = "https://host.foo.com/?foo=Zoo&foo=aha"; Map headers = new HashMap<>(); @@ -256,7 +256,7 @@ 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 - void sign_postWithUpperCaseHeaderKey() { + public void sign_postWithUpperCaseHeaderKey() { String url = "https://host.foo.com/"; String headerKey = "ZOO"; String headerValue = "zoobar"; @@ -291,7 +291,7 @@ 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 - void sign_postWithUpperCaseHeaderValue() { + public void sign_postWithUpperCaseHeaderValue() { String url = "https://host.foo.com/"; String headerKey = "zoo"; String headerValue = "ZOOBAR"; @@ -326,7 +326,7 @@ 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 - void sign_postWithHeader() { + public void sign_postWithHeader() { String url = "https://host.foo.com/"; String headerKey = "p"; String headerValue = "phfft"; @@ -361,7 +361,7 @@ 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 - void sign_postWithBodyNoCustomHeaders() { + public void sign_postWithBodyNoCustomHeaders() { String url = "https://host.foo.com/"; String headerKey = "Content-Type"; String headerValue = "application/x-www-form-urlencoded"; @@ -397,7 +397,7 @@ 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 - void sign_postWithQueryString() { + public void sign_postWithQueryString() { String url = "https://host.foo.com/?foo=bar"; Map headers = new HashMap<>(); @@ -426,7 +426,7 @@ void sign_postWithQueryString() { } @Test - void sign_getDescribeRegions() { + public void sign_getDescribeRegions() { String url = "https://ec2.us-east-2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15"; Map additionalHeaders = new HashMap<>(); @@ -457,7 +457,7 @@ void sign_getDescribeRegions() { } @Test - void sign_postGetCallerIdentity() { + public void sign_postGetCallerIdentity() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; Map additionalHeaders = new HashMap<>(); @@ -488,7 +488,7 @@ void sign_postGetCallerIdentity() { } @Test - void sign_postGetCallerIdentityNoToken() { + public void sign_postGetCallerIdentityNoToken() { String url = "https://sts.us-east-2.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; AwsSecurityCredentials awsSecurityCredentialsWithoutToken = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java index 1409507ea..d7a5ca015 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ClientIdTest.java @@ -31,23 +31,25 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import com.google.api.client.json.GenericJson; import com.google.auth.TestUtils; import java.io.IOException; import java.io.InputStream; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Unit tests for ClientId */ -class ClientIdTest { +@RunWith(JUnit4.class) +public class ClientIdTest { private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; @Test - void constructor() { + public void constructor() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); @@ -55,22 +57,20 @@ void constructor() { assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test - void constructor_nullClientId_throws() { - assertThrows( - NullPointerException.class, - () -> ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build()); + @Test(expected = NullPointerException.class) + public void constructor_nullClientId_throws() { + ClientId.newBuilder().setClientSecret(CLIENT_SECRET).build(); } @Test - void constructor_nullClientSecret() { + public void constructor_nullClientSecret() { ClientId clientId = ClientId.newBuilder().setClientId(CLIENT_ID).build(); assertEquals(CLIENT_ID, clientId.getClientId()); assertNull(clientId.getClientSecret()); } @Test - void fromJson_web() throws IOException { + public void fromJson_web() throws IOException { GenericJson json = writeClientIdJson("web", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -80,7 +80,7 @@ void fromJson_web() throws IOException { } @Test - void fromJson_installed() throws IOException { + public void fromJson_installed() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, CLIENT_SECRET); ClientId clientId = ClientId.fromJson(json); @@ -90,7 +90,7 @@ void fromJson_installed() throws IOException { } @Test - void fromJson_installedNoSecret() throws IOException { + public void fromJson_installedNoSecret() throws IOException { GenericJson json = writeClientIdJson("installed", CLIENT_ID, null); ClientId clientId = ClientId.fromJson(json); @@ -99,44 +99,42 @@ void fromJson_installedNoSecret() throws IOException { assertNull(clientId.getClientSecret()); } - @Test - void fromJson_invalidType_throws() { + @Test(expected = IOException.class) + public void fromJson_invalidType_throws() throws IOException { GenericJson json = writeClientIdJson("invalid", CLIENT_ID, null); - assertThrows(IOException.class, () -> ClientId.fromJson(json)); + ClientId.fromJson(json); } - @Test - void fromJson_noClientId_throws() { + @Test(expected = IOException.class) + public void fromJson_noClientId_throws() throws IOException { GenericJson json = writeClientIdJson("web", null, null); - assertThrows(IOException.class, () -> ClientId.fromJson(json)); + ClientId.fromJson(json); } - @Test - void fromJson_zeroLengthClientId_throws() { + @Test(expected = IOException.class) + public void fromJson_zeroLengthClientId_throws() throws IOException { GenericJson json = writeClientIdJson("web", "", null); - assertThrows(IOException.class, () -> ClientId.fromJson(json)); + ClientId.fromJson(json); } @Test - void fromResource() throws IOException { + public void fromResource() throws IOException { ClientId clientId = ClientId.fromResource(ClientIdTest.class, "/client_secret.json"); assertEquals(CLIENT_ID, clientId.getClientId()); assertEquals(CLIENT_SECRET, clientId.getClientSecret()); } - @Test - void fromResource_badResource() { - assertThrows( - NullPointerException.class, - () -> ClientId.fromResource(ClientIdTest.class, "invalid.json")); + @Test(expected = NullPointerException.class) + public void fromResource_badResource() throws IOException { + ClientId.fromResource(ClientIdTest.class, "invalid.json"); } @Test - void fromStream() throws IOException { + public void fromStream() throws IOException { String text = "{" + "\"web\": {" @@ -157,7 +155,7 @@ void fromStream() throws IOException { } @Test - void fromStream_invalidJson_doesNotThrow() throws IOException { + public 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 110214508..2dc075f17 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.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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import com.google.api.client.util.Clock; import java.io.BufferedReader; @@ -43,14 +43,18 @@ import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Unit tests for CloudShellCredentials */ -class CloudShellCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class CloudShellCredentialsTest extends BaseSerializationTest { @Test - void refreshAccessToken() throws IOException { - try (ServerSocket authSocket = new ServerSocket(0)) { + public void refreshAccessToken() throws IOException { + final ServerSocket authSocket = new ServerSocket(0); + try { Runnable serverTask = new Runnable() { @Override @@ -76,11 +80,13 @@ public void run() { GoogleCredentials creds = CloudShellCredentials.newBuilder().setAuthPort(authSocket.getLocalPort()).build(); assertEquals("token", creds.refreshAccessToken().getTokenValue()); + } finally { + authSocket.close(); } } @Test - void equals_true() { + public void equals_true() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertTrue(credentials.equals(otherCredentials)); @@ -88,7 +94,7 @@ void equals_true() { } @Test - void equals_false_authPort() { + public void equals_false_authPort() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(43).build(); assertFalse(credentials.equals(otherCredentials)); @@ -96,21 +102,21 @@ void equals_false_authPort() { } @Test - void toString_containsFields() { + public void toString_containsFields() throws IOException { String expectedToString = String.format("CloudShellCredentials{authPort=%d}", 42); GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(expectedToString, credentials.toString()); } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials otherCredentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { GoogleCredentials credentials = CloudShellCredentials.newBuilder().setAuthPort(42).build(); GoogleCredentials deserializedCredentials = serializeAndDeserialize(credentials); assertEquals(credentials, deserializedCredentials); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java index 26b57113b..34dff5c1f 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java @@ -31,14 +31,14 @@ package com.google.auth.oauth2; -import static org.junit.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.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -60,10 +60,13 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link ComputeEngineCredentials}. */ -class ComputeEngineCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class ComputeEngineCredentialsTest extends BaseSerializationTest { private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo"); @@ -116,7 +119,7 @@ public HttpTransport create() { } @Test - void createTokenUrlWithScopes_null_scopes() { + public void createTokenUrlWithScopes_null_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); Collection scopes = credentials.getScopes(); @@ -127,9 +130,9 @@ void createTokenUrlWithScopes_null_scopes() { } @Test - void createTokenUrlWithScopes_empty_scopes() { + public void createTokenUrlWithScopes_empty_scopes() { ComputeEngineCredentials.Builder builder = - ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); + ComputeEngineCredentials.newBuilder().setScopes(Collections.emptyList()); ComputeEngineCredentials credentials = builder.build(); Collection scopes = credentials.getScopes(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -140,7 +143,7 @@ void createTokenUrlWithScopes_empty_scopes() { } @Test - void createTokenUrlWithScopes_single_scope() { + public void createTokenUrlWithScopes_single_scope() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(Arrays.asList("foo")).build(); String tokenUrlWithScopes = credentials.createTokenUrlWithScopes(); @@ -152,7 +155,7 @@ void createTokenUrlWithScopes_single_scope() { } @Test - void createTokenUrlWithScopes_multiple_scopes() { + public void createTokenUrlWithScopes_multiple_scopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder() .setScopes(Arrays.asList(null, "foo", "", "bar")) @@ -167,7 +170,7 @@ void createTokenUrlWithScopes_multiple_scopes() { } @Test - void createTokenUrlWithScopes_defaultScopes() { + public void createTokenUrlWithScopes_defaultScopes() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().build(); credentials = (ComputeEngineCredentials) @@ -182,7 +185,7 @@ void createTokenUrlWithScopes_defaultScopes() { } @Test - void createScoped() { + public void createScoped() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setScopes(null).build(); ComputeEngineCredentials credentialsWithScopes = @@ -194,7 +197,7 @@ void createScoped() { } @Test - void createScoped_defaultScopes() { + public void createScoped_defaultScopes() { GoogleCredentials credentials = ComputeEngineCredentials.create().createScoped(null, Arrays.asList("foo")); Collection scopes = ((ComputeEngineCredentials) credentials).getScopes(); @@ -204,7 +207,7 @@ void createScoped_defaultScopes() { } @Test - void getRequestMetadata_hasAccessToken() throws IOException { + public void getRequestMetadata_hasAccessToken() throws IOException { String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(accessToken); @@ -216,45 +219,44 @@ void getRequestMetadata_hasAccessToken() throws IOException { } @Test - void getRequestMetadata_missingServiceAccount_throws() { + public void getRequestMetadata_missingServiceAccount_throws() { String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(accessToken); transportFactory.transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - - IOException exception = - assertThrows( - IOException.class, - () -> credentials.getRequestMetadata(CALL_URI), - "Expected error refreshing token."); - String message = exception.getMessage(); - assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND))); - assertTrue(message.contains("scope"), "Message should mention scopes are missing on the VM."); + try { + credentials.getRequestMetadata(CALL_URI); + fail("Expected error refreshing token."); + } catch (IOException expected) { + String message = expected.getMessage(); + assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND))); + // Message should mention scopes are missing on the VM. + assertTrue(message.contains("scope")); + } } @Test - void getRequestMetadata_serverError_throws() { + public void getRequestMetadata_serverError_throws() { String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(accessToken); transportFactory.transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - - IOException exception = - assertThrows( - IOException.class, - () -> credentials.getRequestMetadata(CALL_URI), - "Expected error refreshing token."); - String message = exception.getMessage(); - assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR))); - assertTrue(message.contains("Unexpected")); + try { + credentials.getRequestMetadata(CALL_URI); + fail("Expected error refreshing token."); + } catch (IOException expected) { + String message = expected.getMessage(); + assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR))); + assertTrue(message.contains("Unexpected")); + } } @Test - void equals_true() { + public void equals_true() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -265,7 +267,7 @@ void equals_true() { } @Test - void equals_false_transportFactory() { + public void equals_false_transportFactory() throws IOException { MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); @@ -280,7 +282,7 @@ void equals_false_transportFactory() { } @Test - void toString_containsFields() { + public void toString_containsFields() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); String expectedToString = @@ -295,7 +297,7 @@ void toString_containsFields() { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -310,7 +312,7 @@ void hashCode_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { MockMetadataServerTransportFactory serverTransportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = @@ -331,7 +333,7 @@ void serialize() throws IOException, ClassNotFoundException { } @Test - void getAccount_sameAs() { + public void getAccount_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -343,7 +345,7 @@ void getAccount_sameAs() { } @Test - void getAccount_missing_throws() { + public void getAccount_missing_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -368,18 +370,18 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - RuntimeException exception = - assertThrows( - RuntimeException.class, - credentials::getAccount, - "Fetching default service account should have failed"); - assertEquals("Failed to get service account", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("404")); + try { + credentials.getAccount(); + fail("Fetching default service account should have failed"); + } catch (RuntimeException e) { + assertEquals("Failed to get service account", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("404")); + } } @Test - void getAccount_emptyContent_throws() { + public void getAccount_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String defaultAccountEmail = "mail@mail.com"; @@ -403,18 +405,18 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - RuntimeException exception = - assertThrows( - RuntimeException.class, - credentials::getAccount, - "Fetching default service account should have failed"); - assertEquals("Failed to get service account", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("Empty content")); + try { + credentials.getAccount(); + fail("Fetching default service account should have failed"); + } catch (RuntimeException e) { + assertEquals("Failed to get service account", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("Empty content")); + } } @Test - void sign_sameAs() { + public void sign_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -430,7 +432,7 @@ void sign_sameAs() { } @Test - void sign_getAccountFails() { + public void sign_getAccountFails() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; byte[] expectedSignature = {0xD, 0xE, 0xA, 0xD}; @@ -440,14 +442,17 @@ void sign_getAccountFails() { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - SigningException exception = - assertThrows(SigningException.class, () -> credentials.sign(expectedSignature)); - assertNotNull(exception.getMessage()); - assertNotNull(exception.getCause()); + try { + credentials.sign(expectedSignature); + fail("Should not be able to use credential without exception."); + } catch (SigningException ex) { + assertNotNull(ex.getMessage()); + assertNotNull(ex.getCause()); + } } @Test - void sign_accessDenied_throws() { + public void sign_accessDenied_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -476,17 +481,19 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - SigningException exception = - assertThrows( - SigningException.class, () -> credentials.sign(bytes), "Signing should have failed"); - assertEquals("Failed to sign the provided bytes", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("403")); + try { + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + credentials.sign(bytes); + fail("Signing should have failed"); + } catch (SigningException e) { + assertEquals("Failed to sign the provided bytes", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("403")); + } } @Test - void sign_serverError_throws() { + public void sign_serverError_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -515,17 +522,19 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - SigningException exception = - assertThrows( - SigningException.class, () -> credentials.sign(bytes), "Signing should have failed"); - assertEquals("Failed to sign the provided bytes", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("500")); + try { + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + credentials.sign(bytes); + fail("Signing should have failed"); + } catch (SigningException e) { + assertEquals("Failed to sign the provided bytes", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("500")); + } } @Test - void sign_emptyContent_throws() { + public void sign_emptyContent_throws() { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; String defaultAccountEmail = "mail@mail.com"; @@ -553,17 +562,19 @@ public LowLevelHttpResponse execute() throws IOException { ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - SigningException exception = - assertThrows( - SigningException.class, () -> credentials.sign(bytes), "Signing should have failed"); - assertEquals("Failed to sign the provided bytes", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("Empty content")); + try { + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + credentials.sign(bytes); + fail("Signing should have failed"); + } catch (SigningException e) { + assertEquals("Failed to sign the provided bytes", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("Empty content")); + } } @Test - void idTokenWithAudience_sameAs() throws IOException { + public void idTokenWithAudience_sameAs() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(STANDARD_ID_TOKEN); ComputeEngineCredentials credentials = @@ -584,7 +595,7 @@ void idTokenWithAudience_sameAs() throws IOException { } @Test - void idTokenWithAudience_standard() throws IOException { + public void idTokenWithAudience_standard() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -603,7 +614,7 @@ void idTokenWithAudience_standard() throws IOException { @Test @SuppressWarnings("unchecked") - void idTokenWithAudience_full() throws IOException { + public void idTokenWithAudience_full() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -617,14 +628,14 @@ void idTokenWithAudience_full() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - assertTrue(p.containsKey("google"), "Full ID Token format not provided"); + assertTrue("Full ID Token format not provided", p.containsKey("google")); ArrayMap googleClaim = (ArrayMap) p.get("google"); assertTrue(googleClaim.containsKey("compute_engine")); } @Test @SuppressWarnings("unchecked") - void idTokenWithAudience_license() throws IOException { + public void idTokenWithAudience_license() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); ComputeEngineCredentials credentials = ComputeEngineCredentials.newBuilder().setHttpTransportFactory(transportFactory).build(); @@ -640,7 +651,7 @@ void idTokenWithAudience_license() throws IOException { .build(); tokenCredential.refresh(); Payload p = tokenCredential.getIdToken().getJsonWebSignature().getPayload(); - assertTrue(p.containsKey("google"), "Full ID Token format not provided"); + assertTrue("Full ID Token format not provided", p.containsKey("google")); ArrayMap googleClaim = (ArrayMap) p.get("google"); assertTrue(googleClaim.containsKey("license")); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java index a43f8ac7a..ac042e065 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/CredentialAccessBoundaryTest.java @@ -31,22 +31,25 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.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.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link CredentialAccessBoundary} and encompassing classes. */ -class CredentialAccessBoundaryTest { +@RunWith(JUnit4.class) +public class CredentialAccessBoundaryTest { @Test - void credentialAccessBoundary() { + public void credentialAccessBoundary() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -89,25 +92,27 @@ void credentialAccessBoundary() { } @Test - void credentialAccessBoundary_nullRules_throws() { - assertThrows( - NullPointerException.class, - () -> CredentialAccessBoundary.newBuilder().build(), - "Should fail."); + public void credentialAccessBoundary_nullRules_throws() { + try { + CredentialAccessBoundary.newBuilder().build(); + fail("Should fail."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void credentialAccessBoundary_withoutRules_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> CredentialAccessBoundary.newBuilder().setRules(new ArrayList<>()).build(), - "Should fail."); - assertEquals("At least one access boundary rule must be provided.", exception.getMessage()); + public void credentialAccessBoundary_withoutRules_throws() { + try { + CredentialAccessBoundary.newBuilder().setRules(new ArrayList()).build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("At least one access boundary rule must be provided.", e.getMessage()); + } } @Test - void credentialAccessBoundary_ruleCountExceeded_throws() { + public void credentialAccessBoundary_ruleCountExceeded_throws() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -119,14 +124,16 @@ void credentialAccessBoundary_ruleCountExceeded_throws() { builder.addRule(rule); } - IllegalArgumentException exception = - assertThrows(IllegalArgumentException.class, builder::build, "Should fail."); - assertEquals( - "The provided list has more than 10 access boundary rules.", exception.getMessage()); + try { + builder.build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("The provided list has more than 10 access boundary rules.", e.getMessage()); + } } @Test - void credentialAccessBoundary_toJson() { + public void credentialAccessBoundary_toJson() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -165,7 +172,7 @@ void credentialAccessBoundary_toJson() { } @Test - void accessBoundaryRule_allFields() { + public void accessBoundaryRule_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -185,7 +192,7 @@ void accessBoundaryRule_allFields() { } @Test - void accessBoundaryRule_requiredFields() { + public void accessBoundaryRule_requiredFields() { AccessBoundaryRule rule = AccessBoundaryRule.newBuilder() .setAvailableResource("resource") @@ -199,83 +206,79 @@ void accessBoundaryRule_requiredFields() { } @Test - void accessBoundaryRule_withEmptyAvailableResource_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - AccessBoundaryRule.newBuilder() - .setAvailableResource("") - .addAvailablePermission("permission") - .build(); - }, - "Should fail."); - assertEquals("The provided availableResource is empty.", exception.getMessage()); + public void accessBoundaryRule_withEmptyAvailableResource_throws() { + try { + AccessBoundaryRule.newBuilder() + .setAvailableResource("") + .addAvailablePermission("permission") + .build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("The provided availableResource is empty.", e.getMessage()); + } } @Test - void accessBoundaryRule_withoutAvailableResource_throws() { - assertThrows( - NullPointerException.class, - () -> AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(), - "Should fail."); + public void accessBoundaryRule_withoutAvailableResource_throws() { + try { + AccessBoundaryRule.newBuilder().addAvailablePermission("permission").build(); + fail("Should fail."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void accessBoundaryRule_withoutAvailablePermissions_throws() { - assertThrows( - NullPointerException.class, - () -> AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(), - "Should fail."); + public void accessBoundaryRule_withoutAvailablePermissions_throws() { + try { + AccessBoundaryRule.newBuilder().setAvailableResource("resource").build(); + fail("Should fail."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void accessBoundaryRule_withEmptyAvailablePermissions_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - AccessBoundaryRule.newBuilder() - .setAvailableResource("resource") - .setAvailablePermissions(new ArrayList()) - .build(); - }, - "Should fail."); - assertEquals("The list of provided availablePermissions is empty.", exception.getMessage()); + public void accessBoundaryRule_withEmptyAvailablePermissions_throws() { + try { + AccessBoundaryRule.newBuilder() + .setAvailableResource("resource") + .setAvailablePermissions(new ArrayList()) + .build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("The list of provided availablePermissions is empty.", e.getMessage()); + } } @Test - void accessBoundaryRule_withNullAvailablePermissions_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - AccessBoundaryRule.newBuilder() - .setAvailableResource("resource") - .addAvailablePermission(null) - .build(); - }, - "Should fail."); - assertEquals("One of the provided available permissions is null.", exception.getMessage()); + public void accessBoundaryRule_withNullAvailablePermissions_throws() { + try { + AccessBoundaryRule.newBuilder() + .setAvailableResource("resource") + .addAvailablePermission(null) + .build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("One of the provided available permissions is null.", e.getMessage()); + } } @Test - void accessBoundaryRule_withEmptyAvailablePermission_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - AccessBoundaryRule.newBuilder() - .setAvailableResource("resource") - .addAvailablePermission("") - .build(); - }, - "Should fail."); - assertEquals("One of the provided available permissions is empty.", exception.getMessage()); + public void accessBoundaryRule_withEmptyAvailablePermission_throws() { + try { + AccessBoundaryRule.newBuilder() + .setAvailableResource("resource") + .addAvailablePermission("") + .build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("One of the provided available permissions is empty.", e.getMessage()); + } } @Test - void availabilityCondition_allFields() { + public void availabilityCondition_allFields() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder() .setExpression("expression") @@ -289,7 +292,7 @@ void availabilityCondition_allFields() { } @Test - void availabilityCondition_expressionOnly() { + public void availabilityCondition_expressionOnly() { AvailabilityCondition availabilityCondition = AvailabilityCondition.newBuilder().setExpression("expression").build(); @@ -299,20 +302,22 @@ void availabilityCondition_expressionOnly() { } @Test - void availabilityCondition_nullExpression_throws() { - assertThrows( - NullPointerException.class, - () -> AvailabilityCondition.newBuilder().setExpression(null).build(), - "Should fail."); + public void availabilityCondition_nullExpression_throws() { + try { + AvailabilityCondition.newBuilder().setExpression(null).build(); + fail("Should fail."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void availabilityCondition_emptyExpression_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> AvailabilityCondition.newBuilder().setExpression("").build(), - "Should fail."); - assertEquals("The provided expression is empty.", exception.getMessage()); + public void availabilityCondition_emptyExpression_throws() { + try { + AvailabilityCondition.newBuilder().setExpression("").build(); + fail("Should fail."); + } catch (IllegalArgumentException e) { + assertEquals("The provided expression is empty.", e.getMessage()); + } } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DefaultCredentialsProviderTest.java index c8f787d20..8db555318 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.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.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 com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; @@ -65,10 +65,13 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link DefaultCredentialsProvider}. */ -class DefaultCredentialsProviderTest { +@RunWith(JUnit4.class) +public class DefaultCredentialsProviderTest { private static final String USER_CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String USER_CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -98,36 +101,36 @@ public HttpTransport create() { } @Test - void getDefaultCredentials_noCredentials_throws() { + public void getDefaultCredentials_noCredentials_throws() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); - IOException exception = - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected."); - String message = exception.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected."); + } catch (IOException e) { + String message = e.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + } } @Test - void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() { + public void getDefaultCredentials_noCredentialsSandbox_throwsNonSecurity() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setFileSandbox(true); - IOException exception = - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected."); - String message = exception.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected."); + } catch (IOException e) { + String message = e.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + } } @Test - void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { + public void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -138,39 +141,43 @@ void getDefaultCredentials_envValidSandbox_throwsNonSecurity() throws Exception testProvider.addFile(userPath, userStream); testProvider.setEnv(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR, userPath); - IOException exception = - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected."); - String message = exception.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected."); + } catch (IOException e) { + String message = e.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + } } @Test - void getDefaultCredentials_noCredentials_singleGceTestRequest() { + public void getDefaultCredentials_noCredentials_singleGceTestRequest() { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected."); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected."); + } catch (IOException expected) { + // Expected + } assertEquals( transportFactory.transport.getRequestCount(), ComputeEngineCredentials.MAX_COMPUTE_PING_TRIES); - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected."); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected."); + } catch (IOException expected) { + // Expected + } assertEquals( transportFactory.transport.getRequestCount(), ComputeEngineCredentials.MAX_COMPUTE_PING_TRIES); } @Test - void getDefaultCredentials_caches() throws IOException { + public void getDefaultCredentials_caches() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -182,42 +189,43 @@ void getDefaultCredentials_caches() throws IOException { } @Test - void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { + public void getDefaultCredentials_appEngineClassWithoutRuntime_NotFoundError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( DefaultCredentialsProvider.APP_ENGINE_SIGNAL_CLASS, MockOffAppEngineSystemProperty.class); testProvider.setProperty("isOnGAEStandard7", "true"); - IOException exception = - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected when not on App Engine."); - String message = exception.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected when not on App Engine."); + } catch (IOException e) { + String message = e.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + } } @Test - void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { + public void getDefaultCredentials_appEngineRuntimeWithoutClass_throwsHelpfulLoadError() { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( DefaultCredentialsProvider.APP_ENGINE_SIGNAL_CLASS, MockAppEngineSystemProperty.class); testProvider.setProperty("isOnGAEStandard7", "true"); - IOException exception = - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "Credential expected to fail to load if credential class not present."); - String message = exception.getMessage(); - assertFalse(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); - assertTrue(message.contains("Check that the App Engine SDK is deployed.")); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("Credential expected to fail to load if credential class not present."); + } catch (IOException e) { + String message = e.getMessage(); + assertFalse(message.contains(DefaultCredentialsProvider.HELP_PERMALINK)); + assertTrue(message.contains("Check that the App Engine SDK is deployed.")); + } } @Test - void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() throws IOException { + public void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() + throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.addType( @@ -231,7 +239,7 @@ void getDefaultCredentials_appEngineSkipWorks_retrievesCloudShellCredential() th } @Test - void getDefaultCredentials_compute_providesToken() throws IOException { + public void getDefaultCredentials_compute_providesToken() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(ACCESS_TOKEN); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -244,7 +252,7 @@ void getDefaultCredentials_compute_providesToken() throws IOException { } @Test - void getDefaultCredentials_cloudshell() throws IOException { + public void getDefaultCredentials_cloudshell() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CLOUD_SHELL_ENV_VAR, "4"); @@ -256,7 +264,7 @@ void getDefaultCredentials_cloudshell() throws IOException { } @Test - void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { + public void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOException { MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory(); transportFactory.transport.setAccessToken(ACCESS_TOKEN); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); @@ -269,24 +277,24 @@ void getDefaultCredentials_cloudshell_withComputCredentialsPresent() throws IOEx } @Test - void getDefaultCredentials_envMissingFile_throws() { + public void getDefaultCredentials_envMissingFile_throws() { final String invalidPath = "/invalid/path"; MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR, invalidPath); - IOException exception = - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "Non existent credential should throw exception"); - String message = exception.getMessage(); - assertTrue(message.contains(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR)); - assertTrue(message.contains(invalidPath)); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("Non existent credential should throw exception"); + } catch (IOException e) { + String message = e.getMessage(); + assertTrue(message.contains(DefaultCredentialsProvider.CREDENTIAL_ENV_VAR)); + assertTrue(message.contains(invalidPath)); + } } @Test - void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { + public void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -306,7 +314,7 @@ void getDefaultCredentials_envServiceAccount_providesToken() throws IOException } @Test - void getDefaultCredentials_envUser_providesToken() throws IOException { + public void getDefaultCredentials_envUser_providesToken() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -319,21 +327,23 @@ void getDefaultCredentials_envUser_providesToken() throws IOException { } @Test - void getDefaultCredentials_envNoGceCheck_noGceRequest() { + public void getDefaultCredentials_envNoGceCheck_noGceRequest() throws IOException { MockRequestCountingTransportFactory transportFactory = new MockRequestCountingTransportFactory(); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.NO_GCE_CHECK_ENV_VAR, "true"); - assertThrows( - IOException.class, - () -> testProvider.getDefaultCredentials(transportFactory), - "No credential expected."); + try { + testProvider.getDefaultCredentials(transportFactory); + fail("No credential expected."); + } catch (IOException expected) { + // Expected + } assertEquals(transportFactory.transport.getRequestCount(), 0); } @Test - void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { + public void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -341,7 +351,7 @@ void getDefaultCredentials_envGceMetadataHost_setsMetadataServerUrl() { } @Test - void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { + public void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { String testUrl = "192.0.2.0"; TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); testProvider.setEnv(DefaultCredentialsProvider.GCE_METADATA_HOST_ENV_VAR, testUrl); @@ -351,7 +361,7 @@ void getDefaultCredentials_envGceMetadataHost_setsTokenServerUrl() { } @Test - void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { + public void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { File cloudConfigDir = getTempDirectory(); InputStream userStream = UserCredentialsTest.writeUserStream( @@ -366,7 +376,7 @@ void getDefaultCredentials_wellKnownFileEnv_providesToken() throws IOException { } @Test - void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { + public void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File configDir = new File(homeDir, ".config"); File cloudConfigDir = new File(configDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); @@ -384,7 +394,7 @@ void getDefaultCredentials_wellKnownFileNonWindows_providesToken() throws IOExce } @Test - void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { + public void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOException { File homeDir = getTempDirectory(); File cloudConfigDir = new File(homeDir, DefaultCredentialsProvider.CLOUDSDK_CONFIG_DIRECTORY); InputStream userStream = @@ -401,7 +411,7 @@ void getDefaultCredentials_wellKnownFileWindows_providesToken() throws IOExcepti } @Test - void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { + public void getDefaultCredentials_envAndWellKnownFile_envPrecedence() throws IOException { final String refreshTokenEnv = "2/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; final String accessTokenEnv = "2/MkSJoj1xsli0AccessToken_NKPY2"; final String refreshTokenWkf = "3/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; @@ -456,7 +466,7 @@ public void flush() {} } @Test - void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { + public void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(false); assertNotNull(message); assertEquals(Level.WARNING, message.getLevel()); @@ -464,7 +474,7 @@ void getDefaultCredentials_wellKnownFile_logsGcloudWarning() throws IOException } @Test - void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { + public void getDefaultCredentials_wellKnownFile_suppressGcloudWarning() throws IOException { LogRecord message = getCredentialsAndReturnLogMessage(true); assertNull(message); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index f77c0bb19..77f34eac6 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -31,9 +31,9 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.auth.TestUtils; @@ -41,10 +41,13 @@ import java.io.IOException; import java.util.Date; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link DownscopedCredentials}. */ -class DownscopedCredentialsTest { +@RunWith(JUnit4.class) +public class DownscopedCredentialsTest { private static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n" @@ -80,7 +83,7 @@ public HttpTransport create() { } @Test - void refreshAccessToken() throws IOException { + public void refreshAccessToken() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -107,7 +110,7 @@ void refreshAccessToken() throws IOException { } @Test - void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { + public 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 @@ -135,7 +138,7 @@ void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOExcepti } @Test - void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { + public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); GoogleCredentials sourceCredentials = @@ -148,42 +151,42 @@ void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException .setHttpTransportFactory(transportFactory) .build(); - IOException exception = - assertThrows( - IOException.class, - downscopedCredentials::refreshAccessToken, - "Should fail as the source credential should not be able to be refreshed."); - assertEquals("Unable to refresh the provided source credential.", exception.getMessage()); + try { + downscopedCredentials.refreshAccessToken(); + fail("Should fail as the source credential should not be able to be refreshed."); + } catch (IOException e) { + assertEquals("Unable to refresh the provided source credential.", e.getMessage()); + } } @Test - void builder_noSourceCredential_throws() { - assertThrows( - NullPointerException.class, - () -> { - DownscopedCredentials.newBuilder() - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) - .build(); - }, - "Should fail as the source credential is null."); + public void builder_noSourceCredential_throws() { + try { + DownscopedCredentials.newBuilder() + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .build(); + fail("Should fail as the source credential is null."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void builder_noCredentialAccessBoundary_throws() throws IOException { - assertThrows( - NullPointerException.class, - () -> { - DownscopedCredentials.newBuilder() - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setSourceCredential(getServiceAccountSourceCredentials(/* canRefresh= */ true)) - .build(); - }, - "Should fail as no access boundary was provided."); + public void builder_noCredentialAccessBoundary_throws() throws IOException { + try { + DownscopedCredentials.newBuilder() + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setSourceCredential(getServiceAccountSourceCredentials(/* canRefresh= */ true)) + .build(); + fail("Should fail as no access boundary was provided."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void builder_noTransport_defaults() throws IOException { + public void builder_noTransport_defaults() throws IOException { GoogleCredentials sourceCredentials = getServiceAccountSourceCredentials(/* canRefresh= */ true); DownscopedCredentials credentials = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExecutableResponseTest.java index 7c8fec60d..6020ad51e 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.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.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +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 com.google.api.client.json.GenericJson; import java.io.IOException; import java.math.BigDecimal; import java.time.Instant; -import org.junit.jupiter.api.Test; +import org.junit.Test; /** Tests for {@link ExecutableResponse}. */ -class ExecutableResponseTest { +public 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 @@ class ExecutableResponseTest { private static final int EXPIRATION_DURATION = 3600; @Test - void constructor_successOidcResponse() throws IOException { + public void constructor_successOidcResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildOidcResponse()); assertTrue(response.isSuccessful()); @@ -63,12 +63,13 @@ void constructor_successOidcResponse() throws IOException { assertEquals(EXECUTABLE_SUPPORTED_MAX_VERSION, response.getVersion()); assertEquals(TOKEN_TYPE_OIDC, response.getTokenType()); assertEquals(ID_TOKEN, response.getSubjectToken()); - assertEquals( - Instant.now().getEpochSecond() + EXPIRATION_DURATION, response.getExpirationTime()); + assertTrue( + Instant.now().getEpochSecond() + EXPIRATION_DURATION == response.getExpirationTime()); } @Test - void constructor_successOidcResponseMissingExpirationTimeField_notExpired() throws IOException { + public void constructor_successOidcResponseMissingExpirationTimeField_notExpired() + throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("expiration_time"); @@ -84,7 +85,7 @@ void constructor_successOidcResponseMissingExpirationTimeField_notExpired() thro } @Test - void constructor_successSamlResponse() throws IOException { + public void constructor_successSamlResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildSamlResponse()); assertTrue(response.isSuccessful()); @@ -92,12 +93,13 @@ void constructor_successSamlResponse() throws IOException { assertEquals(EXECUTABLE_SUPPORTED_MAX_VERSION, response.getVersion()); assertEquals(TOKEN_TYPE_SAML, response.getTokenType()); assertEquals(SAML_RESPONSE, response.getSubjectToken()); - assertEquals( - Instant.now().getEpochSecond() + EXPIRATION_DURATION, response.getExpirationTime()); + assertTrue( + Instant.now().getEpochSecond() + EXPIRATION_DURATION == response.getExpirationTime()); } @Test - void constructor_successSamlResponseMissingExpirationTimeField_notExpired() throws IOException { + public void constructor_successSamlResponseMissingExpirationTimeField_notExpired() + throws IOException { GenericJson jsonResponse = buildSamlResponse(); jsonResponse.remove("expiration_time"); @@ -113,7 +115,7 @@ void constructor_successSamlResponseMissingExpirationTimeField_notExpired() thro } @Test - void constructor_validErrorResponse() throws IOException { + public void constructor_validErrorResponse() throws IOException { ExecutableResponse response = new ExecutableResponse(buildErrorResponse()); assertFalse(response.isSuccessful()); @@ -128,142 +130,134 @@ void constructor_validErrorResponse() throws IOException { } @Test - void constructor_errorResponseMissingCode_throws() { + public void constructor_errorResponseMissingCode_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; for (Object value : values) { jsonResponse.put("code", value); - - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain " - + "`error` and `message` fields when unsuccessful.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain " + + "`error` and `message` fields when unsuccessful.", + exception.getMessage()); + } } } @Test - void constructor_errorResponseMissingMessage_throws() { + public void constructor_errorResponseMissingMessage_throws() throws IOException { GenericJson jsonResponse = buildErrorResponse(); Object[] values = new Object[] {null, ""}; for (Object value : values) { jsonResponse.put("message", value); - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain " - + "`error` and `message` fields when unsuccessful.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain " + + "`error` and `message` fields when unsuccessful.", + exception.getMessage()); + } } } @Test - void constructor_successResponseMissingVersionField_throws() { + public void constructor_successResponseMissingVersionField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("version"); - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " - + "`version` field.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " + + "`version` field.", + exception.getMessage()); + } } @Test - void constructor_successResponseMissingSuccessField_throws() { + public void constructor_successResponseMissingSuccessField_throws() throws Exception { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("success"); - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " - + "`success` field.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " + + "`success` field.", + exception.getMessage()); + } } @Test - void constructor_successResponseMissingTokenTypeField_throws() { + public void constructor_successResponseMissingTokenTypeField_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); jsonResponse.remove("token_type"); - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " - + "`token_type` field.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response is missing the " + + "`token_type` field.", + exception.getMessage()); + } } @Test - void constructor_samlResponseMissingSubjectToken_throws() { + public void constructor_samlResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildSamlResponse(); Object[] values = new Object[] {null, ""}; for (Object value : values) { jsonResponse.put("saml_response", value); - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response does not " - + "contain a valid token.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response does not " + + "contain a valid token.", + exception.getMessage()); + } } } @Test - void constructor_oidcResponseMissingSubjectToken_throws() { + public void constructor_oidcResponseMissingSubjectToken_throws() throws IOException { GenericJson jsonResponse = buildOidcResponse(); Object[] values = new Object[] {null, ""}; for (Object value : values) { jsonResponse.put("id_token", value); - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> new ExecutableResponse(jsonResponse), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response does not " - + "contain a valid token.", - exception.getMessage()); + try { + new ExecutableResponse(jsonResponse); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response does not " + + "contain a valid token.", + exception.getMessage()); + } } } @Test - void isExpired() throws IOException { + public void isExpired() throws IOException { GenericJson jsonResponse = buildOidcResponse(); BigDecimal[] values = diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java index 75b88dcfa..1125ebc51 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ExternalAccountCredentialsTest.java @@ -32,11 +32,11 @@ package com.google.auth.oauth2; import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -54,10 +54,13 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link ExternalAccountCredentials}. */ +@RunWith(JUnit4.class) public class ExternalAccountCredentialsTest { private static final String STS_URL = "https://sts.googleapis.com"; @@ -82,13 +85,13 @@ public HttpTransport create() { private MockExternalAccountCredentialsTransportFactory transportFactory; - @BeforeEach - void setup() { + @Before + public void setup() { transportFactory = new MockExternalAccountCredentialsTransportFactory(); } @Test - void fromStream_identityPoolCredentials() throws IOException { + public void fromStream_identityPoolCredentials() throws IOException { GenericJson json = buildJsonIdentityPoolCredential(); ExternalAccountCredentials credential = @@ -98,7 +101,7 @@ void fromStream_identityPoolCredentials() throws IOException { } @Test - void fromStream_awsCredentials() throws IOException { + public void fromStream_awsCredentials() throws IOException { GenericJson json = buildJsonAwsCredential(); ExternalAccountCredentials credential = @@ -108,7 +111,7 @@ void fromStream_awsCredentials() throws IOException { } @Test - void fromStream_pluggableAuthCredentials() throws IOException { + public void fromStream_pluggableAuthCredentials() throws IOException { GenericJson json = buildJsonPluggableAuthCredential(); ExternalAccountCredentials credential = @@ -118,57 +121,56 @@ void fromStream_pluggableAuthCredentials() throws IOException { } @Test - void fromStream_invalidStream_throws() { + public void fromStream_invalidStream_throws() throws IOException { GenericJson json = buildJsonAwsCredential(); json.put("audience", new HashMap<>()); - CredentialFormatException exception = - assertThrows( - CredentialFormatException.class, - () -> ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)), - "Should fail."); - assertEquals("An invalid input stream was provided.", exception.getMessage()); + try { + ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)); + fail("Should fail."); + } catch (CredentialFormatException e) { + assertEquals("An invalid input stream was provided.", e.getMessage()); + } } @Test - void fromStream_nullTransport_throws() { - assertThrows( - NullPointerException.class, - () -> { - ExternalAccountCredentials.fromStream( - new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); - }, - "NullPointerException should be thrown."); + public void fromStream_nullTransport_throws() throws IOException { + try { + ExternalAccountCredentials.fromStream( + new ByteArrayInputStream("foo".getBytes()), /* transportFactory= */ null); + fail("NullPointerException should be thrown."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void fromStream_nullStream_throws() { - assertThrows( - NullPointerException.class, - () -> { - ExternalAccountCredentials.fromStream( - /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); - }, - "NullPointerException should be thrown."); + public void fromStream_nullStream_throws() throws IOException { + try { + ExternalAccountCredentials.fromStream( + /* credentialsStream= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); + fail("NullPointerException should be thrown."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void fromStream_invalidWorkloadAudience_throws() throws IOException { - CredentialFormatException exception = - assertThrows( - CredentialFormatException.class, - () -> { - GenericJson json = buildJsonIdentityPoolWorkforceCredential(); - json.put("audience", "invalidAudience"); - ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)); - }, - "CredentialFormatException should be thrown."); - assertEquals("An invalid input stream was provided.", exception.getMessage()); + public void fromStream_invalidWorkloadAudience_throws() throws IOException { + try { + GenericJson json = buildJsonIdentityPoolWorkforceCredential(); + json.put("audience", "invalidAudience"); + ExternalAccountCredentials credential = + ExternalAccountCredentials.fromStream(TestUtils.jsonToInputStream(json)); + fail("CredentialFormatException should be thrown."); + } catch (CredentialFormatException e) { + assertEquals("An invalid input stream was provided.", e.getMessage()); + } } @Test - void fromJson_identityPoolCredentialsWorkload() { + public void fromJson_identityPoolCredentialsWorkload() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -184,7 +186,7 @@ void fromJson_identityPoolCredentialsWorkload() { } @Test - void fromJson_identityPoolCredentialsWorkforce() { + public void fromJson_identityPoolCredentialsWorkforce() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -201,7 +203,7 @@ void fromJson_identityPoolCredentialsWorkforce() { } @Test - void fromJson_awsCredentials() { + public void fromJson_awsCredentials() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonAwsCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -215,7 +217,7 @@ void fromJson_awsCredentials() { } @Test - void fromJson_pluggableAuthCredentials() { + public void fromJson_pluggableAuthCredentials() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -235,7 +237,7 @@ void fromJson_pluggableAuthCredentials() { } @Test - void fromJson_pluggableAuthCredentialsWorkforce() { + public void fromJson_pluggableAuthCredentialsWorkforce() { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonPluggableAuthWorkforceCredential(), OAuth2Utils.HTTP_TRANSPORT_FACTORY); @@ -259,7 +261,7 @@ void fromJson_pluggableAuthCredentialsWorkforce() { } @Test - void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() { + public void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() { GenericJson json = buildJsonPluggableAuthCredential(); Map credentialSourceMap = (Map) json.get("credential_source"); // Add optional params to the executable config (timeout, output file path). @@ -286,40 +288,43 @@ void fromJson_pluggableAuthCredentials_allExecutableOptionsSet() { } @Test - void fromJson_nullJson_throws() { - assertThrows( - NullPointerException.class, - () -> - ExternalAccountCredentials.fromJson( - /* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY), - "Exception should be thrown."); + public void fromJson_nullJson_throws() { + try { + ExternalAccountCredentials.fromJson(/* json= */ null, OAuth2Utils.HTTP_TRANSPORT_FACTORY); + fail("Exception should be thrown."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void fromJson_invalidServiceAccountImpersonationUrl_throws() { + public void fromJson_invalidServiceAccountImpersonationUrl_throws() { GenericJson json = buildJsonIdentityPoolCredential(); json.put("service_account_impersonation_url", "https://iamcredentials.googleapis.com"); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY), - "Exception should be thrown."); - assertEquals( - "Unable to determine target principal from service account impersonation URL.", - exception.getMessage()); + try { + ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals( + "Unable to determine target principal from service account impersonation URL.", + e.getMessage()); + } } @Test - void fromJson_nullTransport_throws() { - assertThrows( - NullPointerException.class, - () -> ExternalAccountCredentials.fromJson(new HashMap<>(), /* transportFactory= */ null), - "Exception should be thrown."); + public void fromJson_nullTransport_throws() { + try { + ExternalAccountCredentials.fromJson( + new HashMap(), /* transportFactory= */ null); + fail("Exception should be thrown."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void fromJson_invalidWorkforceAudiences_throws() { + public void fromJson_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "//iam.googleapis.com/locations/global/workloadIdentityPools/pool/providers/provider", @@ -332,25 +337,23 @@ void fromJson_invalidWorkforceAudiences_throws() { "//iam.googleapis.com/locations/global/workforce/providers"); for (String audience : invalidAudiences) { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - GenericJson json = buildJsonIdentityPoolCredential(); - json.put("audience", audience); - json.put("workforce_pool_user_project", "userProject"); - - ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY); - }, - "Exception should be thrown."); - assertEquals( - "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", - exception.getMessage()); + try { + GenericJson json = buildJsonIdentityPoolCredential(); + json.put("audience", audience); + json.put("workforce_pool_user_project", "userProject"); + + ExternalAccountCredentials.fromJson(json, OAuth2Utils.HTTP_TRANSPORT_FACTORY); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals( + "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", + e.getMessage()); + } } } @Test - void constructor_builder() { + public void constructor_builder() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); @@ -388,46 +391,42 @@ void constructor_builder() { } @Test - void constructor_builder_invalidTokenUrl() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - ExternalAccountCredentials.Builder builder = - TestExternalAccountCredentials.newBuilder() - .setHttpTransportFactory(transportFactory) - .setAudience("audience") - .setSubjectTokenType("subjectTokenType") - .setTokenUrl("tokenUrl") - .setCredentialSource(new TestCredentialSource(FILE_CREDENTIAL_SOURCE_MAP)); - new TestExternalAccountCredentials(builder); - }, - "Should have failed since an invalid token URL was passed."); - assertEquals("The provided token URL is invalid.", exception.getMessage()); - } - - @Test - void constructor_builder_invalidServiceAccountImpersonationUrl() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - ExternalAccountCredentials.Builder builder = - TestExternalAccountCredentials.newBuilder() - .setHttpTransportFactory(transportFactory) - .setAudience("audience") - .setSubjectTokenType("subjectTokenType") - .setTokenUrl("tokenUrl") - .setCredentialSource(new TestCredentialSource(FILE_CREDENTIAL_SOURCE_MAP)) - .setServiceAccountImpersonationUrl("serviceAccountImpersonationUrl"); - new TestExternalAccountCredentials(builder); - }, - "Should have failed since an invalid token URL was passed."); - assertEquals("The provided token URL is invalid.", exception.getMessage()); - } - - @Test - void constructor_builderWithInvalidWorkforceAudiences_throws() { + public void constructor_builder_invalidTokenUrl() { + try { + ExternalAccountCredentials.Builder builder = + TestExternalAccountCredentials.newBuilder() + .setHttpTransportFactory(transportFactory) + .setAudience("audience") + .setSubjectTokenType("subjectTokenType") + .setTokenUrl("tokenUrl") + .setCredentialSource(new TestCredentialSource(FILE_CREDENTIAL_SOURCE_MAP)); + new TestExternalAccountCredentials(builder); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals("The provided token URL is invalid.", exception.getMessage()); + } + } + + @Test + public void constructor_builder_invalidServiceAccountImpersonationUrl() { + try { + ExternalAccountCredentials.Builder builder = + TestExternalAccountCredentials.newBuilder() + .setHttpTransportFactory(transportFactory) + .setAudience("audience") + .setSubjectTokenType("subjectTokenType") + .setTokenUrl("tokenUrl") + .setCredentialSource(new TestCredentialSource(FILE_CREDENTIAL_SOURCE_MAP)) + .setServiceAccountImpersonationUrl("serviceAccountImpersonationUrl"); + new TestExternalAccountCredentials(builder); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals("The provided token URL is invalid.", exception.getMessage()); + } + } + + @Test + public void constructor_builderWithInvalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -443,28 +442,26 @@ void constructor_builderWithInvalidWorkforceAudiences_throws() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); for (String audience : invalidAudiences) { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - TestExternalAccountCredentials.newBuilder() - .setWorkforcePoolUserProject("workforcePoolUserProject") - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setAudience(audience) - .setSubjectTokenType("subjectTokenType") - .setTokenUrl(STS_URL) - .setCredentialSource(new TestCredentialSource(credentialSource)) - .build(); - }, - "Exception should be thrown."); - assertEquals( - "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", - exception.getMessage()); + try { + TestExternalAccountCredentials.newBuilder() + .setWorkforcePoolUserProject("workforcePoolUserProject") + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setAudience(audience) + .setSubjectTokenType("subjectTokenType") + .setTokenUrl(STS_URL) + .setCredentialSource(new TestCredentialSource(credentialSource)) + .build(); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals( + "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", + exception.getMessage()); + } } } @Test - void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { + public void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { HashMap credentialSource = new HashMap<>(); credentialSource.put("file", "file"); // No exception should be thrown. @@ -479,7 +476,7 @@ void constructor_builderWithEmptyWorkforceUserProjectAndWorkforceAudience() { } @Test - void exchangeExternalCredentialForAccessToken() throws IOException { + public void exchangeExternalCredentialForAccessToken() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -498,7 +495,7 @@ void exchangeExternalCredentialForAccessToken() throws IOException { } @Test - void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { + public void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -523,7 +520,7 @@ void exchangeExternalCredentialForAccessToken_withInternalOptions() throws IOExc } @Test - void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() + public void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPassedToSts() throws IOException { ExternalAccountCredentials identityPoolCredential = ExternalAccountCredentials.fromJson( @@ -557,8 +554,9 @@ void exchangeExternalCredentialForAccessToken_workforceCred_expectUserProjectPas } @Test - void exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() - throws IOException { + public void + exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_expectOverridden() + throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson( buildJsonIdentityPoolWorkforceCredential(), transportFactory); @@ -583,7 +581,7 @@ void exchangeExternalCredentialForAccessToken_workforceCredWithInternalOptions_e } @Test - void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() + public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -606,7 +604,7 @@ void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonation() } @Test - void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOverride() + public void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOverride() throws IOException { transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime()); @@ -638,7 +636,7 @@ void exchangeExternalCredentialForAccessToken_withServiceAccountImpersonationOve } @Test - void exchangeExternalCredentialForAccessToken_throws() throws IOException { + public void exchangeExternalCredentialForAccessToken_throws() throws IOException { ExternalAccountCredentials credential = ExternalAccountCredentials.fromJson(buildJsonIdentityPoolCredential(), transportFactory); @@ -651,18 +649,18 @@ void exchangeExternalCredentialForAccessToken_throws() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); - OAuthException exception = - assertThrows( - OAuthException.class, - () -> credential.exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest), - "Exception should be thrown."); - assertEquals(errorCode, exception.getErrorCode()); - assertEquals(errorDescription, exception.getErrorDescription()); - assertEquals(errorUri, exception.getErrorUri()); + try { + credential.exchangeExternalCredentialForAccessToken(stsTokenExchangeRequest); + fail("Exception should be thrown."); + } catch (OAuthException e) { + assertEquals(errorCode, e.getErrorCode()); + assertEquals(errorDescription, e.getErrorDescription()); + assertEquals(errorUri, e.getErrorUri()); + } } @Test - void getRequestMetadata_withQuotaProjectId() throws IOException { + public void getRequestMetadata_withQuotaProjectId() throws IOException { TestExternalAccountCredentials testCredentials = (TestExternalAccountCredentials) TestExternalAccountCredentials.newBuilder() @@ -681,7 +679,7 @@ void getRequestMetadata_withQuotaProjectId() throws IOException { } @Test - void validateTokenUrl_validUrls() { + public void validateTokenUrl_validUrls() { List validUrls = Arrays.asList( "https://sts.googleapis.com", @@ -700,7 +698,7 @@ void validateTokenUrl_validUrls() { } @Test - void validateTokenUrl_invalidUrls() { + public void validateTokenUrl_invalidUrls() { List invalidUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -724,17 +722,17 @@ void validateTokenUrl_invalidUrls() { "https://us-east-1.sts.googleapis.com.evil.com"); for (String url : invalidUrls) { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> ExternalAccountCredentials.validateTokenUrl(url), - "Should have failed since an invalid URL was passed."); - assertEquals("The provided token URL is invalid.", exception.getMessage()); + try { + ExternalAccountCredentials.validateTokenUrl(url); + fail("Should have failed since an invalid URL was passed."); + } catch (IllegalArgumentException e) { + assertEquals("The provided token URL is invalid.", e.getMessage()); + } } } @Test - void validateServiceAccountImpersonationUrls_validUrls() { + public void validateServiceAccountImpersonationUrls_validUrls() { List validUrls = Arrays.asList( "https://iamcredentials.googleapis.com", @@ -754,7 +752,7 @@ void validateServiceAccountImpersonationUrls_validUrls() { } @Test - void validateServiceAccountImpersonationUrls_invalidUrls() { + public void validateServiceAccountImpersonationUrls_invalidUrls() { List invalidUrls = Arrays.asList( "https://sts.googleapis.com", @@ -778,13 +776,12 @@ void validateServiceAccountImpersonationUrls_invalidUrls() { "https://us-east-1.iamcredentials.googleapis.com.evil.com"); for (String url : invalidUrls) { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> ExternalAccountCredentials.validateServiceAccountImpersonationInfoUrl(url), - "Should have failed since an invalid URL was passed."); - assertEquals( - "The provided service account impersonation URL is invalid.", exception.getMessage()); + try { + ExternalAccountCredentials.validateServiceAccountImpersonationInfoUrl(url); + fail("Should have failed since an invalid URL was passed."); + } catch (IllegalArgumentException e) { + assertEquals("The provided service account impersonation URL is invalid.", e.getMessage()); + } } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java index 4505445ce..551aecf43 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.testing.http.MockHttpTransport; @@ -54,9 +54,12 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link GoogleCredentials}. */ +@RunWith(JUnit4.class) public class GoogleCredentialsTest { private static final String SA_CLIENT_EMAIL = @@ -101,30 +104,39 @@ public HttpTransport create() { } @Test - void getApplicationDefault_nullTransport_throws() { - assertThrows(NullPointerException.class, () -> GoogleCredentials.getApplicationDefault(null)); + public void getApplicationDefault_nullTransport_throws() throws IOException { + try { + GoogleCredentials.getApplicationDefault(null); + fail(); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_nullTransport_throws() { + public void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); - assertThrows( - NullPointerException.class, - () -> GoogleCredentials.fromStream(stream, null), - "Should throw if HttpTransportFactory is null"); + try { + GoogleCredentials.fromStream(stream, null); + fail("Should throw if HttpTransportFactory is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_nullStream_throws() { + public void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - assertThrows( - NullPointerException.class, - () -> GoogleCredentials.fromStream(null, transportFactory), - "Should throw if InputStream is null"); + try { + GoogleCredentials.fromStream(null, transportFactory); + fail("Should throw if InputStream is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_serviceAccount_providesToken() throws IOException { + public void fromStream_serviceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -145,7 +157,7 @@ void fromStream_serviceAccount_providesToken() throws IOException { } @Test - void fromStream_serviceAccountNoClientId_throws() throws IOException { + public void fromStream_serviceAccountNoClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -154,7 +166,7 @@ void fromStream_serviceAccountNoClientId_throws() throws IOException { } @Test - void fromStream_serviceAccountNoClientEmail_throws() throws IOException { + public void fromStream_serviceAccountNoClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -163,7 +175,7 @@ void fromStream_serviceAccountNoClientEmail_throws() throws IOException { } @Test - void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { + public void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -172,7 +184,7 @@ void fromStream_serviceAccountNoPrivateKey_throws() throws IOException { } @Test - void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { + public void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -181,7 +193,7 @@ void fromStream_serviceAccountNoPrivateKeyId_throws() throws IOException { } @Test - void fromStream_user_providesToken() throws IOException { + public void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(USER_CLIENT_ID, USER_CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -197,7 +209,7 @@ void fromStream_user_providesToken() throws IOException { } @Test - void fromStream_userNoClientId_throws() throws IOException { + public void fromStream_userNoClientId_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(null, USER_CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); @@ -205,7 +217,7 @@ void fromStream_userNoClientId_throws() throws IOException { } @Test - void fromStream_userNoClientSecret_throws() throws IOException { + public void fromStream_userNoClientSecret_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream(USER_CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); @@ -213,7 +225,7 @@ void fromStream_userNoClientSecret_throws() throws IOException { } @Test - void fromStream_userNoRefreshToken_throws() throws IOException { + public void fromStream_userNoRefreshToken_throws() throws IOException { InputStream userStream = UserCredentialsTest.writeUserStream( USER_CLIENT_ID, USER_CLIENT_SECRET, null, QUOTA_PROJECT); @@ -222,7 +234,7 @@ void fromStream_userNoRefreshToken_throws() throws IOException { } @Test - void fromStream_identityPoolCredentials_providesToken() throws IOException { + public void fromStream_identityPoolCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); InputStream identityPoolCredentialStream = @@ -241,7 +253,7 @@ void fromStream_identityPoolCredentials_providesToken() throws IOException { } @Test - void fromStream_awsCredentials_providesToken() throws IOException { + public void fromStream_awsCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -261,7 +273,7 @@ void fromStream_awsCredentials_providesToken() throws IOException { } @Test - void fromStream_pluggableAuthCredentials_providesToken() throws IOException { + public void fromStream_pluggableAuthCredentials_providesToken() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -284,7 +296,7 @@ void fromStream_pluggableAuthCredentials_providesToken() throws IOException { } @Test - void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { + public void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -320,7 +332,7 @@ void fromStream_Impersonation_providesToken_WithQuotaProject() throws IOExceptio } @Test - void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { + public void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOException { MockTokenServerTransportFactory transportFactoryForSource = new MockTokenServerTransportFactory(); transportFactoryForSource.transport.addServiceAccount( @@ -353,7 +365,7 @@ void fromStream_Impersonation_providesToken_WithoutQuotaProject() throws IOExcep } @Test - void createScoped_overloadCallsImplementation() { + public void createScoped_overloadCallsImplementation() { final AtomicReference> called = new AtomicReference<>(); final GoogleCredentials expectedScopedCredentials = new GoogleCredentials(); @@ -373,12 +385,13 @@ public GoogleCredentials createScoped(Collection scopes) { } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - IOException exception = - assertThrows( - IOException.class, - () -> GoogleCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY), - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - assertTrue(exception.getMessage().contains(expectedMessageContent)); + try { + GoogleCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY); + fail( + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedMessageContent)); + } } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITDownscopingTest.java index 875719fbc..bd00f42c4 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.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.jupiter.api.Test; +import org.junit.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). */ -class ITDownscopingTest { +public 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 @@ class ITDownscopingTest { * in the same bucket. */ @Test - void downscoping_serviceAccountSourceWithRefresh() throws IOException { + public void downscoping_serviceAccountSourceWithRefresh() throws IOException { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -122,12 +122,12 @@ public AccessToken refreshAccessToken() throws IOException { // Attempt to retrieve the object that the downscoped token does not have access to. This should // fail. - HttpResponseException exception = - assertThrows( - HttpResponseException.class, - () -> retrieveObjectFromGcs(credentials, GCS_OBJECT_NAME_WITHOUT_PERMISSION), - "Call to GCS should have failed."); - assertEquals(403, exception.getStatusCode()); + try { + retrieveObjectFromGcs(credentials, GCS_OBJECT_NAME_WITHOUT_PERMISSION); + fail("Call to GCS should have failed."); + } catch (HttpResponseException e) { + assertEquals(403, e.getStatusCode()); + } } private void retrieveObjectFromGcs(Credentials credentials, String objectName) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ITWorkloadIdentityFederationTest.java index 8ece218a4..3ab290993 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.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -52,8 +52,8 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Instant; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.Before; +import org.junit.Test; /** * Integration tests for Workload Identity Federation. @@ -63,7 +63,7 @@ * (workloadidentityfederation-setup). These tests call GCS to get bucket information. The bucket * name must be provided through the GCS_BUCKET environment variable. */ -class ITWorkloadIdentityFederationTest { +public final class ITWorkloadIdentityFederationTest { // Copy output from workloadidentityfederation-setup. private static final String AUDIENCE_PREFIX = @@ -76,8 +76,8 @@ class ITWorkloadIdentityFederationTest { private String clientEmail; - @BeforeEach - void setup() throws IOException { + @Before + public void setup() throws IOException { GenericJson keys = getServiceAccountKeyFileAsJson(); clientEmail = (String) keys.get("client_email"); } @@ -90,7 +90,7 @@ void setup() throws IOException { * service account key. Retrieves the OIDC token from a file. */ @Test - void identityPoolCredentials() throws IOException { + public void identityPoolCredentials() throws IOException { IdentityPoolCredentials identityPoolCredentials = (IdentityPoolCredentials) ExternalAccountCredentials.fromJson( @@ -109,7 +109,7 @@ void identityPoolCredentials() throws IOException { * service account key. */ @Test - void awsCredentials() throws Exception { + public void awsCredentials() throws Exception { String idToken = generateGoogleIdToken(AWS_AUDIENCE); String url = @@ -159,7 +159,7 @@ void awsCredentials() throws Exception { * service account key. Runs an executable to get the OIDC token. */ @Test - void pluggableAuthCredentials() throws IOException { + public void pluggableAuthCredentials() throws IOException { PluggableAuthCredentials pluggableAuthCredentials = (PluggableAuthCredentials) ExternalAccountCredentials.fromJson( @@ -271,7 +271,9 @@ private GenericJson buildAwsCredentialConfig() { private void callGcs(GoogleCredentials credentials) throws IOException { String bucketName = System.getenv("GCS_BUCKET"); - assertNotNull(bucketName, "GCS bucket name not set through GCS_BUCKET env variable."); + if (bucketName == null) { + fail("GCS bucket name not set through GCS_BUCKET env variable."); + } String url = "https://storage.googleapis.com/storage/v1/b/" + bucketName; diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java index e3dcec4b5..7dbf770c3 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenCredentialsTest.java @@ -31,16 +31,19 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.Assert.assertEquals; import java.io.IOException; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link IdTokenCredentials}. */ -class IdTokenCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class IdTokenCredentialsTest extends BaseSerializationTest { @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -66,7 +69,7 @@ void hashCode_equals() throws IOException { } @Test - void toString_equals() throws IOException { + public void toString_equals() throws IOException { ComputeEngineCredentialsTest.MockMetadataServerTransportFactory transportFactory = new ComputeEngineCredentialsTest.MockMetadataServerTransportFactory(); transportFactory.transport.setIdToken(ComputeEngineCredentialsTest.STANDARD_ID_TOKEN); @@ -92,7 +95,7 @@ void toString_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public 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 ae0f921e0..14c94995e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdTokenTest.java @@ -31,16 +31,19 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Date; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Unit tests for AccessToken */ -class IdTokenTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class IdTokenTest extends BaseSerializationTest { private static final String TOKEN_1 = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjM0OTRiMWU3ODZjZGFkMDkyZTQyMzc2NmJiZTM3ZjU0ZWQ4N2IyMmQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhdWQiOiJodHRwczovL2Zvby5iYXIiLCJhenAiOiJzdmMtMi00MjlAbWluZXJhbC1taW51dGlhLTgyMC5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInN1YiI6IjEwMDE0NzEwNjk5Njc2NDQ3OTA4NSIsImVtYWlsIjoic3ZjLTItNDI5QG1pbmVyYWwtbWludXRpYS04MjAuaWFtLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiaWF0IjoxNTY1Mzg3NTM4LCJleHAiOjE1NjUzOTExMzh9.foo"; @@ -49,14 +52,14 @@ class IdTokenTest extends BaseSerializationTest { private static final Date EXPIRATION_DATE = new Date((long) 1565391138 * 1000); @Test - void constructor() throws IOException { + public void constructor() throws IOException { IdToken idToken = IdToken.create(TOKEN_1); assertEquals(TOKEN_1, idToken.getTokenValue()); assertEquals(EXPIRATION_DATE, idToken.getExpirationTime()); } @Test - void equals_true() throws IOException { + public void equals_true() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertTrue(accessToken.equals(otherAccessToken)); @@ -64,7 +67,7 @@ void equals_true() throws IOException { } @Test - void equals_false_token() throws IOException { + public void equals_false_token() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_2); assertFalse(accessToken.equals(otherAccessToken)); @@ -72,7 +75,7 @@ void equals_false_token() throws IOException { } @Test - void toString_test() throws IOException { + public void toString_test() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); String expectedToString = String.format( @@ -82,14 +85,14 @@ void toString_test() throws IOException { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken otherAccessToken = IdToken.create(TOKEN_1); assertEquals(accessToken.hashCode(), otherAccessToken.hashCode()); } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { IdToken accessToken = IdToken.create(TOKEN_1); IdToken deserializedAccessToken = serializeAndDeserialize(accessToken); assertEquals(accessToken, deserializedAccessToken); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java index 73a3d2f12..e7d48978e 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/IdentityPoolCredentialsTest.java @@ -33,10 +33,10 @@ import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +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 com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -53,10 +53,13 @@ import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link IdentityPoolCredentials}. */ -class IdentityPoolCredentialsTest { +@RunWith(JUnit4.class) +public class IdentityPoolCredentialsTest { private static final String STS_URL = "https://sts.googleapis.com"; @@ -94,7 +97,7 @@ public HttpTransport create() { } @Test - void createdScoped_clonedCredentialWithAddedScopes() { + public void createdScoped_clonedCredentialWithAddedScopes() { IdentityPoolCredentials credentials = (IdentityPoolCredentials) IdentityPoolCredentials.newBuilder(FILE_SOURCED_CREDENTIAL) @@ -123,7 +126,7 @@ void createdScoped_clonedCredentialWithAddedScopes() { } @Test - void retrieveSubjectToken_fileSourced() throws IOException { + public void retrieveSubjectToken_fileSourced() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -150,7 +153,7 @@ void retrieveSubjectToken_fileSourced() throws IOException { } @Test - void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { + public void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -192,7 +195,7 @@ void retrieveSubjectToken_fileSourcedWithJsonFormat() throws IOException { } @Test - void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { + public void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException { File file = File.createTempFile("RETRIEVE_SUBJECT_TOKEN", /* suffix= */ null, /* directory= */ null); file.deleteOnExit(); @@ -204,16 +207,16 @@ void retrieveSubjectToken_fileSourcedWithNullFormat_throws() throws IOException credentialSourceMap.put("file", file.getAbsolutePath()); credentialSourceMap.put("format", formatMap); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new IdentityPoolCredentialSource(credentialSourceMap), - "Exception should be thrown due to null format."); - assertEquals("Invalid credential source format type: null.", exception.getMessage()); + try { + new IdentityPoolCredentialSource(credentialSourceMap); + fail("Exception should be thrown due to null format."); + } catch (IllegalArgumentException e) { + assertEquals("Invalid credential source format type: null.", e.getMessage()); + } } @Test - void retrieveSubjectToken_noFile_throws() { + public void retrieveSubjectToken_noFile_throws() { Map credentialSourceMap = new HashMap<>(); String path = "badPath"; credentialSourceMap.put("file", path); @@ -226,16 +229,18 @@ void retrieveSubjectToken_noFile_throws() { .setCredentialSource(credentialSource) .build(); - IOException exception = - assertThrows( - IOException.class, credentials::retrieveSubjectToken, "Exception should be thrown."); - assertEquals( - String.format("Invalid credential location. The file at %s does not exist.", path), - exception.getMessage()); + try { + credentials.retrieveSubjectToken(); + fail("Exception should be thrown."); + } catch (IOException e) { + assertEquals( + String.format("Invalid credential location. The file at %s does not exist.", path), + e.getMessage()); + } } @Test - void retrieveSubjectToken_urlSourced() throws IOException { + public void retrieveSubjectToken_urlSourced() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -253,7 +258,7 @@ void retrieveSubjectToken_urlSourced() throws IOException { } @Test - void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { + public void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -279,7 +284,7 @@ void retrieveSubjectToken_urlSourcedWithJsonFormat() throws IOException { } @Test - void retrieveSubjectToken_urlSourcedCredential_throws() { + public void retrieveSubjectToken_urlSourcedCredential_throws() { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -294,17 +299,19 @@ void retrieveSubjectToken_urlSourcedCredential_throws() { buildUrlBasedCredentialSource(transportFactory.transport.getMetadataUrl())) .build(); - IOException exception = - assertThrows( - IOException.class, credential::retrieveSubjectToken, "Exception should be thrown."); - assertEquals( - String.format( - "Error getting subject token from metadata server: %s", response.getMessage()), - exception.getMessage()); + try { + credential.retrieveSubjectToken(); + fail("Exception should be thrown."); + } catch (IOException e) { + assertEquals( + String.format( + "Error getting subject token from metadata server: %s", response.getMessage()), + e.getMessage()); + } } @Test - void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -323,7 +330,7 @@ void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException } @Test - void refreshAccessToken_internalOptionsSet() throws IOException { + public void refreshAccessToken_internalOptionsSet() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -357,7 +364,7 @@ void refreshAccessToken_internalOptionsSet() throws IOException { } @Test - void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -380,7 +387,7 @@ void refreshAccessToken_withServiceAccountImpersonation() throws IOException { } @Test - void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -416,7 +423,7 @@ void refreshAccessToken_workforceWithServiceAccountImpersonation() throws IOExce } @Test - void identityPoolCredentialSource_validFormats() { + public void identityPoolCredentialSource_validFormats() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -459,7 +466,7 @@ void identityPoolCredentialSource_validFormats() { } @Test - void identityPoolCredentialSource_caseInsensitive() { + public void identityPoolCredentialSource_caseInsensitive() { Map credentialSourceMapWithFileTextSource = new HashMap<>(); Map credentialSourceMapWithFileJsonTextSource = new HashMap<>(); Map credentialSourceMapWithUrlTextSource = new HashMap<>(); @@ -502,19 +509,19 @@ void identityPoolCredentialSource_caseInsensitive() { } @Test - void identityPoolCredentialSource_invalidSourceType() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new IdentityPoolCredentialSource(new HashMap<>()), - "Exception should be thrown."); - assertEquals( - "Missing credential source file location or URL. At least one must be specified.", - exception.getMessage()); + public void identityPoolCredentialSource_invalidSourceType() { + try { + new IdentityPoolCredentialSource(new HashMap<>()); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals( + "Missing credential source file location or URL. At least one must be specified.", + exception.getMessage()); + } } @Test - void identityPoolCredentialSource_invalidFormatType() { + public void identityPoolCredentialSource_invalidFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -522,16 +529,16 @@ void identityPoolCredentialSource_invalidFormatType() { format.put("type", "unsupportedType"); credentialSourceMap.put("format", format); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new IdentityPoolCredentialSource(credentialSourceMap), - "Exception should be thrown."); - assertEquals("Invalid credential source format type: unsupportedType.", exception.getMessage()); + try { + new IdentityPoolCredentialSource(credentialSourceMap); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals("Invalid credential source format type: unsupportedType.", e.getMessage()); + } } @Test - void identityPoolCredentialSource_nullFormatType() { + public void identityPoolCredentialSource_nullFormatType() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -539,16 +546,16 @@ void identityPoolCredentialSource_nullFormatType() { format.put("type", null); credentialSourceMap.put("format", format); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new IdentityPoolCredentialSource(credentialSourceMap), - "Exception should be thrown."); - assertEquals("Invalid credential source format type: null.", exception.getMessage()); + try { + new IdentityPoolCredentialSource(credentialSourceMap); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals("Invalid credential source format type: null.", e.getMessage()); + } } @Test - void identityPoolCredentialSource_subjectTokenFieldNameUnset() { + public void identityPoolCredentialSource_subjectTokenFieldNameUnset() { Map credentialSourceMap = new HashMap<>(); credentialSourceMap.put("url", "url"); @@ -556,18 +563,18 @@ void identityPoolCredentialSource_subjectTokenFieldNameUnset() { format.put("type", "json"); credentialSourceMap.put("format", format); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new IdentityPoolCredentialSource(credentialSourceMap), - "Exception should be thrown."); - assertEquals( - "When specifying a JSON credential type, the subject_token_field_name must be set.", - exception.getMessage()); + try { + new IdentityPoolCredentialSource(credentialSourceMap); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals( + "When specifying a JSON credential type, the subject_token_field_name must be set.", + e.getMessage()); + } } @Test - void builder() { + public void builder() { List scopes = Arrays.asList("scope1", "scope2"); IdentityPoolCredentials credentials = @@ -601,7 +608,7 @@ void builder() { } @Test - void builder_invalidWorkforceAudiences_throws() { + public void builder_invalidWorkforceAudiences_throws() { List invalidAudiences = Arrays.asList( "", @@ -615,30 +622,28 @@ void builder_invalidWorkforceAudiences_throws() { "//iam.googleapis.com/locations/global/workforce/providers"); for (String audience : invalidAudiences) { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - IdentityPoolCredentials.newBuilder() - .setWorkforcePoolUserProject("workforcePoolUserProject") - .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) - .setAudience(audience) - .setSubjectTokenType("subjectTokenType") - .setTokenUrl(STS_URL) - .setTokenInfoUrl("tokenInfoUrl") - .setCredentialSource(FILE_CREDENTIAL_SOURCE) - .setQuotaProjectId("quotaProjectId") - .build(); - }, - "Exception should be thrown."); - assertEquals( - "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", - exception.getMessage()); + try { + IdentityPoolCredentials.newBuilder() + .setWorkforcePoolUserProject("workforcePoolUserProject") + .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY) + .setAudience(audience) + .setSubjectTokenType("subjectTokenType") + .setTokenUrl(STS_URL) + .setTokenInfoUrl("tokenInfoUrl") + .setCredentialSource(FILE_CREDENTIAL_SOURCE) + .setQuotaProjectId("quotaProjectId") + .build(); + fail("Exception should be thrown."); + } catch (IllegalArgumentException e) { + assertEquals( + "The workforce_pool_user_project parameter should only be provided for a Workforce Pool configuration.", + e.getMessage()); + } } } @Test - void builder_emptyWorkforceUserProjectWithWorkforceAudience() { + public void builder_emptyWorkforceUserProjectWithWorkforceAudience() { // No exception should be thrown. IdentityPoolCredentials credentials = (IdentityPoolCredentials) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java index 4cbacb12d..8a3819d53 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java @@ -31,14 +31,14 @@ package com.google.auth.oauth2; -import static org.junit.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.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; @@ -69,13 +69,15 @@ import java.util.Date; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.TimeZone; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link ImpersonatedCredentials}. */ -class ImpersonatedCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class ImpersonatedCredentialsTest extends BaseSerializationTest { public static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -112,7 +114,8 @@ class ImpersonatedCredentialsTest extends BaseSerializationTest { + "CJzdWIiOiIxMDIxMDE1NTA4MzQyMDA3MDg1NjgifQ.redacted"; public static final String ACCESS_TOKEN = "1/MkSJoj1xsli0AccessToken_NKPY2"; - private static final Set IMMUTABLE_SCOPES_SET = ImmutableSet.of("scope1", "scope2"); + private static final ImmutableSet IMMUTABLE_SCOPES_SET = + ImmutableSet.of("scope1", "scope2"); private static final String PROJECT_ID = "project-id"; public static final String IMPERSONATED_CLIENT_EMAIL = "impersonated-account@iam.gserviceaccount.com"; @@ -151,8 +154,8 @@ public HttpTransport create() { private GoogleCredentials sourceCredentials; private MockIAMCredentialsServiceTransportFactory mockTransportFactory; - @BeforeEach - void setup() throws IOException { + @Before + public void setup() throws IOException { sourceCredentials = getSourceCredentials(); mockTransportFactory = new MockIAMCredentialsServiceTransportFactory(); } @@ -174,8 +177,8 @@ private GoogleCredentials getSourceCredentials() throws IOException { return sourceCredentials; } - @Test - void fromJson_userAsSource_WithQuotaProjectId() throws IOException { + @Test() + public void fromJson_userAsSource_WithQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_URL, @@ -196,8 +199,8 @@ void fromJson_userAsSource_WithQuotaProjectId() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test - void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { + @Test() + public void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_URL, @@ -218,8 +221,8 @@ void fromJson_userAsSource_WithoutQuotaProjectId() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test - void fromJson_userAsSource_MissingDelegatesField() throws IOException { + @Test() + public void fromJson_userAsSource_MissingDelegatesField() throws IOException { GenericJson json = buildImpersonationCredentialsJson( IMPERSONATION_URL, @@ -241,8 +244,8 @@ void fromJson_userAsSource_MissingDelegatesField() throws IOException { assertTrue(sourceCredentials instanceof UserCredentials); } - @Test - void fromJson_ServiceAccountAsSource() throws IOException { + @Test() + public void fromJson_ServiceAccountAsSource() throws IOException { GenericJson json = buildImpersonationCredentialsJson(IMPERSONATION_URL, DELEGATES, QUOTA_PROJECT_ID); ImpersonatedCredentials credentials = @@ -257,19 +260,19 @@ void fromJson_ServiceAccountAsSource() throws IOException { assertTrue(sourceCredentials instanceof ServiceAccountCredentials); } - @Test - void fromJson_InvalidFormat() throws IOException { + @Test() + public void fromJson_InvalidFormat() throws IOException { GenericJson json = buildInvalidCredentialsJson(); - CredentialFormatException exception = - assertThrows( - CredentialFormatException.class, - () -> ImpersonatedCredentials.fromJson(json, mockTransportFactory), - "An exception should be thrown."); - assertEquals("An invalid input stream was provided.", exception.getMessage()); + try { + ImpersonatedCredentials.fromJson(json, mockTransportFactory); + fail("An exception should be thrown."); + } catch (CredentialFormatException e) { + assertEquals("An invalid input stream was provided.", e.getMessage()); + } } - @Test - void createScopedRequired_True() { + @Test() + public void createScopedRequired_True() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -281,8 +284,8 @@ void createScopedRequired_True() { assertTrue(targetCredentials.createScopedRequired()); } - @Test - void createScopedRequired_False() { + @Test() + public void createScopedRequired_False() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -295,7 +298,7 @@ void createScopedRequired_False() { } @Test - void createScoped() { + public void createScoped() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -318,7 +321,7 @@ void createScoped() { } @Test - void createScopedWithImmutableScopes() { + public void createScopedWithImmutableScopes() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -341,7 +344,7 @@ void createScopedWithImmutableScopes() { } @Test - void createScopedWithIamEndpointOverride() { + public void createScopedWithIamEndpointOverride() { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, @@ -360,7 +363,7 @@ void createScopedWithIamEndpointOverride() { } @Test - void refreshAccessToken_unauthorized() throws IOException { + public void refreshAccessToken_unauthorized() throws IOException { String expectedMessage = "The caller does not have permission"; mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -378,17 +381,17 @@ void refreshAccessToken_unauthorized() throws IOException { VALID_LIFETIME, mockTransportFactory); - IOException exception = - assertThrows( - IOException.class, - () -> targetCredentials.refreshAccessToken().getTokenValue(), - String.format("Should throw exception with message containing '%s'", expectedMessage)); - assertEquals("Error requesting access token", exception.getMessage()); - assertTrue(exception.getCause().getMessage().contains(expectedMessage)); + try { + targetCredentials.refreshAccessToken().getTokenValue(); + fail(String.format("Should throw exception with message containing '%s'", expectedMessage)); + } catch (IOException expected) { + assertEquals("Error requesting access token", expected.getMessage()); + assertTrue(expected.getCause().getMessage().contains(expectedMessage)); + } } - @Test - void refreshAccessToken_malformedTarget() throws IOException { + @Test() + public void refreshAccessToken_malformedTarget() throws IOException { String invalidTargetEmail = "foo"; String expectedMessage = "Request contains an invalid argument"; @@ -407,64 +410,62 @@ void refreshAccessToken_malformedTarget() throws IOException { VALID_LIFETIME, mockTransportFactory); - IOException exception = - assertThrows( - IOException.class, - () -> targetCredentials.refreshAccessToken().getTokenValue(), - String.format("Should throw exception with message containing '%s'", expectedMessage)); - assertEquals("Error requesting access token", exception.getMessage()); - assertTrue(exception.getCause().getMessage().contains(expectedMessage)); + try { + targetCredentials.refreshAccessToken().getTokenValue(); + fail(String.format("Should throw exception with message containing '%s'", expectedMessage)); + } catch (IOException expected) { + assertEquals("Error requesting access token", expected.getMessage()); + assertTrue(expected.getCause().getMessage().contains(expectedMessage)); + } } - @Test - void credential_with_zero_lifetime() throws IllegalStateException { + @Test() + public void credential_with_zero_lifetime() throws IllegalStateException { ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create( sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, IMMUTABLE_SCOPES_LIST, 0); assertEquals(3600, targetCredentials.getLifetime()); } - @Test - void credential_with_invalid_lifetime() throws IOException, IllegalStateException { - - IllegalStateException exception = - assertThrows( - IllegalStateException.class, - () -> { - ImpersonatedCredentials targetCredentials = - ImpersonatedCredentials.create( - sourceCredentials, - IMPERSONATED_CLIENT_EMAIL, - null, - IMMUTABLE_SCOPES_LIST, - INVALID_LIFETIME); - targetCredentials.refreshAccessToken().getTokenValue(); - }, - String.format( - "Should throw exception with message containing '%s'", - "lifetime must be less than or equal to 43200")); - assertTrue(exception.getMessage().contains("lifetime must be less than or equal to 43200")); + @Test() + public void credential_with_invalid_lifetime() throws IOException, IllegalStateException { + + try { + ImpersonatedCredentials targetCredentials = + ImpersonatedCredentials.create( + sourceCredentials, + IMPERSONATED_CLIENT_EMAIL, + null, + IMMUTABLE_SCOPES_LIST, + INVALID_LIFETIME); + targetCredentials.refreshAccessToken().getTokenValue(); + fail( + String.format( + "Should throw exception with message containing '%s'", + "lifetime must be less than or equal to 43200")); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage().contains("lifetime must be less than or equal to 43200")); + } } - @Test - void credential_with_invalid_scope() throws IOException, IllegalStateException { - - IllegalStateException exception = - assertThrows( - IllegalStateException.class, - () -> { - ImpersonatedCredentials targetCredentials = - ImpersonatedCredentials.create( - sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, null, VALID_LIFETIME); - targetCredentials.refreshAccessToken().getTokenValue(); - }, - String.format( - "Should throw exception with message containing '%s'", "Scopes cannot be null")); - assertTrue(exception.getMessage().contains("Scopes cannot be null")); + @Test() + public void credential_with_invalid_scope() throws IOException, IllegalStateException { + + try { + ImpersonatedCredentials targetCredentials = + ImpersonatedCredentials.create( + sourceCredentials, IMPERSONATED_CLIENT_EMAIL, null, null, VALID_LIFETIME); + targetCredentials.refreshAccessToken().getTokenValue(); + fail( + String.format( + "Should throw exception with message containing '%s'", "Scopes cannot be null")); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage().contains("Scopes cannot be null")); + } } - @Test - void refreshAccessToken_success() throws IOException, IllegalStateException { + @Test() + public void refreshAccessToken_success() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -483,7 +484,7 @@ void refreshAccessToken_success() throws IOException, IllegalStateException { } @Test - void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { + public void refreshAccessToken_endpointOverride() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -504,8 +505,8 @@ void refreshAccessToken_endpointOverride() throws IOException, IllegalStateExcep assertEquals(IMPERSONATION_URL, mockTransportFactory.transport.getRequest().getUrl()); } - @Test - void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { + @Test() + public void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -527,8 +528,8 @@ void getRequestMetadata_withQuotaProjectId() throws IOException, IllegalStateExc assertEquals(QUOTA_PROJECT_ID, headerValues.get(0)); } - @Test - void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { + @Test() + public void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -546,8 +547,8 @@ void getRequestMetadata_withoutQuotaProjectId() throws IOException, IllegalState assertFalse(metadata.containsKey("x-goog-user-project")); } - @Test - void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { + @Test() + public void refreshAccessToken_delegates_success() throws IOException, IllegalStateException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); @@ -566,7 +567,8 @@ void refreshAccessToken_delegates_success() throws IOException, IllegalStateExce } @Test - void refreshAccessToken_GMT_dateParsedCorrectly() throws IOException, IllegalStateException { + public void refreshAccessToken_GMT_dateParsedCorrectly() + throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -585,13 +587,14 @@ void refreshAccessToken_GMT_dateParsedCorrectly() throws IOException, IllegalSta // Set system timezone to GMT Calendar.getInstance(TimeZone.getTimeZone("GMT"))); - assertEquals( - c.getTime().toInstant().truncatedTo(ChronoUnit.SECONDS).toEpochMilli(), - targetCredentials.refreshAccessToken().getExpirationTimeMillis()); + assertTrue( + c.getTime().toInstant().truncatedTo(ChronoUnit.SECONDS).toEpochMilli() + == targetCredentials.refreshAccessToken().getExpirationTimeMillis()); } @Test - void refreshAccessToken_nonGMT_dateParsedCorrectly() throws IOException, IllegalStateException { + public void refreshAccessToken_nonGMT_dateParsedCorrectly() + throws IOException, IllegalStateException { Calendar c = Calendar.getInstance(); c.add(Calendar.SECOND, VALID_LIFETIME); @@ -610,13 +613,13 @@ void refreshAccessToken_nonGMT_dateParsedCorrectly() throws IOException, Illegal // Set system timezone to one different than GMT Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"))); - assertEquals( - c.getTime().toInstant().truncatedTo(ChronoUnit.SECONDS).toEpochMilli(), - targetCredentials.refreshAccessToken().getExpirationTimeMillis()); + assertTrue( + c.getTime().toInstant().truncatedTo(ChronoUnit.SECONDS).toEpochMilli() + == targetCredentials.refreshAccessToken().getExpirationTimeMillis()); } @Test - void refreshAccessToken_invalidDate() throws IllegalStateException { + public void refreshAccessToken_invalidDate() throws IllegalStateException { String expectedMessage = "Unparseable date"; mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); @@ -631,16 +634,16 @@ void refreshAccessToken_invalidDate() throws IllegalStateException { VALID_LIFETIME, mockTransportFactory); - IOException exception = - assertThrows( - IOException.class, - () -> targetCredentials.refreshAccessToken().getTokenValue(), - String.format("Should throw exception with message containing '%s'", expectedMessage)); - assertTrue(exception.getMessage().contains(expectedMessage)); + try { + targetCredentials.refreshAccessToken().getTokenValue(); + fail(String.format("Should throw exception with message containing '%s'", expectedMessage)); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedMessage)); + } } @Test - void getAccount_sameAs() { + public void getAccount_sameAs() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -657,7 +660,7 @@ void getAccount_sameAs() { } @Test - void sign_sameAs() { + public void sign_sameAs() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -679,7 +682,7 @@ void sign_sameAs() { } @Test - void sign_requestIncludesDelegates() throws IOException { + public void sign_requestIncludesDelegates() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -710,7 +713,7 @@ void sign_requestIncludesDelegates() throws IOException { } @Test - void sign_usesSourceCredentials() { + public void sign_usesSourceCredentials() { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date expiry = c.getTime(); @@ -743,7 +746,7 @@ void sign_usesSourceCredentials() { } @Test - void sign_accessDenied_throws() { + public void sign_accessDenied_throws() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -763,19 +766,19 @@ void sign_accessDenied_throws() { mockTransportFactory.transport.setErrorResponseCodeAndMessage( HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Sign Error"); - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - SigningException exception = - assertThrows( - SigningException.class, - () -> targetCredentials.sign(bytes), - "Signing should have failed"); - assertEquals("Failed to sign the provided bytes", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("403")); + try { + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + targetCredentials.sign(bytes); + fail("Signing should have failed"); + } catch (SigningException e) { + assertEquals("Failed to sign the provided bytes", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("403")); + } } @Test - void sign_serverError_throws() { + public void sign_serverError_throws() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -795,19 +798,19 @@ void sign_serverError_throws() { mockTransportFactory.transport.setErrorResponseCodeAndMessage( HttpStatusCodes.STATUS_CODE_SERVER_ERROR, "Sign Error"); - byte[] bytes = {0xD, 0xE, 0xA, 0xD}; - SigningException exception = - assertThrows( - SigningException.class, - () -> targetCredentials.sign(bytes), - "Signing should have failed"); - assertEquals("Failed to sign the provided bytes", exception.getMessage()); - assertNotNull(exception.getCause()); - assertTrue(exception.getCause().getMessage().contains("500")); + try { + byte[] bytes = {0xD, 0xE, 0xA, 0xD}; + targetCredentials.sign(bytes); + fail("Signing should have failed"); + } catch (SigningException e) { + assertEquals("Failed to sign the provided bytes", e.getMessage()); + assertNotNull(e.getCause()); + assertTrue(e.getCause().getMessage().contains("500")); + } } @Test - void idTokenWithAudience_sameAs() throws IOException { + public void idTokenWithAudience_sameAs() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -838,7 +841,7 @@ void idTokenWithAudience_sameAs() throws IOException { } @Test - void idTokenWithAudience_withEmail() throws IOException { + public void idTokenWithAudience_withEmail() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -868,7 +871,7 @@ void idTokenWithAudience_withEmail() throws IOException { } @Test - void idToken_withServerError() { + public void idToken_withServerError() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -892,13 +895,16 @@ void idToken_withServerError() { .setIdTokenProvider(targetCredentials) .setTargetAudience(targetAudience) .build(); - - IOException exception = assertThrows(IOException.class, tokenCredential::refresh); - assertTrue(exception.getMessage().contains("Error code 500 trying to getIDToken")); + try { + tokenCredential.refresh(); + fail("Should not be able to use credential without exception."); + } catch (IOException e) { + assertTrue(e.getMessage().contains("Error code 500 trying to getIDToken")); + } } @Test - void idToken_withOtherError() { + public void idToken_withOtherError() { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -922,13 +928,16 @@ void idToken_withOtherError() { .setIdTokenProvider(targetCredentials) .setTargetAudience(targetAudience) .build(); - - IOException exception = assertThrows(IOException.class, tokenCredential::refresh); - assertTrue(exception.getMessage().contains("Unexpected Error code 301 trying to getIDToken")); + try { + tokenCredential.refresh(); + fail("Should not be able to use credential without exception."); + } catch (IOException e) { + assertTrue(e.getMessage().contains("Unexpected Error code 301 trying to getIDToken")); + } } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); mockTransportFactory.transport.setExpireTime(getDefaultExpireTime()); @@ -955,7 +964,7 @@ void hashCode_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { mockTransportFactory.transport.setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL); mockTransportFactory.transport.setAccessToken(ACCESS_TOKEN); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java index 69e9684e4..dff076658 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/JwtClaimsTest.java @@ -31,19 +31,22 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +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 java.util.Collections; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class JwtClaimsTest { @Test - void testMergeOverwritesFields() { + public void testMergeOverwritesFields() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -64,7 +67,7 @@ void testMergeOverwritesFields() { } @Test - void testMergeDefaultValues() { + public void testMergeDefaultValues() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -80,7 +83,7 @@ void testMergeDefaultValues() { } @Test - void testMergeNull() { + public void testMergeNull() { JwtClaims claims1 = JwtClaims.newBuilder().build(); JwtClaims claims2 = JwtClaims.newBuilder().build(); JwtClaims merged = claims1.merge(claims2); @@ -93,7 +96,7 @@ void testMergeNull() { } @Test - void testEquals() { + public void testEquals() { JwtClaims claims1 = JwtClaims.newBuilder() .setAudience("audience-1") @@ -111,14 +114,14 @@ void testEquals() { } @Test - void testAdditionalClaimsDefaults() { + public void testAdditionalClaimsDefaults() { JwtClaims claims = JwtClaims.newBuilder().build(); assertNotNull(claims.getAdditionalClaims()); assertTrue(claims.getAdditionalClaims().isEmpty()); } @Test - void testMergeAdditionalClaims() { + public void testMergeAdditionalClaims() { JwtClaims claims1 = JwtClaims.newBuilder().setAdditionalClaims(Collections.singletonMap("foo", "bar")).build(); JwtClaims claims2 = @@ -138,7 +141,7 @@ void testMergeAdditionalClaims() { } @Test - void testIsComplete() { + public 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 7f65c0035..1c934a8f4 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; +import 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 com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; @@ -47,9 +47,12 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -class JwtCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class JwtCredentialsTest extends BaseSerializationTest { private static final String PRIVATE_KEY_ID = "d84a4fefcf50791d4a90f2d7af17469d6282df9d"; private static final String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" @@ -77,7 +80,7 @@ static PrivateKey getPrivateKey() { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -99,51 +102,51 @@ void serialize() throws IOException, ClassNotFoundException { } @Test - void builder_requiresPrivateKey() { - assertThrows( - NullPointerException.class, - () -> { - JwtClaims claims = - JwtClaims.newBuilder() - .setAudience("some-audience") - .setIssuer("some-issuer") - .setSubject("some-subject") - .build(); - JwtCredentials.newBuilder().setJwtClaims(claims).setPrivateKeyId(PRIVATE_KEY_ID).build(); - }, - "Should throw exception"); + public void builder_requiresPrivateKey() { + try { + JwtClaims claims = + JwtClaims.newBuilder() + .setAudience("some-audience") + .setIssuer("some-issuer") + .setSubject("some-subject") + .build(); + JwtCredentials.newBuilder().setJwtClaims(claims).setPrivateKeyId(PRIVATE_KEY_ID).build(); + fail("Should throw exception"); + } catch (NullPointerException ex) { + // expected + } } @Test - void builder_requiresClaims() { - assertThrows( - NullPointerException.class, - () -> { - JwtCredentials.newBuilder() - .setPrivateKeyId(PRIVATE_KEY_ID) - .setPrivateKey(getPrivateKey()) - .build(); - }, - "Should throw exception"); + public void builder_requiresClaims() { + try { + JwtCredentials.newBuilder() + .setPrivateKeyId(PRIVATE_KEY_ID) + .setPrivateKey(getPrivateKey()) + .build(); + fail("Should throw exception"); + } catch (NullPointerException ex) { + // expected + } } @Test - void builder_requiresCompleteClaims() { - assertThrows( - IllegalStateException.class, - () -> { - JwtClaims claims = JwtClaims.newBuilder().build(); - JwtCredentials.newBuilder() - .setJwtClaims(claims) - .setPrivateKeyId(PRIVATE_KEY_ID) - .setPrivateKey(getPrivateKey()) - .build(); - }, - "Should throw exception"); + public void builder_requiresCompleteClaims() { + try { + JwtClaims claims = JwtClaims.newBuilder().build(); + JwtCredentials.newBuilder() + .setJwtClaims(claims) + .setPrivateKeyId(PRIVATE_KEY_ID) + .setPrivateKey(getPrivateKey()) + .build(); + fail("Should throw exception"); + } catch (IllegalStateException ex) { + // expected + } } @Test - void jwtWithClaims_overwritesClaims() throws IOException { + public void jwtWithClaims_overwritesClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -168,7 +171,7 @@ void jwtWithClaims_overwritesClaims() throws IOException { } @Test - void jwtWithClaims_defaultsClaims() throws IOException { + public void jwtWithClaims_defaultsClaims() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -188,7 +191,7 @@ void jwtWithClaims_defaultsClaims() throws IOException { } @Test - void getRequestMetadata_hasJwtAccess() throws IOException { + public void getRequestMetadata_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -207,7 +210,7 @@ void getRequestMetadata_hasJwtAccess() throws IOException { } @Test - void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { + public void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -233,7 +236,7 @@ void getRequestMetadata_withAdditionalClaims_hasJwtAccess() throws IOException { } @Test - void privateKeyIdNull() throws IOException { + public void privateKeyIdNull() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -252,7 +255,7 @@ void privateKeyIdNull() throws IOException { } @Test - void privateKeyIdNotSpecified() throws IOException { + public void privateKeyIdNotSpecified() throws IOException { JwtClaims claims = JwtClaims.newBuilder() .setAudience("some-audience") @@ -279,7 +282,7 @@ private void verifyJwtAccess( expectedIssuer, expectedSubject, expectedKeyId, - Collections.emptyMap()); + Collections.emptyMap()); } private void verifyJwtAccess( @@ -292,15 +295,15 @@ private void verifyJwtAccess( throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull(authorizations, "Authorization headers not found"); + assertNotNull("Authorization headers not found", authorizations); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull(assertion, "Multiple bearer assertions found"); + assertNull("Multiple bearer assertions found", assertion); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull(assertion, "Bearer assertion not found"); + assertNotNull("Bearer assertion not found", assertion); 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/MockExecutor.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java index 3c425e345..ce36548e2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockExecutor.java @@ -36,7 +36,7 @@ /** Mock thread-less executor. */ public final class MockExecutor implements Executor { - private LinkedList tasks = new LinkedList<>(); + private LinkedList tasks = new LinkedList(); @Override public void execute(Runnable task) { @@ -45,7 +45,7 @@ public void execute(Runnable task) { int runTasks() { LinkedList savedTasks = tasks; - tasks = new LinkedList<>(); + tasks = new LinkedList(); for (Runnable task : savedTasks) { task.run(); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockExternalAccountCredentialsTransport.java index 1199ac1f7..96400dfe8 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.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/MockMetadataServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java index b3dd9ca89..07c5b0fb5 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockMetadataServerTransport.java @@ -166,7 +166,7 @@ public LowLevelHttpResponse execute() throws IOException { } // https://cloud.google.com/compute/docs/instances/verifying-instance-identity#token_format - Map queryPairs = new HashMap<>(); + Map queryPairs = new HashMap(); String query = (new URL(url)).getQuery(); String[] pairs = query.split("&"); for (String pair : pairs) { diff --git a/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockStsTransport.java index 527532170..1695c8450 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.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/MockTokenServerTransport.java b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java index 29c8e6337..add74834a 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/MockTokenServerTransport.java @@ -60,10 +60,10 @@ public class MockTokenServerTransport extends MockHttpTransport { static final String EXPECTED_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; static final JsonFactory JSON_FACTORY = new GsonFactory(); int buildRequestCount; - final Map clients = new HashMap<>(); - final Map refreshTokens = new HashMap<>(); - final Map serviceAccounts = new HashMap<>(); - final Map codes = new HashMap<>(); + final Map clients = new HashMap(); + final Map refreshTokens = new HashMap(); + final Map serviceAccounts = new HashMap(); + final Map codes = new HashMap(); URI tokenServerUri = OAuth2Utils.TOKEN_SERVER_URI; private IOException error; private final Queue> responseSequence = new ArrayDeque<>(); @@ -106,7 +106,7 @@ public void setError(IOException error) { public void addResponseErrorSequence(IOException... errors) { for (IOException error : errors) { - responseSequence.add(Futures.immediateFailedFuture(error)); + responseSequence.add(Futures.immediateFailedFuture(error)); } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java index 34add0b0c..733240985 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsTest.java @@ -32,13 +32,14 @@ package com.google.auth.oauth2; import static java.util.concurrent.TimeUnit.HOURS; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -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.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.util.Clock; import com.google.auth.TestClock; @@ -68,12 +69,16 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link OAuth2Credentials}. */ -class OAuth2CredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class OAuth2CredentialsTest extends BaseSerializationTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -83,25 +88,25 @@ class OAuth2CredentialsTest extends BaseSerializationTest { private ExecutorService realExecutor; - @BeforeEach - void setUp() { + @Before + public void setUp() { realExecutor = Executors.newCachedThreadPool(); } - @AfterEach - void tearDown() { + @After + public void tearDown() { realExecutor.shutdown(); } @Test - void constructor_storesAccessToken() { + public void constructor_storesAccessToken() { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); - assertEquals(ACCESS_TOKEN, credentials.getAccessToken().getTokenValue()); + assertEquals(credentials.getAccessToken().getTokenValue(), ACCESS_TOKEN); } @Test - void constructor_overrideMargin() throws Throwable { + public void constructor_overrideMargin() throws Throwable { Duration staleMargin = Duration.ofMinutes(3); Duration expirationMargin = Duration.ofMinutes(2); @@ -182,18 +187,18 @@ public AccessToken refreshAccessToken() throws IOException { } @Test - void getAuthenticationType_returnsOAuth2() { + public void getAuthenticationType_returnsOAuth2() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .build(); - assertEquals("OAuth2", credentials.getAuthenticationType()); + assertEquals(credentials.getAuthenticationType(), "OAuth2"); } @Test - void hasRequestMetadata_returnsTrue() { + public void hasRequestMetadata_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -204,7 +209,7 @@ void hasRequestMetadata_returnsTrue() { } @Test - void hasRequestMetadataOnly_returnsTrue() { + public void hasRequestMetadataOnly_returnsTrue() { OAuth2Credentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -215,7 +220,7 @@ void hasRequestMetadataOnly_returnsTrue() { } @Test - void addChangeListener_notifiesOnRefresh() throws IOException { + public void addChangeListener_notifiesOnRefresh() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -253,7 +258,7 @@ void addChangeListener_notifiesOnRefresh() throws IOException { } @Test - void removeChangeListener_unregisters_observer() throws IOException { + public void removeChangeListener_unregisters_observer() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -290,7 +295,7 @@ void removeChangeListener_unregisters_observer() throws IOException { } @Test - void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { + public void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -328,11 +333,13 @@ void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { clock.addToCurrentTime(60 * 60 * 1000); assertEquals(0, transportFactory.transport.buildRequestCount); - IOException exception = - assertThrows( - IOException.class, () -> credentials.getRequestMetadata(CALL_URI), "Should throw"); - assertSame(error, exception); - assertEquals(1, transportFactory.transport.buildRequestCount--); + try { + credentials.getRequestMetadata(CALL_URI); + fail("Should throw"); + } catch (IOException e) { + assertSame(error, e); + assertEquals(1, transportFactory.transport.buildRequestCount--); + } // Reset the error and try again transportFactory.transport.setError(null); @@ -342,7 +349,7 @@ void getRequestMetadata_blocking_cachesExpiringToken() throws IOException { } @Test - void getRequestMetadata_async() { + public void getRequestMetadata_async() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -412,7 +419,8 @@ void getRequestMetadata_async() { } @Test - void getRequestMetadata_async_refreshRace() throws ExecutionException, InterruptedException { + public void getRequestMetadata_async_refreshRace() + throws ExecutionException, InterruptedException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); @@ -470,7 +478,7 @@ public Map> call() throws Exception { } @Test - void getRequestMetadata_temporaryToken_hasToken() throws IOException { + public void getRequestMetadata_temporaryToken_hasToken() throws IOException { OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); @@ -480,7 +488,7 @@ void getRequestMetadata_temporaryToken_hasToken() throws IOException { } @Test - void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { + public void getRequestMetadata_staleTemporaryToken() throws IOException, InterruptedException { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); @@ -550,7 +558,7 @@ public AccessToken refreshAccessToken() { } @Test - void getRequestMetadata_staleTemporaryToken_expirationWaits() throws Throwable { + public 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); @@ -619,7 +627,7 @@ public AccessToken refreshAccessToken() { } @Test - void getRequestMetadata_singleFlightErrorSharing() { + public void getRequestMetadata_singleFlightErrorSharing() { Instant actualExpiration = Instant.now(); Instant clientStale = actualExpiration.minus(OAuth2Credentials.DEFAULT_REFRESH_MARGIN); Instant clientExpired = actualExpiration.minus(OAuth2Credentials.DEFAULT_EXPIRATION_MARGIN); @@ -663,17 +671,32 @@ public Map> call() throws Exception { // Get the error that getRequestMetadata(uri) created Throwable actualBlockingError = - assertThrows(ExecutionException.class, blockingCall::get).getCause(); + assertThrows( + ExecutionException.class, + new ThrowingRunnable() { + @Override + public void run() throws Throwable { + blockingCall.get(); + } + }) + .getCause(); assertEquals(error, actualBlockingError); RuntimeException actualAsyncError = - assertThrows(RuntimeException.class, callback1::awaitResult); + assertThrows( + RuntimeException.class, + new ThrowingRunnable() { + @Override + public void run() throws Throwable { + callback1.awaitResult(); + } + }); assertEquals(error, actualAsyncError); } @Test - void getRequestMetadata_syncErrorsIncludeCallingStackframe() { + public void getRequestMetadata_syncErrorsIncludeCallingStackframe() { final OAuth2Credentials creds = new OAuth2Credentials() { @Override @@ -689,6 +712,7 @@ public AccessToken refreshAccessToken() { AtomicReference actualError = new AtomicReference<>(); try { creds.getRequestMetadata(CALL_URI); + fail("Should not be able to use credential without exception."); } catch (Exception refreshError) { actualError.set(refreshError); } @@ -703,7 +727,7 @@ public AccessToken refreshAccessToken() { } @Test - void refresh_refreshesToken() throws IOException { + public void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -739,7 +763,7 @@ void refresh_refreshesToken() throws IOException { } @Test - void refreshIfExpired_refreshesToken() throws IOException { + public void refreshIfExpired_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -782,21 +806,15 @@ void refreshIfExpired_refreshesToken() throws IOException { assertEquals(1, transportFactory.transport.buildRequestCount--); } - @Test - void refresh_temporaryToken_throws() { - assertThrows( - IllegalStateException.class, - () -> { - OAuth2Credentials credentials = - OAuth2Credentials.newBuilder() - .setAccessToken(new AccessToken(ACCESS_TOKEN, null)) - .build(); - credentials.refresh(); - }); + @Test(expected = IllegalStateException.class) + public void refresh_temporaryToken_throws() throws IOException { + OAuth2Credentials credentials = + OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(ACCESS_TOKEN, null)).build(); + credentials.refresh(); } @Test - void equals_true() { + public void equals_true() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken1, null)).build(); @@ -807,7 +825,7 @@ void equals_true() { } @Test - void equals_false_accessToken() { + public void equals_false_accessToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = @@ -819,7 +837,7 @@ void equals_false_accessToken() { } @Test - void toString_containsFields() { + public void toString_containsFields() throws IOException { AccessToken accessToken = new AccessToken("1/MkSJoj1xsli0AccessToken_NKPY2", null); OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(accessToken).build(); @@ -834,7 +852,7 @@ void toString_containsFields() { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); @@ -844,7 +862,7 @@ void hashCode_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2"; OAuth2Credentials credentials = OAuth2Credentials.newBuilder().setAccessToken(new AccessToken(accessToken, null)).build(); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java index f9a41eec9..2acd41ed9 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -31,20 +31,23 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import java.io.IOException; import java.util.Date; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link OAuth2CredentialsWithRefresh}. */ -class OAuth2CredentialsWithRefreshTest { +@RunWith(JUnit4.class) +public class OAuth2CredentialsWithRefreshTest { private static final AccessToken ACCESS_TOKEN = new AccessToken("accessToken", new Date()); @Test - void builder() { + public void builder() { OAuth2CredentialsWithRefresh.OAuth2RefreshHandler refreshHandler = new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @Override @@ -63,7 +66,7 @@ public AccessToken refreshAccessToken() { } @Test - void builder_noAccessToken() { + public void builder_noAccessToken() { OAuth2CredentialsWithRefresh.newBuilder() .setRefreshHandler( new OAuth2CredentialsWithRefresh.OAuth2RefreshHandler() { @@ -76,27 +79,29 @@ public AccessToken refreshAccessToken() { } @Test - void builder_noRefreshHandler_throws() { - assertThrows( - NullPointerException.class, - () -> OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(), - "Should fail as a refresh handler must be provided."); + public void builder_noRefreshHandler_throws() { + try { + OAuth2CredentialsWithRefresh.newBuilder().setAccessToken(ACCESS_TOKEN).build(); + fail("Should fail as a refresh handler must be provided."); + } catch (NullPointerException e) { + // Expected. + } } @Test - void builder_noExpirationTimeInAccessToken_throws() { - assertThrows( - IllegalArgumentException.class, - () -> { - OAuth2CredentialsWithRefresh.newBuilder() - .setAccessToken(new AccessToken("accessToken", null)) - .build(); - }, - "Should fail as a refresh handler must be provided."); + public void builder_noExpirationTimeInAccessToken_throws() { + try { + OAuth2CredentialsWithRefresh.newBuilder() + .setAccessToken(new AccessToken("accessToken", null)) + .build(); + fail("Should fail as a refresh handler must be provided."); + } catch (IllegalArgumentException e) { + // Expected. + } } @Test - void refreshAccessToken_delegateToRefreshHandler() throws IOException { + public void refreshAccessToken_delegateToRefreshHandler() throws IOException { final AccessToken refreshedToken = new AccessToken("refreshedAccessToken", new Date()); OAuth2CredentialsWithRefresh credentials = OAuth2CredentialsWithRefresh.newBuilder() diff --git a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java index 67f3ba82b..f864f4791 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/OAuthExceptionTest.java @@ -31,20 +31,23 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link OAuthException}. */ -class OAuthExceptionTest { +@RunWith(JUnit4.class) +public 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 - void getMessage_fullFormat() { + public void getMessage_fullFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", "errorUri"); assertEquals("errorCode", e.getErrorCode()); @@ -57,7 +60,7 @@ void getMessage_fullFormat() { } @Test - void getMessage_descriptionFormat() { + public void getMessage_descriptionFormat() { OAuthException e = new OAuthException("errorCode", "errorDescription", /* errorUri= */ null); assertEquals("errorCode", e.getErrorCode()); @@ -70,7 +73,7 @@ void getMessage_descriptionFormat() { } @Test - void getMessage_baseFormat() { + public void getMessage_baseFormat() { OAuthException e = new OAuthException("errorCode", /* errorDescription= */ null, /* errorUri= */ null); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java index 01185bdb0..bddccd6e2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthCredentialsTest.java @@ -32,9 +32,9 @@ package com.google.auth.oauth2; import static com.google.auth.oauth2.MockExternalAccountCredentialsTransport.SERVICE_ACCOUNT_IMPERSONATION_URL; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.GenericJson; @@ -51,10 +51,10 @@ import java.util.List; import java.util.Map; import javax.annotation.Nullable; -import org.junit.jupiter.api.Test; +import org.junit.Test; /** Tests for {@link PluggableAuthCredentials}. */ -class PluggableAuthCredentialsTest { +public class PluggableAuthCredentialsTest { // 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). @@ -87,7 +87,7 @@ public HttpTransport create() { } @Test - void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { + public void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { PluggableAuthCredentials credential = PluggableAuthCredentials.newBuilder(CREDENTIAL) .setExecutableHandler(options -> "pluggableAuthToken") @@ -97,7 +97,7 @@ void retrieveSubjectToken_shouldDelegateToHandler() throws IOException { } @Test - void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { + public void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { String command = "/path/to/executable"; String timeout = "5000"; String outputFile = "/path/to/output/file"; @@ -140,7 +140,7 @@ void retrieveSubjectToken_shouldPassAllOptionsToHandler() throws IOException { } @Test - void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { + public void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException { String command = "/path/to/executable"; final ExecutableOptions[] providedOptions = {null}; @@ -179,7 +179,7 @@ void retrieveSubjectToken_shouldPassMinimalOptionsToHandler() throws IOException } @Test - void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -204,7 +204,7 @@ void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException } @Test - void refreshAccessToken_withServiceAccountImpersonation() throws IOException { + public void refreshAccessToken_withServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); @@ -232,7 +232,7 @@ void refreshAccessToken_withServiceAccountImpersonation() throws IOException { } @Test - void pluggableAuthCredentialSource_allFields() { + public void pluggableAuthCredentialSource_allFields() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -248,7 +248,7 @@ void pluggableAuthCredentialSource_allFields() { } @Test - void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { + public void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -261,7 +261,7 @@ void pluggableAuthCredentialSource_noTimeoutProvided_setToDefault() { } @Test - void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { + public void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -273,23 +273,21 @@ void pluggableAuthCredentialSource_timeoutProvidedOutOfRange_throws() { for (int value : possibleOutOfRangeValues) { executable.put("timeout_millis", value); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> { - new PluggableAuthCredentialSource(source); - }, - "Exception should be thrown."); - assertEquals( - String.format( - "The executable timeout must be between %s and %s milliseconds.", - MINIMUM_EXECUTABLE_TIMEOUT_MS, MAXIMUM_EXECUTABLE_TIMEOUT_MS), - exception.getMessage()); + try { + new PluggableAuthCredentialSource(source); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals( + String.format( + "The executable timeout must be between %s and %s milliseconds.", + MINIMUM_EXECUTABLE_TIMEOUT_MS, MAXIMUM_EXECUTABLE_TIMEOUT_MS), + exception.getMessage()); + } } } @Test - void pluggableAuthCredentialSource_validTimeoutProvided() { + public void pluggableAuthCredentialSource_validTimeoutProvided() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); @@ -309,34 +307,34 @@ void pluggableAuthCredentialSource_validTimeoutProvided() { } @Test - void pluggableAuthCredentialSource_missingExecutableField_throws() { - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new PluggableAuthCredentialSource(new HashMap<>()), - "Exception should be thrown."); - assertEquals( - "Invalid credential source for PluggableAuth credentials.", exception.getMessage()); + public void pluggableAuthCredentialSource_missingExecutableField_throws() { + try { + new PluggableAuthCredentialSource(new HashMap<>()); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals( + "Invalid credential source for PluggableAuth credentials.", exception.getMessage()); + } } @Test - void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { + public void pluggableAuthCredentialSource_missingExecutableCommandField_throws() { Map source = new HashMap<>(); Map executable = new HashMap<>(); source.put("executable", executable); - IllegalArgumentException exception = - assertThrows( - IllegalArgumentException.class, - () -> new PluggableAuthCredentialSource(source), - "Exception should be thrown."); - assertEquals( - "The PluggableAuthCredentialSource is missing the required 'command' field.", - exception.getMessage()); + try { + new PluggableAuthCredentialSource(source); + fail("Should not be able to continue without exception."); + } catch (IllegalArgumentException exception) { + assertEquals( + "The PluggableAuthCredentialSource is missing the required 'command' field.", + exception.getMessage()); + } } @Test - void builder_allFields() { + public void builder_allFields() { List scopes = Arrays.asList("scope1", "scope2"); CredentialSource source = buildCredentialSource(); @@ -375,7 +373,7 @@ void builder_allFields() { } @Test - void createdScoped_clonedCredentialWithAddedScopes() { + public void createdScoped_clonedCredentialWithAddedScopes() { PluggableAuthCredentials credentials = (PluggableAuthCredentials) PluggableAuthCredentials.newBuilder(CREDENTIAL) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java index f924d4137..bf4d0eea7 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/PluggableAuthExceptionTest.java @@ -31,39 +31,34 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; -import org.junit.jupiter.api.Test; +import org.junit.Test; /** Tests for {@link PluggableAuthException}. */ -class PluggableAuthExceptionTest { +public class PluggableAuthExceptionTest { private static final String MESSAGE_FORMAT = "Error code %s: %s"; @Test - void constructor() { + public void constructor() { PluggableAuthException e = new PluggableAuthException("errorCode", "errorDescription"); assertEquals("errorCode", e.getErrorCode()); assertEquals("errorDescription", e.getErrorDescription()); } - @Test - void constructor_nullErrorCode_throws() { - assertThrows( - NullPointerException.class, - () -> new PluggableAuthException(/* errorCode= */ null, "errorDescription")); + @Test(expected = NullPointerException.class) + public void constructor_nullErrorCode_throws() { + new PluggableAuthException(/* errorCode= */ null, "errorDescription"); } - @Test - void constructor_nullErrorDescription_throws() { - assertThrows( - NullPointerException.class, - () -> new PluggableAuthException("errorCode", /* errorDescription= */ null)); + @Test(expected = NullPointerException.class) + public void constructor_nullErrorDescription_throws() { + new PluggableAuthException("errorCode", /* errorDescription= */ null); } @Test - void getMessage() { + public 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 d751c403f..121a1186a 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.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.jupiter.api.Test; +import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; /** Tests for {@link PluggableAuthHandler}. */ @RunWith(MockitoJUnitRunner.class) -class PluggableAuthHandlerTest { +public 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 - void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { + public void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -144,7 +144,7 @@ void retrieveTokenFromExecutable_oidcResponse() throws IOException, InterruptedE } @Test - void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { + public void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -189,7 +189,8 @@ void retrieveTokenFromExecutable_samlResponse() throws IOException, InterruptedE } @Test - void retrieveTokenFromExecutable_errorResponse_throws() throws InterruptedException { + public void retrieveTokenFromExecutable_errorResponse_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -211,17 +212,17 @@ void retrieveTokenFromExecutable_errorResponse_throws() throws InterruptedExcept PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call retrieveTokenFromExecutable(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, - () -> handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS)); - - assertEquals("401", e.getErrorCode()); - assertEquals("Caller not authorized.", e.getErrorDescription()); + try { + handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("401", e.getErrorCode()); + assertEquals("Caller not authorized.", e.getErrorDescription()); + } } @Test - void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() + public void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -279,7 +280,7 @@ void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeField() } @Test - void + public void retrieveTokenFromExecutable_successResponseWithoutExpirationTimeFieldWithOutputFileSpecified_throws() throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); @@ -336,17 +337,16 @@ public String getOutputFilePath() { // Call retrieveTokenFromExecutable() should throw an exception as the STDOUT response // is missing // the `expiration_time` field and an output file was specified in the configuration. - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> handler.retrieveTokenFromExecutable(options), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain the " - + "`expiration_time` field for successful responses when an output_file has been specified in the" - + " configuration.", - exception.getMessage()); + try { + handler.retrieveTokenFromExecutable(options); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain the " + + "`expiration_time` field for successful responses when an output_file has been specified in the" + + " configuration.", + exception.getMessage()); + } verify(mockProcess, times(i + 1)).destroy(); verify(mockProcess, times(i + 1)) @@ -355,8 +355,9 @@ public String getOutputFilePath() { } @Test - void retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() - throws InterruptedException, IOException { + public void + retrieveTokenFromExecutable_successResponseInOutputFileMissingExpirationTimeField_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -411,17 +412,16 @@ public String getOutputFilePath() { // Call retrieveTokenFromExecutable() which should throw an exception as the output file // response is missing // the `expiration_time` field. - PluggableAuthException exception = - assertThrows( - PluggableAuthException.class, - () -> handler.retrieveTokenFromExecutable(options), - "Exception should be thrown."); - - assertEquals( - "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain the " - + "`expiration_time` field for successful responses when an output_file has been specified in the" - + " configuration.", - exception.getMessage()); + try { + handler.retrieveTokenFromExecutable(options); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException exception) { + assertEquals( + "Error code INVALID_EXECUTABLE_RESPONSE: The executable response must contain the " + + "`expiration_time` field for successful responses when an output_file has been specified in the" + + " configuration.", + exception.getMessage()); + } // Validate executable not invoked. verify(mockProcess, times(0)).destroyForcibly(); @@ -431,7 +431,7 @@ public String getOutputFilePath() { } @Test - void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() + public void retrieveTokenFromExecutable_withOutputFile_usesCachedResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -487,7 +487,7 @@ public String getOutputFilePath() { } @Test - void retrieveTokenFromExecutable_withInvalidOutputFile_throws() + public void retrieveTokenFromExecutable_withInvalidOutputFile_throws() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -532,15 +532,16 @@ public String getOutputFilePath() { PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call retrieveTokenFromExecutable(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, () -> handler.retrieveTokenFromExecutable(options)); - - assertEquals("INVALID_OUTPUT_FILE", e.getErrorCode()); + try { + handler.retrieveTokenFromExecutable(options); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("INVALID_OUTPUT_FILE", e.getErrorCode()); + } } @Test - void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() + public void retrieveTokenFromExecutable_expiredOutputFileResponse_callsExecutable() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -607,7 +608,8 @@ public String getOutputFilePath() { } @Test - void retrieveTokenFromExecutable_expiredResponse_throws() throws InterruptedException { + public void retrieveTokenFromExecutable_expiredResponse_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -629,17 +631,18 @@ void retrieveTokenFromExecutable_expiredResponse_throws() throws InterruptedExce PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call retrieveTokenFromExecutable(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, - () -> handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS)); - - assertEquals("INVALID_RESPONSE", e.getErrorCode()); - assertEquals("The executable response is expired.", e.getErrorDescription()); + try { + handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("INVALID_RESPONSE", e.getErrorCode()); + assertEquals("The executable response is expired.", e.getErrorDescription()); + } } @Test - void retrieveTokenFromExecutable_invalidVersion_throws() throws InterruptedException { + public void retrieveTokenFromExecutable_invalidVersion_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -662,21 +665,22 @@ void retrieveTokenFromExecutable_invalidVersion_throws() throws InterruptedExcep PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call retrieveTokenFromExecutable(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, - () -> handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS)); - - assertEquals("UNSUPPORTED_VERSION", e.getErrorCode()); - assertEquals( - "The version of the executable response is not supported. " - + String.format( - "The maximum version currently supported is %s.", EXECUTABLE_SUPPORTED_MAX_VERSION), - e.getErrorDescription()); + try { + handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("UNSUPPORTED_VERSION", e.getErrorCode()); + assertEquals( + "The version of the executable response is not supported. " + + String.format( + "The maximum version currently supported is %s.", + EXECUTABLE_SUPPORTED_MAX_VERSION), + e.getErrorDescription()); + } } @Test - void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() { + public 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(); @@ -684,20 +688,20 @@ void retrieveTokenFromExecutable_allowExecutablesDisabled_throws() { PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider); - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, - () -> handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS)); - - assertEquals("PLUGGABLE_AUTH_DISABLED", e.getErrorCode()); - assertEquals( - "Pluggable Auth executables need to be explicitly allowed to run by " - + "setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable to 1.", - e.getErrorDescription()); + try { + handler.retrieveTokenFromExecutable(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("PLUGGABLE_AUTH_DISABLED", e.getErrorCode()); + assertEquals( + "Pluggable Auth executables need to be explicitly allowed to run by " + + "setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable to 1.", + e.getErrorDescription()); + } } @Test - void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { + public void getExecutableResponse_oidcResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -737,15 +741,15 @@ void getExecutableResponse_oidcResponse() throws IOException, InterruptedExcepti assertTrue(response.isSuccessful()); assertEquals(TOKEN_TYPE_OIDC, response.getTokenType()); assertEquals(ID_TOKEN, response.getSubjectToken()); - assertEquals( - Instant.now().getEpochSecond() + EXPIRATION_DURATION, response.getExpirationTime()); + assertTrue( + Instant.now().getEpochSecond() + EXPIRATION_DURATION == response.getExpirationTime()); // Current env map should include the mappings from options. assertEquals(4, currentEnv.size()); assertEquals(expectedMap, currentEnv); } @Test - void getExecutableResponse_samlResponse() throws IOException, InterruptedException { + public void getExecutableResponse_samlResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -784,8 +788,8 @@ void getExecutableResponse_samlResponse() throws IOException, InterruptedExcepti assertTrue(response.isSuccessful()); assertEquals(TOKEN_TYPE_SAML, response.getTokenType()); assertEquals(SAML_RESPONSE, response.getSubjectToken()); - assertEquals( - Instant.now().getEpochSecond() + EXPIRATION_DURATION, response.getExpirationTime()); + assertTrue( + Instant.now().getEpochSecond() + EXPIRATION_DURATION == response.getExpirationTime()); // Current env map should include the mappings from options. assertEquals(4, currentEnv.size()); @@ -795,7 +799,7 @@ void getExecutableResponse_samlResponse() throws IOException, InterruptedExcepti } @Test - void getExecutableResponse_errorResponse() throws IOException, InterruptedException { + public void getExecutableResponse_errorResponse() throws IOException, InterruptedException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -843,7 +847,8 @@ void getExecutableResponse_errorResponse() throws IOException, InterruptedExcept } @Test - void getExecutableResponse_timeoutExceeded_throws() throws InterruptedException { + public void getExecutableResponse_timeoutExceeded_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -857,13 +862,15 @@ void getExecutableResponse_timeoutExceeded_throws() throws InterruptedException PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call getExecutableResponse(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, () -> handler.getExecutableResponse(DEFAULT_OPTIONS)); + try { + handler.getExecutableResponse(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("TIMEOUT_EXCEEDED", e.getErrorCode()); + assertEquals( + "The executable failed to finish within the timeout specified.", e.getErrorDescription()); + } - assertEquals("TIMEOUT_EXCEEDED", e.getErrorCode()); - assertEquals( - "The executable failed to finish within the timeout specified.", e.getErrorDescription()); verify(mockProcess, times(1)) .waitFor( eq(Long.valueOf(DEFAULT_OPTIONS.getExecutableTimeoutMs())), eq(TimeUnit.MILLISECONDS)); @@ -871,7 +878,8 @@ void getExecutableResponse_timeoutExceeded_throws() throws InterruptedException } @Test - void getExecutableResponse_nonZeroExitCode_throws() throws InterruptedException { + public void getExecutableResponse_nonZeroExitCode_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -887,14 +895,15 @@ void getExecutableResponse_nonZeroExitCode_throws() throws InterruptedException PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call getExecutableResponse(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, () -> handler.getExecutableResponse(DEFAULT_OPTIONS)); - - assertEquals("EXIT_CODE", e.getErrorCode()); - assertEquals( - String.format("The executable failed with exit code %s.", EXIT_CODE_FAIL), - e.getErrorDescription()); + try { + handler.getExecutableResponse(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("EXIT_CODE", e.getErrorCode()); + assertEquals( + String.format("The executable failed with exit code %s.", EXIT_CODE_FAIL), + e.getErrorDescription()); + } verify(mockProcess, times(1)) .waitFor( @@ -903,7 +912,8 @@ void getExecutableResponse_nonZeroExitCode_throws() throws InterruptedException } @Test - void getExecutableResponse_processInterrupted_throws() throws InterruptedException { + public void getExecutableResponse_processInterrupted_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -918,14 +928,15 @@ void getExecutableResponse_processInterrupted_throws() throws InterruptedExcepti PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call getExecutableResponse(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, () -> handler.getExecutableResponse(DEFAULT_OPTIONS)); - - assertEquals("INTERRUPTED", e.getErrorCode()); - assertEquals( - String.format("The execution was interrupted: %s.", new InterruptedException()), - e.getErrorDescription()); + try { + handler.getExecutableResponse(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("INTERRUPTED", e.getErrorCode()); + assertEquals( + String.format("The execution was interrupted: %s.", new InterruptedException()), + e.getErrorDescription()); + } verify(mockProcess, times(1)) .waitFor( @@ -934,7 +945,8 @@ void getExecutableResponse_processInterrupted_throws() throws InterruptedExcepti } @Test - void getExecutableResponse_invalidResponse_throws() throws InterruptedException { + public void getExecutableResponse_invalidResponse_throws() + throws InterruptedException, IOException { TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider(); environmentProvider.setEnv("GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "1"); @@ -955,14 +967,15 @@ void getExecutableResponse_invalidResponse_throws() throws InterruptedException PluggableAuthHandler handler = new PluggableAuthHandler(environmentProvider, processBuilder); // Call getExecutableResponse(). - PluggableAuthException e = - assertThrows( - PluggableAuthException.class, () -> handler.getExecutableResponse(DEFAULT_OPTIONS)); - - assertEquals("INVALID_RESPONSE", e.getErrorCode()); - assertEquals( - String.format("The executable returned an invalid response: %s.", badResponse), - e.getErrorDescription()); + try { + handler.getExecutableResponse(DEFAULT_OPTIONS); + fail("Should not be able to continue without exception."); + } catch (PluggableAuthException e) { + assertEquals("INVALID_RESPONSE", e.getErrorCode()); + assertEquals( + String.format("The executable returned an invalid response: %s.", badResponse), + e.getErrorDescription()); + } verify(mockProcess, times(1)) .waitFor( diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index b67ab40a4..e278b8648 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -31,17 +31,15 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; @@ -51,6 +49,7 @@ import com.google.api.client.testing.http.FixedClock; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Clock; +import com.google.api.client.util.Joiner; import com.google.auth.RequestMetadataCallback; import com.google.auth.TestUtils; import com.google.auth.http.AuthHttpConstants; @@ -75,10 +74,13 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link ServiceAccountCredentials}. */ -class ServiceAccountCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class ServiceAccountCredentialsTest extends BaseSerializationTest { private static final String CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -133,7 +135,7 @@ private ServiceAccountCredentials.Builder createDefaultBuilder() throws IOExcept } @Test - void setLifetime() throws IOException { + public void setLifetime() throws IOException { ServiceAccountCredentials.Builder builder = createDefaultBuilder(); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.getLifetime()); assertEquals(DEFAULT_LIFETIME_IN_SECONDS, builder.build().getLifetime()); @@ -147,27 +149,27 @@ void setLifetime() throws IOException { } @Test - void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { - IllegalStateException exception = - assertThrows( - IllegalStateException.class, - () -> createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(), - String.format( - "Should throw exception with message containing '%s'", - "lifetime must be less than or equal to 43200")); - - assertTrue(exception.getMessage().contains("lifetime must be less than or equal to 43200")); + public void setLifetime_invalid_lifetime() throws IOException, IllegalStateException { + try { + createDefaultBuilder().setLifetime(INVALID_LIFETIME).build(); + fail( + String.format( + "Should throw exception with message containing '%s'", + "lifetime must be less than or equal to 43200")); + } catch (IllegalStateException expected) { + assertTrue(expected.getMessage().contains("lifetime must be less than or equal to 43200")); + } } @Test - void createWithCustomLifetime() throws IOException { + public void createWithCustomLifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().build(); credentials = credentials.createWithCustomLifetime(4000); assertEquals(4000, credentials.getLifetime()); } @Test - void createdScoped_clones() throws IOException { + public void createdScoped_clones() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -197,7 +199,7 @@ void createdScoped_clones() throws IOException { } @Test - void createdDelegated_clones() throws IOException { + public void createdDelegated_clones() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -228,7 +230,7 @@ void createdDelegated_clones() throws IOException { } @Test - void createAssertion_correct() throws IOException { + public void createAssertion_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials credentials = @@ -253,11 +255,11 @@ void createAssertion_correct() throws IOException { assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(USER, payload.getSubject()); - assertEquals(String.join(" ", scopes), payload.get("scope")); + assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); } @Test - void createAssertion_defaultScopes_correct() throws IOException { + public void createAssertion_defaultScopes_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); List scopes = Arrays.asList("scope1", "scope2"); ServiceAccountCredentials.Builder builder = @@ -283,11 +285,11 @@ void createAssertion_defaultScopes_correct() throws IOException { assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds()); assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds()); assertEquals(USER, payload.getSubject()); - assertEquals(String.join(" ", scopes), payload.get("scope")); + assertEquals(Joiner.on(' ').join(scopes), payload.get("scope")); } @Test - void createAssertion_custom_lifetime() throws IOException { + public void createAssertion_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; @@ -300,7 +302,7 @@ void createAssertion_custom_lifetime() throws IOException { } @Test - void createAssertionForIdToken_correct() throws IOException { + public void createAssertionForIdToken_correct() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = @@ -329,7 +331,7 @@ void createAssertionForIdToken_correct() throws IOException { } @Test - void createAssertionForIdToken_custom_lifetime() throws IOException { + public void createAssertionForIdToken_custom_lifetime() throws IOException { ServiceAccountCredentials credentials = createDefaultBuilder().setLifetime(4000).build(); @@ -345,7 +347,7 @@ void createAssertionForIdToken_custom_lifetime() throws IOException { } @Test - void createAssertionForIdToken_incorrect() throws IOException { + public void createAssertionForIdToken_incorrect() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); ServiceAccountCredentials credentials = @@ -375,7 +377,7 @@ void createAssertionForIdToken_incorrect() throws IOException { } @Test - void createdScoped_enablesAccessTokens() throws IOException { + public void createdScoped_enablesAccessTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GoogleCredentials credentials = @@ -388,13 +390,14 @@ void createdScoped_enablesAccessTokens() throws IOException { transportFactory, null); - IOException exception = - assertThrows( - IOException.class, - () -> credentials.getRequestMetadata(null), - "Should not be able to get token without scopes"); - assertTrue( - exception.getMessage().contains("Scopes and uri are not configured for service account")); + try { + credentials.getRequestMetadata(null); + fail("Should not be able to get token without scopes"); + } catch (IOException e) { + assertTrue( + "expected to fail with exception", + e.getMessage().contains("Scopes and uri are not configured for service account")); + } GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES); Map> metadata = scopedCredentials.getRequestMetadata(CALL_URI); @@ -402,7 +405,7 @@ void createdScoped_enablesAccessTokens() throws IOException { } @Test - void createdScoped_defaultScopes() throws IOException { + public void createdScoped_defaultScopes() throws IOException { final URI TOKEN_SERVER = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -443,7 +446,7 @@ void createdScoped_defaultScopes() throws IOException { } @Test - void createScopedRequired_emptyScopes() throws IOException { + public void createScopedRequired_emptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, EMPTY_SCOPES); @@ -452,7 +455,7 @@ void createScopedRequired_emptyScopes() throws IOException { } @Test - void createScopedRequired_nonEmptyScopes() throws IOException { + public void createScopedRequired_nonEmptyScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, SCOPES); @@ -461,7 +464,7 @@ void createScopedRequired_nonEmptyScopes() throws IOException { } @Test - void createScopedRequired_nonEmptyDefaultScopes() throws IOException { + public void createScopedRequired_nonEmptyDefaultScopes() throws IOException { GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null, SCOPES); @@ -470,7 +473,7 @@ void createScopedRequired_nonEmptyDefaultScopes() throws IOException { } @Test - void fromJSON_getProjectId() throws IOException { + public void fromJSON_getProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -483,7 +486,7 @@ void fromJSON_getProjectId() throws IOException { } @Test - void fromJSON_getProjectIdNull() throws IOException { + public void fromJSON_getProjectIdNull() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -496,7 +499,7 @@ void fromJSON_getProjectIdNull() throws IOException { } @Test - void fromJSON_hasAccessToken() throws IOException { + public void fromJSON_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -511,7 +514,7 @@ void fromJSON_hasAccessToken() throws IOException { } @Test - void fromJSON_tokenServerUri() throws IOException { + public void fromJSON_tokenServerUri() throws IOException { final String tokenServerUri = "https://foo.com/bar"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -525,7 +528,7 @@ void fromJSON_tokenServerUri() throws IOException { } @Test - void fromJson_hasQuotaProjectId() throws IOException { + public void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); GenericJson json = @@ -542,7 +545,7 @@ void fromJson_hasQuotaProjectId() throws IOException { } @Test - void getRequestMetadata_hasAccessToken() throws IOException { + public void getRequestMetadata_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); OAuth2Credentials credentials = @@ -561,7 +564,7 @@ void getRequestMetadata_hasAccessToken() throws IOException { } @Test - void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + public 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); @@ -582,7 +585,7 @@ void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { } @Test - void refreshAccessToken_refreshesToken() throws IOException { + public void refreshAccessToken_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -606,7 +609,7 @@ void refreshAccessToken_refreshesToken() throws IOException { } @Test - void refreshAccessToken_tokenExpiry() throws IOException { + public void refreshAccessToken_tokenExpiry() throws IOException { final String tokenString = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -633,8 +636,8 @@ void refreshAccessToken_tokenExpiry() throws IOException { assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); } - @Test - void refreshAccessToken_IOException_NoRetry() throws IOException { + @Test(expected = IOException.class) + public void refreshAccessToken_IOException_NoRetry() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -652,18 +655,13 @@ void refreshAccessToken_IOException_NoRetry() throws IOException { transport.addServiceAccount(CLIENT_EMAIL, accessToken1); TestUtils.assertContainsBearerToken(credentials.getRequestMetadata(CALL_URI), accessToken1); - assertThrows( - IOException.class, - () -> { - transport.addResponseErrorSequence(new IOException()); - transport.addServiceAccount(CLIENT_EMAIL, accessToken2); - credentials.refresh(); - }, - "Should not retry on IOException"); + transport.addResponseErrorSequence(new IOException()); + transport.addServiceAccount(CLIENT_EMAIL, accessToken2); + credentials.refresh(); } @Test - void refreshAccessToken_retriesServerErrors() throws IOException { + public void refreshAccessToken_retriesServerErrors() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -690,7 +688,7 @@ void refreshAccessToken_retriesServerErrors() throws IOException { } @Test - void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { + public void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -717,7 +715,7 @@ void refreshAccessToken_retriesTimeoutAndThrottled() throws IOException { } @Test - void refreshAccessToken_defaultRetriesDisabled() throws IOException { + public void refreshAccessToken_defaultRetriesDisabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -739,22 +737,20 @@ void refreshAccessToken_defaultRetriesDisabled() throws IOException { MockLowLevelHttpResponse response408 = new MockLowLevelHttpResponse().setStatusCode(408); MockLowLevelHttpResponse response429 = new MockLowLevelHttpResponse().setStatusCode(429); transport.addServiceAccount(CLIENT_EMAIL, accessToken2); - GoogleAuthException ex = - assertThrows( - GoogleAuthException.class, - () -> { - transport.addResponseSequence(response408, response429); - credentials.refresh(); - }, - "Should not retry"); - assertTrue(ex.getMessage().contains("Error getting access token for service account: 408")); - assertTrue(ex.isRetryable()); - assertEquals(0, ex.getRetryCount()); + try { + transport.addResponseSequence(response408, response429); + credentials.refresh(); + fail("Should not be able to use credential without exception."); + } catch (GoogleAuthException ex) { + assertTrue(ex.getMessage().contains("Error getting access token for service account: 408")); + assertTrue(ex.isRetryable()); + assertEquals(0, ex.getRetryCount()); + } } @Test - void refreshAccessToken_maxRetries_maxDelay() throws IOException { + public void refreshAccessToken_maxRetries_maxDelay() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -778,26 +774,24 @@ void refreshAccessToken_maxRetries_maxDelay() throws IOException { MockLowLevelHttpResponse response503 = new MockLowLevelHttpResponse().setStatusCode(503); Instant start = Instant.now(); - GoogleAuthException ex = - assertThrows( - GoogleAuthException.class, - () -> { - transport.addResponseSequence(response408, response429, response500, response503); - credentials.refresh(); - }, - "Should retry only three times"); - Instant finish = Instant.now(); - long timeElapsed = Duration.between(start, finish).toMillis(); - - // we expect max retry time of 7 sec +/- jitter - assertTrue(timeElapsed > 5500 && timeElapsed < 10000); - assertTrue(ex.getMessage().contains("Error getting access token for service account: 503")); - assertTrue(ex.isRetryable()); - assertEquals(3, ex.getRetryCount()); - } - - @Test - void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + try { + transport.addResponseSequence(response408, response429, response500, response503); + credentials.refresh(); + fail("Should not be able to use credential without exception."); + } catch (GoogleAuthException ex) { + Instant finish = Instant.now(); + long timeElapsed = Duration.between(start, finish).toMillis(); + + // we expect max retry time of 7 sec +/- jitter + assertTrue(timeElapsed > 5500 && timeElapsed < 10000); + assertTrue(ex.getMessage().contains("Error getting access token for service account: 503")); + assertTrue(ex.isRetryable()); + assertEquals(3, ex.getRetryCount()); + } + } + + @Test + public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -821,22 +815,20 @@ void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { } MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse().setStatusCode(status); - GoogleAuthException ex = - assertThrows( - GoogleAuthException.class, - () -> { - transport.addResponseSequence(mockResponse); - transport.addServiceAccount(CLIENT_EMAIL, accessToken2); - credentials.refresh(); - }, - "Should not retry status " + status); - assertFalse(ex.isRetryable()); - assertEquals(0, ex.getRetryCount()); + try { + transport.addResponseSequence(mockResponse); + transport.addServiceAccount(CLIENT_EMAIL, accessToken2); + credentials.refresh(); + fail("Should not be able to use credential without exception."); + } catch (GoogleAuthException ex) { + assertFalse(ex.isRetryable()); + assertEquals(0, ex.getRetryCount()); + } } } @Test - void idTokenWithAudience_correct() throws IOException { + public void idTokenWithAudience_correct() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -868,7 +860,7 @@ void idTokenWithAudience_correct() throws IOException { } @Test - void idTokenWithAudience_incorrect() throws IOException { + public void idTokenWithAudience_incorrect() throws IOException { String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; @@ -898,7 +890,7 @@ void idTokenWithAudience_incorrect() throws IOException { } @Test - void getScopes_nullReturnsEmpty() throws IOException { + public void getScopes_nullReturnsEmpty() throws IOException { ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null); @@ -910,7 +902,7 @@ void getScopes_nullReturnsEmpty() throws IOException { } @Test - void getAccount_sameAs() throws IOException { + public void getAccount_sameAs() throws IOException { ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8( CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, null); @@ -918,7 +910,7 @@ void getAccount_sameAs() throws IOException { } @Test - void sign_sameAs() + public void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { byte[] toSign = {0xD, 0xE, 0xA, 0xD}; ServiceAccountCredentials credentials = @@ -932,7 +924,7 @@ void sign_sameAs() } @Test - void equals_true() throws IOException { + public void equals_true() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -958,7 +950,7 @@ void equals_true() throws IOException { } @Test - void equals_false_clientId() throws IOException { + public void equals_false_clientId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -984,7 +976,7 @@ void equals_false_clientId() throws IOException { } @Test - void equals_false_email() throws IOException { + public void equals_false_email() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1010,7 +1002,7 @@ void equals_false_email() throws IOException { } @Test - void equals_false_keyId() throws IOException { + public void equals_false_keyId() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1036,7 +1028,7 @@ void equals_false_keyId() throws IOException { } @Test - void equals_false_scopes() throws IOException { + public void equals_false_scopes() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1054,7 +1046,7 @@ void equals_false_scopes() throws IOException { CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, - ImmutableSet.of(), + ImmutableSet.of(), serverTransportFactory, tokenServer1); assertFalse(credentials.equals(otherCredentials)); @@ -1062,7 +1054,7 @@ void equals_false_scopes() throws IOException { } @Test - void equals_false_transportFactory() throws IOException { + public void equals_false_transportFactory() throws IOException { final URI tokenServer1 = URI.create("https://foo1.com/bar"); MockHttpTransportFactory httpTransportFactory = new MockHttpTransportFactory(); MockTokenServerTransportFactory serverTransportFactory = new MockTokenServerTransportFactory(); @@ -1089,7 +1081,7 @@ void equals_false_transportFactory() throws IOException { } @Test - void equals_false_tokenServer() throws IOException { + public 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(); @@ -1116,7 +1108,7 @@ void equals_false_tokenServer() throws IOException { } @Test - void toString_containsFields() throws IOException { + public void toString_containsFields() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1150,7 +1142,7 @@ void toString_containsFields() throws IOException { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); OAuth2Credentials credentials = @@ -1175,7 +1167,7 @@ void hashCode_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { final URI tokenServer = URI.create("https://foo.com/bar"); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); ServiceAccountCredentials credentials = @@ -1198,25 +1190,29 @@ void serialize() throws IOException, ClassNotFoundException { } @Test - void fromStream_nullTransport_throws() throws IOException { + public void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); - assertThrows( - NullPointerException.class, - () -> ServiceAccountCredentials.fromStream(stream, null), - "Should throw if HttpTransportFactory is null"); + try { + ServiceAccountCredentials.fromStream(stream, null); + fail("Should throw if HttpTransportFactory is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_nullStream_throws() throws IOException { + public void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - assertThrows( - NullPointerException.class, - () -> ServiceAccountCredentials.fromStream(null, transportFactory), - "Should throw if InputStream is null"); + try { + ServiceAccountCredentials.fromStream(null, transportFactory); + fail("Should throw if InputStream is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_providesToken() throws IOException { + public void fromStream_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = @@ -1232,7 +1228,7 @@ void fromStream_providesToken() throws IOException { } @Test - void fromStream_noClientId_throws() throws IOException { + public void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(null, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); @@ -1240,7 +1236,7 @@ void fromStream_noClientId_throws() throws IOException { } @Test - void fromStream_noClientEmail_throws() throws IOException { + public void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, null, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID); @@ -1248,7 +1244,7 @@ void fromStream_noClientEmail_throws() throws IOException { } @Test - void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { + public void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); MockTokenServerTransport transport = transportFactory.transport; transport.setError(new IOException("Invalid grant: Account not found")); @@ -1271,12 +1267,16 @@ void getIdTokenWithAudience_badEmailError_issClaimTraced() throws IOException { String expectedErrorMessage = String.format("iss: %s", CLIENT_EMAIL); - IOException exception = assertThrows(IOException.class, tokenCredential::refresh); - assertTrue(exception.getMessage().contains(expectedErrorMessage)); + try { + tokenCredential.refresh(); + fail("Should not be able to use credential without exception."); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedErrorMessage)); + } } @Test - void fromStream_noPrivateKey_throws() throws IOException { + public void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, null, PRIVATE_KEY_ID); @@ -1284,7 +1284,7 @@ void fromStream_noPrivateKey_throws() throws IOException { } @Test - void fromStream_noPrivateKeyId_throws() throws IOException { + public void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = writeServiceAccountStream(CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, null); @@ -1292,7 +1292,7 @@ void fromStream_noPrivateKeyId_throws() throws IOException { } @Test - void getUriForSelfSignedJWT() { + public void getUriForSelfSignedJWT() { assertNull(ServiceAccountCredentials.getUriForSelfSignedJWT(null)); URI uri = URI.create("https://compute.googleapis.com/compute/v1/projects/"); @@ -1301,21 +1301,21 @@ void getUriForSelfSignedJWT() { } @Test - void getUriForSelfSignedJWT_noHost() { + public void getUriForSelfSignedJWT_noHost() { URI uri = URI.create("file:foo"); URI expected = URI.create("file:foo"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } @Test - void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { + public void getUriForSelfSignedJWT_forStaticAudience_returnsURI() { URI uri = URI.create("compute.googleapis.com"); URI expected = URI.create("compute.googleapis.com"); assertEquals(expected, ServiceAccountCredentials.getUriForSelfSignedJWT(uri)); } @Test - void getRequestMetadataSetsQuotaProjectId() throws IOException { + public void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1334,7 +1334,7 @@ void getRequestMetadataSetsQuotaProjectId() throws IOException { .setHttpTransportFactory(transportFactory) .build(); - Map> metadata = credentials.getRequestMetadata(); + Map> metadata = credentials.getRequestMetadata(CALL_URI); assertTrue(metadata.containsKey("x-goog-user-project")); List headerValues = metadata.get("x-goog-user-project"); assertEquals(1, headerValues.size()); @@ -1342,7 +1342,7 @@ void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - void getRequestMetadataNoQuotaProjectId() throws IOException { + public void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1360,12 +1360,12 @@ void getRequestMetadataNoQuotaProjectId() throws IOException { .setHttpTransportFactory(transportFactory) .build(); - Map> metadata = credentials.getRequestMetadata(); + Map> metadata = credentials.getRequestMetadata(CALL_URI); assertFalse(metadata.containsKey("x-goog-user-project")); } @Test - void getRequestMetadataWithCallback() throws IOException { + public void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, "unused-client-secret"); transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); @@ -1402,11 +1402,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue(success.get(), "Should have run onSuccess() callback"); + assertTrue("Should have run onSuccess() callback", success.get()); } @Test - void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { + public void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1425,7 +1425,7 @@ void getRequestMetadata_selfSignedJWT_withScopes() throws IOException { } @Test - void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { + public void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -1448,10 +1448,12 @@ void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOE Map> metadata = credentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, accessToken1); - assertThrows( - Exception.class, - () -> verifyJwtAccess(metadata, "dummy.scope"), - "jwt access should fail with ServiceAccountUser"); + try { + verifyJwtAccess(metadata, "dummy.scope"); + fail("jwt access should fail with ServiceAccountUser"); + } catch (Exception ex) { + // expected + } transport.addServiceAccount(CLIENT_EMAIL, accessToken2); credentials.refresh(); @@ -1459,7 +1461,7 @@ void refreshAccessToken_withDomainDelegation_selfSignedJWT_disabled() throws IOE } @Test - void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { + public void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1476,7 +1478,7 @@ void getRequestMetadata_selfSignedJWT_withAudience() throws IOException { } @Test - void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOException { + public void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1495,7 +1497,7 @@ void getRequestMetadata_selfSignedJWT_withDefaultScopes() throws IOException { } @Test - void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { + public void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(PRIVATE_KEY_PKCS8); GoogleCredentials credentials = ServiceAccountCredentials.newBuilder() @@ -1517,8 +1519,11 @@ void getRequestMetadataWithCallback_selfSignedJWT() throws IOException { new RequestMetadataCallback() { @Override public void onSuccess(Map> metadata) { - assertDoesNotThrow( - () -> verifyJwtAccess(metadata, "dummy.scope"), "Should not throw a failure"); + try { + verifyJwtAccess(metadata, "dummy.scope"); + } catch (IOException e) { + fail("Should not throw a failure"); + } success.set(true); } @@ -1528,22 +1533,22 @@ public void onFailure(Throwable exception) { } }); - assertTrue(success.get(), "Should have run onSuccess() callback"); + assertTrue("Should have run onSuccess() callback", success.get()); } private void verifyJwtAccess(Map> metadata, String expectedScopeClaim) throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull(authorizations, "Authorization headers not found"); + assertNotNull("Authorization headers not found", authorizations); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull(assertion, "Multiple bearer assertions found"); + assertNull("Multiple bearer assertions found", assertion); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull(assertion, "Bearer assertion not found"); + assertNotNull("Bearer assertion not found", assertion); JsonWebSignature signature = JsonWebSignature.parse(GsonFactory.getDefaultInstance(), assertion); assertEquals(CLIENT_EMAIL, signature.getPayload().getIssuer()); @@ -1597,12 +1602,13 @@ static InputStream writeServiceAccountStream( } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - IOException exception = - assertThrows( - IOException.class, - () -> ServiceAccountCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY), - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - assertTrue(exception.getMessage().contains(expectedMessageContent)); + try { + ServiceAccountCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY); + fail( + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedMessageContent)); + } } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index 3a0249142..5020317f2 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -31,16 +31,15 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; @@ -64,10 +63,13 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link ServiceAccountCredentials}. */ -class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { private static final String SA_CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; @@ -94,7 +96,7 @@ class ServiceAccountJwtAccessCredentialsTest extends BaseSerializationTest { private static final String QUOTA_PROJECT = "sample-quota-project-id"; @Test - void constructor_allParameters_constructs() throws IOException { + public void constructor_allParameters_constructs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -113,7 +115,7 @@ void constructor_allParameters_constructs() throws IOException { } @Test - void constructor_noClientId_constructs() throws IOException { + public void constructor_noClientId_constructs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientEmail(SA_CLIENT_EMAIL) @@ -123,7 +125,7 @@ void constructor_noClientId_constructs() throws IOException { } @Test - void constructor_noPrivateKeyId_constructs() throws IOException { + public void constructor_noPrivateKeyId_constructs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) @@ -133,36 +135,36 @@ void constructor_noPrivateKeyId_constructs() throws IOException { } @Test - void constructor_noEmail_throws() throws IOException { + public void constructor_noEmail_throws() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); - assertThrows( - NullPointerException.class, - () -> { - ServiceAccountJwtAccessCredentials.newBuilder() - .setClientId(SA_CLIENT_ID) - .setPrivateKey(privateKey) - .setPrivateKeyId(SA_PRIVATE_KEY_ID) - .build(); - }, - "exception expected"); - } - - @Test - void constructor_noPrivateKey_throws() { - assertThrows( - NullPointerException.class, - () -> { - ServiceAccountJwtAccessCredentials.newBuilder() - .setClientId(SA_CLIENT_ID) - .setClientEmail(SA_CLIENT_EMAIL) - .setPrivateKeyId(SA_PRIVATE_KEY_ID) - .build(); - }, - "exception expected"); - } - - @Test - void getAuthenticationType_returnsJwtAccess() throws IOException { + try { + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .build(); + fail("exception expected"); + } catch (NullPointerException e) { + // Expected + } + } + + @Test + public void constructor_noPrivateKey_throws() { + try { + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .build(); + fail("exception expected"); + } catch (NullPointerException e) { + // Expected + } + } + + @Test + public void getAuthenticationType_returnsJwtAccess() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -170,7 +172,7 @@ void getAuthenticationType_returnsJwtAccess() throws IOException { } @Test - void hasRequestMetadata_returnsTrue() throws IOException { + public void hasRequestMetadata_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -178,7 +180,7 @@ void hasRequestMetadata_returnsTrue() throws IOException { } @Test - void hasRequestMetadataOnly_returnsTrue() throws IOException { + public void hasRequestMetadataOnly_returnsTrue() throws IOException { Credentials credentials = ServiceAccountJwtAccessCredentials.fromPkcs8( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -186,7 +188,7 @@ void hasRequestMetadataOnly_returnsTrue() throws IOException { } @Test - void getRequestMetadata_blocking_hasJwtAccess() throws IOException { + public void getRequestMetadata_blocking_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -202,7 +204,7 @@ void getRequestMetadata_blocking_hasJwtAccess() throws IOException { } @Test - void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { + public void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -219,7 +221,7 @@ void getRequestMetadata_blocking_defaultURI_hasJwtAccess() throws IOException { } @Test - void getRequestMetadata_blocking_noURI_throws() throws IOException { + public void getRequestMetadata_blocking_noURI_throws() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -229,11 +231,16 @@ void getRequestMetadata_blocking_noURI_throws() throws IOException { .setPrivateKeyId(SA_PRIVATE_KEY_ID) .build(); - assertThrows(IOException.class, credentials::getRequestMetadata, "exception expected"); + try { + credentials.getRequestMetadata(); + fail("exception expected"); + } catch (IOException e) { + // Expected + } } @Test - void getRequestMetadata_blocking_cached() throws IOException { + public void getRequestMetadata_blocking_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -258,7 +265,7 @@ void getRequestMetadata_blocking_cached() throws IOException { } @Test - void getRequestMetadata_blocking_cache_expired() throws IOException { + public void getRequestMetadata_blocking_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -283,7 +290,7 @@ void getRequestMetadata_blocking_cache_expired() throws IOException { } @Test - void getRequestMetadata_async_hasJwtAccess() throws IOException { + public void getRequestMetadata_async_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -302,7 +309,7 @@ void getRequestMetadata_async_hasJwtAccess() throws IOException { } @Test - void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { + public void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -322,7 +329,7 @@ void getRequestMetadata_async_defaultURI_hasJwtAccess() throws IOException { } @Test - void getRequestMetadata_async_noURI_exception() throws IOException { + public void getRequestMetadata_async_noURI_exception() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -340,7 +347,7 @@ void getRequestMetadata_async_noURI_exception() throws IOException { } @Test - void getRequestMetadata_async_cache_expired() throws IOException { + public void getRequestMetadata_async_cache_expired() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -368,7 +375,7 @@ void getRequestMetadata_async_cache_expired() throws IOException { } @Test - void getRequestMetadata_async_cached() throws IOException { + public void getRequestMetadata_async_cached() throws IOException { TestClock testClock = new TestClock(); PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -396,7 +403,7 @@ void getRequestMetadata_async_cached() throws IOException { } @Test - void getRequestMetadata_contains_quotaProjectId() throws IOException { + public void getRequestMetadata_contains_quotaProjectId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); Credentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -416,7 +423,7 @@ void getRequestMetadata_contains_quotaProjectId() throws IOException { } @Test - void getAccount_sameAs() throws IOException { + public void getAccount_sameAs() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -429,7 +436,7 @@ void getAccount_sameAs() throws IOException { } @Test - void sign_sameAs() + public void sign_sameAs() throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); byte[] toSign = {0xD, 0xE, 0xA, 0xD}; @@ -448,7 +455,7 @@ void sign_sameAs() } @Test - void equals_true() throws IOException { + public void equals_true() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -471,7 +478,7 @@ void equals_true() throws IOException { } @Test - void equals_false_clientId() throws IOException { + public void equals_false_clientId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -494,7 +501,7 @@ void equals_false_clientId() throws IOException { } @Test - void equals_false_email() throws IOException { + public void equals_false_email() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -517,7 +524,7 @@ void equals_false_email() throws IOException { } @Test - void equals_false_keyId() throws IOException { + public void equals_false_keyId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -540,7 +547,7 @@ void equals_false_keyId() throws IOException { } @Test - void equals_false_callUri() throws IOException { + public void equals_false_callUri() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); final URI otherCallUri = URI.create("https://foo.com/bar"); ServiceAccountJwtAccessCredentials credentials = @@ -564,7 +571,7 @@ void equals_false_callUri() throws IOException { } @Test - void toString_containsFields() throws IOException { + public void toString_containsFields() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -584,7 +591,7 @@ void toString_containsFields() throws IOException { } @Test - void hashCode_equals() throws IOException { + public void hashCode_equals() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -606,7 +613,7 @@ void hashCode_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public void serialize() throws IOException, ClassNotFoundException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -627,16 +634,18 @@ void serialize() throws IOException, ClassNotFoundException { } @Test - void fromStream_nullStream_throws() throws IOException { + public void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - assertThrows( - NullPointerException.class, - () -> ServiceAccountCredentials.fromStream(null, transportFactory), - "Should throw if InputStream is null"); + try { + ServiceAccountCredentials.fromStream(null, transportFactory); + fail("Should throw if InputStream is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_hasJwtAccess() throws IOException { + public void fromStream_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -649,7 +658,7 @@ void fromStream_hasJwtAccess() throws IOException { } @Test - void fromStream_defaultURI_hasJwtAccess() throws IOException { + public void fromStream_defaultURI_hasJwtAccess() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -663,7 +672,7 @@ void fromStream_defaultURI_hasJwtAccess() throws IOException { } @Test - void fromStream_noClientId_throws() throws IOException { + public void fromStream_noClientId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( null, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -672,7 +681,7 @@ void fromStream_noClientId_throws() throws IOException { } @Test - void fromStream_noClientEmail_throws() throws IOException { + public void fromStream_noClientEmail_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, null, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); @@ -681,7 +690,7 @@ void fromStream_noClientEmail_throws() throws IOException { } @Test - void fromStream_noPrivateKey_throws() throws IOException { + public void fromStream_noPrivateKey_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, null, SA_PRIVATE_KEY_ID); @@ -690,7 +699,7 @@ void fromStream_noPrivateKey_throws() throws IOException { } @Test - void fromStream_noPrivateKeyId_throws() throws IOException { + public void fromStream_noPrivateKeyId_throws() throws IOException { InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, null); @@ -699,7 +708,7 @@ void fromStream_noPrivateKeyId_throws() throws IOException { } @Test - void jwtWithClaims_overrideAudience() throws IOException { + public void jwtWithClaims_overrideAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -717,7 +726,7 @@ void jwtWithClaims_overrideAudience() throws IOException { } @Test - void jwtWithClaims_noAudience() throws IOException { + public void jwtWithClaims_noAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -726,14 +735,16 @@ void jwtWithClaims_noAudience() throws IOException { .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .build(); - assertThrows( - IllegalStateException.class, - () -> credentials.jwtWithClaims(JwtClaims.newBuilder().build()), - "Expected to throw exception for missing audience"); + try { + credentials.jwtWithClaims(JwtClaims.newBuilder().build()); + fail("Expected to throw exception for missing audience"); + } catch (IllegalStateException ex) { + // expected exception + } } @Test - void jwtWithClaims_defaultAudience() throws IOException { + public void jwtWithClaims_defaultAudience() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -750,7 +761,7 @@ void jwtWithClaims_defaultAudience() throws IOException { } @Test - void getRequestMetadataSetsQuotaProjectId() throws IOException { + public void getRequestMetadataSetsQuotaProjectId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -770,7 +781,7 @@ void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - void getRequestMetadataNoQuotaProjectId() throws IOException { + public void getRequestMetadataNoQuotaProjectId() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -786,7 +797,7 @@ void getRequestMetadataNoQuotaProjectId() throws IOException { } @Test - void getRequestMetadataWithCallback() throws IOException { + public void getRequestMetadataWithCallback() throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); ServiceAccountJwtAccessCredentials credentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -816,7 +827,7 @@ public void onFailure(Throwable exception) { } }); - assertTrue(success.get(), "Should have run onSuccess() callback"); + assertTrue("Should have run onSuccess() callback", success.get()); } private void verifyJwtAccess( @@ -827,15 +838,15 @@ private void verifyJwtAccess( throws IOException { assertNotNull(metadata); List authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION); - assertNotNull(authorizations, "Authorization headers not found"); + assertNotNull("Authorization headers not found", authorizations); String assertion = null; for (String authorization : authorizations) { if (authorization.startsWith(JWT_ACCESS_PREFIX)) { - assertNull(assertion, "Multiple bearer assertions found"); + assertNull("Multiple bearer assertions found", assertion); assertion = authorization.substring(JWT_ACCESS_PREFIX.length()); } } - assertNotNull(assertion, "Bearer assertion not found"); + assertNotNull("Bearer assertion not found", assertion); JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion); assertEquals(expectedEmail, signature.getPayload().getIssuer()); assertEquals(expectedEmail, signature.getPayload().getSubject()); @@ -844,12 +855,13 @@ private void verifyJwtAccess( } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - IOException exception = - assertThrows( - IOException.class, - () -> ServiceAccountJwtAccessCredentials.fromStream(stream, CALL_URI), - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - assertTrue(exception.getMessage().contains(expectedMessageContent)); + try { + ServiceAccountJwtAccessCredentials.fromStream(stream, CALL_URI); + fail( + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedMessageContent)); + } } } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/StsRequestHandlerTest.java index 324eede9f..dd0cc7ce9 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import com.google.api.client.http.HttpHeaders; import com.google.api.client.testing.http.MockLowLevelHttpRequest; @@ -44,11 +44,15 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.Before; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Tests for {@link StsRequestHandler}. */ -class StsRequestHandlerTest { +@RunWith(JUnit4.class) +public final class StsRequestHandlerTest { private static final String TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; @@ -60,13 +64,13 @@ class StsRequestHandlerTest { private MockStsTransport transport; - @BeforeEach + @Before public void setup() { transport = new MockStsTransport(); } @Test - void exchangeToken() throws IOException { + public void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType") .setScopes(Arrays.asList(CLOUD_PLATFORM_SCOPE)) @@ -100,7 +104,7 @@ void exchangeToken() throws IOException { } @Test - void exchangeToken_withOptionalParams() throws IOException { + public void exchangeToken_withOptionalParams() throws IOException { // Return optional params scope and the refresh_token. transport.addScopeSequence(Arrays.asList("scope1", "scope2", "scope3")); transport.addRefreshTokenSequence("refreshToken"); @@ -164,7 +168,7 @@ void exchangeToken_withOptionalParams() throws IOException { } @Test - void exchangeToken_throwsException() throws IOException { + public void exchangeToken_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -177,15 +181,23 @@ void exchangeToken_throwsException() throws IOException { TestUtils.buildHttpResponseException( "invalidRequest", /* errorDescription= */ null, /* errorUri= */ null)); - OAuthException exception = assertThrows(OAuthException.class, requestHandler::exchangeToken); - - assertEquals("invalidRequest", exception.getErrorCode()); - assertNull(exception.getErrorDescription()); - assertNull(exception.getErrorUri()); + OAuthException e = + assertThrows( + OAuthException.class, + new ThrowingRunnable() { + @Override + public void run() throws Throwable { + requestHandler.exchangeToken(); + } + }); + + assertEquals("invalidRequest", e.getErrorCode()); + assertNull(e.getErrorDescription()); + assertNull(e.getErrorUri()); } @Test - void exchangeToken_withOptionalParams_throwsException() throws IOException { + public void exchangeToken_withOptionalParams_throwsException() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -197,15 +209,23 @@ void exchangeToken_withOptionalParams_throwsException() throws IOException { transport.addResponseErrorSequence( TestUtils.buildHttpResponseException("invalidRequest", "errorDescription", "errorUri")); - OAuthException exception = assertThrows(OAuthException.class, requestHandler::exchangeToken); - - assertEquals("invalidRequest", exception.getErrorCode()); - assertEquals("errorDescription", exception.getErrorDescription()); - assertEquals("errorUri", exception.getErrorUri()); + OAuthException e = + assertThrows( + OAuthException.class, + new ThrowingRunnable() { + @Override + public void run() throws Throwable { + requestHandler.exchangeToken(); + } + }); + + assertEquals("invalidRequest", e.getErrorCode()); + assertEquals("errorDescription", e.getErrorDescription()); + assertEquals("errorUri", e.getErrorUri()); } @Test - void exchangeToken_ioException() { + public void exchangeToken_ioException() { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder("credential", "subjectTokenType").build(); @@ -217,12 +237,20 @@ void exchangeToken_ioException() { IOException e = new IOException(); transport.addResponseErrorSequence(e); - IOException thrownException = assertThrows(IOException.class, requestHandler::exchangeToken); + IOException thrownException = + assertThrows( + IOException.class, + new ThrowingRunnable() { + @Override + public void run() throws Throwable { + requestHandler.exchangeToken(); + } + }); assertEquals(e, thrownException); } @Test - void exchangeToken_noExpiresInReturned() throws IOException { + public void exchangeToken_noExpiresInReturned() throws IOException { // Don't return expires in. This happens in the CAB flow when the subject token does not belong // to a service account. transport.setReturnExpiresIn(/* returnExpiresIn= */ false); diff --git a/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java b/oauth2_http/javatests/com/google/auth/oauth2/TokenVerifierTest.java index 041fbabe4..1c6e17795 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.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.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.LowLevelHttpRequest; @@ -44,7 +44,6 @@ import com.google.api.client.util.Clock; import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory; -import com.google.auth.oauth2.TokenVerifier.VerificationException; import com.google.common.io.CharStreams; import java.io.IOException; import java.io.InputStream; @@ -52,9 +51,12 @@ import java.io.Reader; import java.util.Arrays; import java.util.List; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -class TokenVerifierTest { +@RunWith(JUnit4.class) +public class TokenVerifierTest { private static final String ES256_TOKEN = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im1wZjBEQSJ9.eyJhdWQiOiIvcHJvamVjdHMvNjUyNTYyNzc2Nzk4L2FwcHMvY2xvdWQtc2FtcGxlcy10ZXN0cy1waHAtaWFwIiwiZW1haWwiOiJjaGluZ29yQGdvb2dsZS5jb20iLCJleHAiOjE1ODQwNDc2MTcsImdvb2dsZSI6eyJhY2Nlc3NfbGV2ZWxzIjpbImFjY2Vzc1BvbGljaWVzLzUxODU1MTI4MDkyNC9hY2Nlc3NMZXZlbHMvcmVjZW50U2VjdXJlQ29ubmVjdERhdGEiLCJhY2Nlc3NQb2xpY2llcy81MTg1NTEyODA5MjQvYWNjZXNzTGV2ZWxzL3Rlc3ROb09wIiwiYWNjZXNzUG9saWNpZXMvNTE4NTUxMjgwOTI0L2FjY2Vzc0xldmVscy9ldmFwb3JhdGlvblFhRGF0YUZ1bGx5VHJ1c3RlZCJdfSwiaGQiOiJnb29nbGUuY29tIiwiaWF0IjoxNTg0MDQ3MDE3LCJpc3MiOiJodHRwczovL2Nsb3VkLmdvb2dsZS5jb20vaWFwIiwic3ViIjoiYWNjb3VudHMuZ29vZ2xlLmNvbToxMTIxODE3MTI3NzEyMDE5NzI4OTEifQ.yKNtdFY5EKkRboYNexBdfugzLhC3VuGyFcuFYA8kgpxMqfyxa41zkML68hYKrWu2kOBTUW95UnbGpsIi_u1fiA"; @@ -72,50 +74,56 @@ class TokenVerifierTest { Arrays.asList(ES256_TOKEN, FEDERATED_SIGNON_RS256_TOKEN, SERVICE_ACCOUNT_RS256_TOKEN); // Fixed to 2020-02-26 08:00:00 to allow expiration tests to pass - private static final Clock FIXED_CLOCK = () -> 1582704000000L; + private static final Clock FIXED_CLOCK = + new Clock() { + @Override + public long currentTimeMillis() { + return 1582704000000L; + } + }; @Test - void verifyExpiredToken() { + public void verifyExpiredToken() { for (String token : ALL_TOKENS) { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().build(); - TokenVerifier.VerificationException exception = - assertThrows( - TokenVerifier.VerificationException.class, - () -> tokenVerifier.verify(token), - "Should have thrown a VerificationException"); - assertTrue(exception.getMessage().contains("expired")); + try { + tokenVerifier.verify(token); + fail("Should have thrown a VerificationException"); + } catch (TokenVerifier.VerificationException e) { + assertTrue(e.getMessage().contains("expired")); + } } } @Test - void verifyExpectedAudience() { + public void verifyExpectedAudience() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setAudience("expected audience").build(); for (String token : ALL_TOKENS) { - TokenVerifier.VerificationException exception = - assertThrows( - TokenVerifier.VerificationException.class, - () -> tokenVerifier.verify(token), - "Should have thrown a VerificationException"); - assertTrue(exception.getMessage().contains("audience does not match")); + try { + tokenVerifier.verify(token); + fail("Should have thrown a VerificationException"); + } catch (TokenVerifier.VerificationException e) { + assertTrue(e.getMessage().contains("audience does not match")); + } } } @Test - void verifyExpectedIssuer() { + public void verifyExpectedIssuer() { TokenVerifier tokenVerifier = TokenVerifier.newBuilder().setIssuer("expected issuer").build(); for (String token : ALL_TOKENS) { - TokenVerifier.VerificationException exception = - assertThrows( - TokenVerifier.VerificationException.class, - () -> tokenVerifier.verify(token), - "Should have thrown a VerificationException"); - assertTrue(exception.getMessage().contains("issuer does not match")); + try { + tokenVerifier.verify(token); + fail("Should have thrown a VerificationException"); + } catch (TokenVerifier.VerificationException e) { + assertTrue(e.getMessage().contains("issuer does not match")); + } } } @Test - void verifyEs256Token404CertificateUrl() { + public void verifyEs256Token404CertificateUrl() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -144,15 +152,17 @@ public LowLevelHttpResponse execute() throws IOException { .setClock(FIXED_CLOCK) .setHttpTransportFactory(httpTransportFactory) .build(); - TokenVerifier.VerificationException exception = - assertThrows( - TokenVerifier.VerificationException.class, () -> tokenVerifier.verify(ES256_TOKEN)); - assertTrue( - exception.getMessage().contains("Error fetching PublicKey from certificate location")); + try { + tokenVerifier.verify(ES256_TOKEN); + fail("Should not be able to continue without exception."); + } catch (TokenVerifier.VerificationException exception) { + assertTrue( + exception.getMessage().contains("Error fetching PublicKey from certificate location")); + } } @Test - void verifyEs256TokenPublicKeyMismatch() { + public void verifyEs256TokenPublicKeyMismatch() { // Mock HTTP requests HttpTransportFactory httpTransportFactory = new HttpTransportFactory() { @@ -181,16 +191,17 @@ public LowLevelHttpResponse execute() throws IOException { .setClock(FIXED_CLOCK) .setHttpTransportFactory(httpTransportFactory) .build(); - TokenVerifier.VerificationException exception = - assertThrows( - TokenVerifier.VerificationException.class, - () -> tokenVerifier.verify(ES256_TOKEN), - "Should have failed verification"); - assertTrue(exception.getMessage().contains("Error fetching PublicKey")); + try { + tokenVerifier.verify(ES256_TOKEN); + fail("Should have failed verification"); + } catch (TokenVerifier.VerificationException e) { + assertTrue(e.getMessage().contains("Error fetching PublicKey")); + } } @Test - void verifyPublicKeyStoreIntermittentError() throws IOException, VerificationException { + public void verifyPublicKeyStoreIntermittentError() + throws TokenVerifier.VerificationException, IOException { // mock responses MockLowLevelHttpResponse response404 = new MockLowLevelHttpResponse() @@ -220,25 +231,25 @@ void verifyPublicKeyStoreIntermittentError() throws IOException, VerificationExc .setClock(FIXED_CLOCK) .setHttpTransportFactory(transportFactory) .build(); - TokenVerifier.VerificationException exception = - assertThrows( - TokenVerifier.VerificationException.class, - () -> tokenVerifier.verify(ES256_TOKEN), - "Should have failed verification"); - assertTrue(exception.getMessage().contains("Error fetching PublicKey")); + try { + tokenVerifier.verify(ES256_TOKEN); + fail("Should not be able to continue without exception."); + } catch (TokenVerifier.VerificationException exception) { + assertTrue(exception.getMessage().contains("Error fetching PublicKey")); + } - exception = - assertThrows( - TokenVerifier.VerificationException.class, - () -> tokenVerifier.verify(ES256_TOKEN), - "Should have failed verification"); - assertTrue(exception.getCause().getMessage().contains("No valid public key")); + try { + tokenVerifier.verify(ES256_TOKEN); + fail("Should not be able to continue without exception."); + } catch (TokenVerifier.VerificationException exception) { + assertTrue(exception.getCause().getMessage().contains("No valid public key")); + } assertNotNull(tokenVerifier.verify(ES256_TOKEN)); } @Test - void verifyEs256Token() throws TokenVerifier.VerificationException, IOException { + public void verifyEs256Token() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.gstatic.com/iap/verify/public_key-jwk", @@ -252,7 +263,7 @@ void verifyEs256Token() throws TokenVerifier.VerificationException, IOException } @Test - void verifyRs256Token() throws TokenVerifier.VerificationException, IOException { + public void verifyRs256Token() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( "https://www.googleapis.com/oauth2/v3/certs", @@ -266,7 +277,7 @@ void verifyRs256Token() throws TokenVerifier.VerificationException, IOException } @Test - void verifyRs256TokenWithLegacyCertificateUrlFormat() + public void verifyRs256TokenWithLegacyCertificateUrlFormat() throws TokenVerifier.VerificationException, IOException { HttpTransportFactory httpTransportFactory = mockTransport( @@ -281,7 +292,8 @@ void verifyRs256TokenWithLegacyCertificateUrlFormat() } @Test - void verifyServiceAccountRs256Token() throws TokenVerifier.VerificationException, IOException { + public void verifyServiceAccountRs256Token() + throws TokenVerifier.VerificationException, IOException { TokenVerifier tokenVerifier = TokenVerifier.newBuilder() .setClock(FIXED_CLOCK) diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java index 16cc0ec1d..345c2b9c3 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserAuthorizerTest.java @@ -31,11 +31,11 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; import com.google.auth.TestUtils; import com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory; @@ -46,10 +46,13 @@ import java.util.Collections; import java.util.Date; import java.util.Map; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Unit Tests for UserAuthorizer */ -class UserAuthorizerTest { +@RunWith(JUnit4.class) +public 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"; @@ -66,7 +69,7 @@ class UserAuthorizerTest { private static final URI BASE_URI = URI.create("http://example.com/foo"); @Test - void constructorMinimum() { + public void constructorMinimum() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -83,7 +86,7 @@ void constructorMinimum() { } @Test - void constructorCommon() { + public void constructorCommon() { TokenStore store = new MemoryTokensStorage(); UserAuthorizer authorizer = @@ -100,22 +103,18 @@ void constructorCommon() { assertEquals(CALLBACK_URI, authorizer.getCallbackUri()); } - @Test - void constructorCommon_nullClientId_throws() { - assertThrows( - NullPointerException.class, - () -> UserAuthorizer.newBuilder().setScopes(SCOPES).setCallbackUri(CALLBACK_URI).build()); + @Test(expected = NullPointerException.class) + public void constructorCommon_nullClientId_throws() { + UserAuthorizer.newBuilder().setScopes(SCOPES).setCallbackUri(CALLBACK_URI).build(); } - @Test - void constructorCommon_nullScopes_throws() { - assertThrows( - NullPointerException.class, - () -> UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build()); + @Test(expected = NullPointerException.class) + public void constructorCommon_nullScopes_throws() { + UserAuthorizer.newBuilder().setClientId(CLIENT_ID).build(); } @Test - void getCallbackUri_relativeToBase() { + public void getCallbackUri_relativeToBase() { final URI callbackURI = URI.create("/bar"); final URI expectedCallbackURI = URI.create("http://example.com/bar"); UserAuthorizer authorizer = @@ -131,7 +130,7 @@ void getCallbackUri_relativeToBase() { } @Test - void getAuthorizationUrl() throws IOException { + public void getAuthorizationUrl() throws IOException { final String CUSTOM_STATE = "custom_state"; final String PROTOCOL = "https"; final String HOST = "accounts.test.com"; @@ -163,7 +162,7 @@ void getAuthorizationUrl() throws IOException { } @Test - void getCredentials_noCredentials_returnsNull() throws IOException { + public void getCredentials_noCredentials_returnsNull() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -177,7 +176,7 @@ void getCredentials_noCredentials_returnsNull() throws IOException { } @Test - void getCredentials_storedCredentials_returnsStored() throws IOException { + public void getCredentials_storedCredentials_returnsStored() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserCredentials initialCredentials = @@ -203,8 +202,8 @@ void getCredentials_storedCredentials_returnsStored() throws IOException { assertEquals(EXPIRATION_TIME, credentials.getAccessToken().getExpirationTimeMillis()); } - @Test - void getCredentials_nullUserId_throws() { + @Test(expected = NullPointerException.class) + public void getCredentials_nullUserId_throws() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); UserAuthorizer authorizer = UserAuthorizer.newBuilder() @@ -213,11 +212,11 @@ void getCredentials_nullUserId_throws() { .setTokenStore(tokenStore) .build(); - assertThrows(NullPointerException.class, () -> authorizer.getCredentials(null)); + authorizer.getCredentials(null); } @Test - void getCredentials_refreshedToken_stored() throws IOException { + public void getCredentials_refreshedToken_stored() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; AccessToken accessToken1 = new AccessToken(accessTokenValue1, new Date(EXPIRATION_TIME)); @@ -263,7 +262,7 @@ void getCredentials_refreshedToken_stored() throws IOException { } @Test - void getCredentialsFromCode_conevertsCodeToTokens() throws IOException { + public void getCredentialsFromCode_conevertsCodeToTokens() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); transportFactory.transport.addAuthorizationCode(CODE, REFRESH_TOKEN, ACCESS_TOKEN_VALUE); @@ -282,8 +281,8 @@ void getCredentialsFromCode_conevertsCodeToTokens() throws IOException { assertEquals(ACCESS_TOKEN_VALUE, credentials.getAccessToken().getTokenValue()); } - @Test - void getCredentialsFromCode_nullCode_throws() { + @Test(expected = NullPointerException.class) + public void getCredentialsFromCode_nullCode_throws() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -291,12 +290,11 @@ void getCredentialsFromCode_nullCode_throws() { .setTokenStore(new MemoryTokensStorage()) .build(); - assertThrows( - NullPointerException.class, () -> authorizer.getCredentialsFromCode(null, BASE_URI)); + authorizer.getCredentialsFromCode(null, BASE_URI); } @Test - void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { + public void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException { final String accessTokenValue1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessTokenValue2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); @@ -331,8 +329,8 @@ void getAndStoreCredentialsFromCode_getAndStoresCredentials() throws IOException assertEquals(accessTokenValue2, credentials2.getAccessToken().getTokenValue()); } - @Test - void getAndStoreCredentialsFromCode_nullCode_throws() { + @Test(expected = NullPointerException.class) + public void getAndStoreCredentialsFromCode_nullCode_throws() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -340,13 +338,11 @@ void getAndStoreCredentialsFromCode_nullCode_throws() { .setTokenStore(new MemoryTokensStorage()) .build(); - assertThrows( - NullPointerException.class, - () -> authorizer.getAndStoreCredentialsFromCode(USER_ID, null, BASE_URI)); + authorizer.getAndStoreCredentialsFromCode(USER_ID, null, BASE_URI); } - @Test - void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOException { + @Test(expected = NullPointerException.class) + public void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOException { UserAuthorizer authorizer = UserAuthorizer.newBuilder() .setClientId(CLIENT_ID) @@ -354,13 +350,11 @@ void getAndStoreCredentialsFromCode_nullUserId_throws() throws IOException { .setTokenStore(new MemoryTokensStorage()) .build(); - assertThrows( - NullPointerException.class, - () -> authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI)); + authorizer.getAndStoreCredentialsFromCode(null, CODE, BASE_URI); } @Test - void revokeAuthorization_revokesAndClears() throws IOException { + public void revokeAuthorization_revokesAndClears() throws IOException { TokenStore tokenStore = new MemoryTokensStorage(); MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID_VALUE, CLIENT_SECRET); @@ -391,8 +385,12 @@ void revokeAuthorization_revokesAndClears() throws IOException { authorizer.revokeAuthorization(USER_ID); - assertThrows( - IOException.class, credentials1::refresh, "Credentials should not refresh after revoke."); + try { + credentials1.refresh(); + fail("Credentials should not refresh after revoke."); + } catch (IOException expected) { + // Expected + } UserCredentials credentials2 = authorizer.getCredentials(USER_ID); assertNull(credentials2); } diff --git a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index 0d3444a58..72d2f0d97 100644 --- a/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -31,14 +31,13 @@ package com.google.auth.oauth2; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static 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 com.google.api.client.json.GenericJson; import com.google.api.client.testing.http.MockLowLevelHttpResponse; @@ -61,10 +60,13 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.Test; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; /** Test case for {@link UserCredentials}. */ -class UserCredentialsTest extends BaseSerializationTest { +@RunWith(JUnit4.class) +public class UserCredentialsTest extends BaseSerializationTest { private static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; private static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; @@ -80,19 +82,13 @@ class UserCredentialsTest extends BaseSerializationTest { + "aXNzIjoiaHR0cHM6Ly9hY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAyMTAxNTUwODM0MjAwNzA4NTY4In0" + ".redacted"; - @Test - void constructor_accessAndRefreshTokenNull_throws() { - assertThrows( - IllegalStateException.class, - () -> - UserCredentials.newBuilder() - .setClientId(CLIENT_ID) - .setClientSecret(CLIENT_SECRET) - .build()); + @Test(expected = IllegalStateException.class) + public void constructor_accessAndRefreshTokenNull_throws() { + UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).build(); } @Test - void constructor() { + public void constructor() { UserCredentials credentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -107,7 +103,7 @@ void constructor() { } @Test - void createScoped_same() { + public void createScoped_same() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -118,7 +114,7 @@ void createScoped_same() { } @Test - void createScopedRequired_false() { + public void createScopedRequired_false() { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -129,7 +125,7 @@ void createScopedRequired_false() { } @Test - void fromJson_hasAccessToken() throws IOException { + public 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 +138,7 @@ void fromJson_hasAccessToken() throws IOException { } @Test - void fromJson_hasQuotaProjectId() throws IOException { + public void fromJson_hasQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -158,7 +154,7 @@ void fromJson_hasQuotaProjectId() throws IOException { } @Test - void getRequestMetadata_initialToken_hasAccessToken() throws IOException { + public void getRequestMetadata_initialToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -176,7 +172,7 @@ void getRequestMetadata_initialToken_hasAccessToken() throws IOException { } @Test - void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { + public void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); AccessToken accessToken = new AccessToken(ACCESS_TOKEN, null); @@ -188,14 +184,16 @@ void getRequestMetadata_initialTokenRefreshed_throws() throws IOException { .setHttpTransportFactory(transportFactory) .build(); - assertThrows( - IllegalStateException.class, - userCredentials::refresh, - "Should not be able to refresh without refresh token."); + try { + userCredentials.refresh(); + fail("Should not be able to refresh without refresh token."); + } catch (IllegalStateException expected) { + // Expected + } } @Test - void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { + public void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -213,7 +211,7 @@ void getRequestMetadata_fromRefreshToken_hasAccessToken() throws IOException { } @Test - void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { + public 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); @@ -234,7 +232,7 @@ void getRequestMetadata_customTokenServer_hasAccessToken() throws IOException { } @Test - void equals_true() { + public 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); @@ -263,7 +261,7 @@ void equals_true() { } @Test - void equals_false_clientId() { + public 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(); @@ -290,7 +288,7 @@ void equals_false_clientId() { } @Test - void equals_false_clientSecret() { + public 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(); @@ -317,7 +315,7 @@ void equals_false_clientSecret() { } @Test - void equals_false_refreshToken() { + public 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(); @@ -344,7 +342,7 @@ void equals_false_refreshToken() { } @Test - void equals_false_accessToken() { + public 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); @@ -372,7 +370,7 @@ void equals_false_accessToken() { } @Test - void equals_false_transportFactory() { + public 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(); @@ -400,7 +398,7 @@ void equals_false_transportFactory() { } @Test - void equals_false_tokenServer() { + public 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); @@ -428,7 +426,7 @@ void equals_false_tokenServer() { } @Test - void equals_false_quotaProjectId() { + public 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); @@ -456,7 +454,7 @@ void equals_false_quotaProjectId() { } @Test - void toString_containsFields() { + public 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(); @@ -488,7 +486,7 @@ void toString_containsFields() { } @Test - void hashCode_equals() throws IOException { + public 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); @@ -516,7 +514,7 @@ void hashCode_equals() throws IOException { } @Test - void serialize() throws IOException, ClassNotFoundException { + public 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); @@ -537,25 +535,29 @@ void serialize() throws IOException, ClassNotFoundException { } @Test - void fromStream_nullTransport_throws() throws IOException { + public void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); - assertThrows( - NullPointerException.class, - () -> UserCredentials.fromStream(stream, null), - "Should throw if HttpTransportFactory is null"); + try { + UserCredentials.fromStream(stream, null); + fail("Should throw if HttpTransportFactory is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_nullStream_throws() throws IOException { + public void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); - assertThrows( - NullPointerException.class, - () -> UserCredentials.fromStream(null, transportFactory), - "Should throw if InputStream is null"); + try { + UserCredentials.fromStream(null, transportFactory); + fail("Should throw if InputStream is null"); + } catch (NullPointerException expected) { + // Expected + } } @Test - void fromStream_user_providesToken() throws IOException { + public void fromStream_user_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -570,28 +572,28 @@ void fromStream_user_providesToken() throws IOException { } @Test - void fromStream_userNoClientId_throws() throws IOException { + public void fromStream_userNoClientId_throws() throws IOException { InputStream userStream = writeUserStream(null, CLIENT_SECRET, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_id"); } @Test - void fromStream_userNoClientSecret_throws() throws IOException { + public void fromStream_userNoClientSecret_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, null, REFRESH_TOKEN, QUOTA_PROJECT); testFromStreamException(userStream, "client_secret"); } @Test - void fromStream_userNoRefreshToken_throws() throws IOException { + public void fromStream_userNoRefreshToken_throws() throws IOException { InputStream userStream = writeUserStream(CLIENT_ID, CLIENT_SECRET, null, QUOTA_PROJECT); testFromStreamException(userStream, "refresh_token"); } @Test - void saveUserCredentials_saved_throws() throws IOException { + public void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -606,7 +608,7 @@ void saveUserCredentials_saved_throws() throws IOException { } @Test - void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { + public void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) @@ -631,7 +633,7 @@ void saveAndRestoreUserCredential_saveAndRestored_throws() throws IOException { } @Test - void getRequestMetadataSetsQuotaProjectId() throws IOException { + public void getRequestMetadataSetsQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -645,7 +647,7 @@ void getRequestMetadataSetsQuotaProjectId() throws IOException { .setHttpTransportFactory(transportFactory) .build(); - Map> metadata = userCredentials.getRequestMetadata(); + Map> metadata = userCredentials.getRequestMetadata(CALL_URI); assertTrue(metadata.containsKey("x-goog-user-project")); List headerValues = metadata.get("x-goog-user-project"); assertEquals(1, headerValues.size()); @@ -653,7 +655,7 @@ void getRequestMetadataSetsQuotaProjectId() throws IOException { } @Test - void getRequestMetadataNoQuotaProjectId() throws IOException { + public void getRequestMetadataNoQuotaProjectId() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -666,12 +668,12 @@ void getRequestMetadataNoQuotaProjectId() throws IOException { .setHttpTransportFactory(transportFactory) .build(); - Map> metadata = userCredentials.getRequestMetadata(); + Map> metadata = userCredentials.getRequestMetadata(CALL_URI); assertFalse(metadata.containsKey("x-goog-user-project")); } @Test - void getRequestMetadataWithCallback() throws IOException { + public void getRequestMetadataWithCallback() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -684,7 +686,7 @@ void getRequestMetadataWithCallback() throws IOException { .setQuotaProjectId("my-quota-project-id") .setHttpTransportFactory(transportFactory) .build(); - final Map> plainMetadata = userCredentials.getRequestMetadata(); + final Map> plainMetadata = userCredentials.getRequestMetadata(CALL_URI); final AtomicBoolean success = new AtomicBoolean(false); userCredentials.getRequestMetadata( null, @@ -702,11 +704,11 @@ public void onFailure(Throwable exception) { } }); - assertTrue(success.get(), "Should have run onSuccess() callback"); + assertTrue("Should have run onSuccess() callback", success.get()); } @Test - void IdTokenCredentials_WithUserEmailScope_success() throws IOException { + public void IdTokenCredentials_WithUserEmailScope_success() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -726,14 +728,14 @@ void IdTokenCredentials_WithUserEmailScope_success() throws IOException { assertNull(tokenCredential.getIdToken()); // trigger the refresh like it would happen during a request build - tokenCredential.getRequestMetadata(); + tokenCredential.getRequestMetadata(CALL_URI); assertEquals(DEFAULT_ID_TOKEN, tokenCredential.getAccessToken().getTokenValue()); assertEquals(DEFAULT_ID_TOKEN, tokenCredential.getIdToken().getTokenValue()); } @Test - void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { + public void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -746,18 +748,15 @@ void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { UserCredentials credentials = UserCredentials.fromStream(userStream, transportFactory); - GoogleAuthException ex = - assertThrows( - GoogleAuthException.class, - () -> { - transportFactory.transport.addResponseSequence(response408, response429); - credentials.refresh(); - }, - "Should not retry"); - - assertTrue(ex.getMessage().contains("com.google.api.client.http.HttpResponseException: 408")); - assertTrue(ex.isRetryable()); - assertEquals(0, ex.getRetryCount()); + try { + transportFactory.transport.addResponseSequence(response408, response429); + credentials.refresh(); + fail("Should not be able to use credential without exception."); + } catch (GoogleAuthException ex) { + assertTrue(ex.getMessage().contains("com.google.api.client.http.HttpResponseException: 408")); + assertTrue(ex.isRetryable()); + assertEquals(0, ex.getRetryCount()); + } IdTokenCredentials tokenCredential = IdTokenCredentials.newBuilder().setIdTokenProvider(credentials).build(); @@ -766,21 +765,18 @@ void IdTokenCredentials_NoRetry_RetryableStatus_throws() throws IOException { assertNull(tokenCredential.getIdToken()); // trigger the refresh like it would happen during a request build - ex = - assertThrows( - GoogleAuthException.class, - () -> { - tokenCredential.getRequestMetadata(); - }, - "Should not retry"); - - assertTrue(ex.getMessage().contains("com.google.api.client.http.HttpResponseException: 429")); - assertTrue(ex.isRetryable()); - assertEquals(0, ex.getRetryCount()); + try { + tokenCredential.getRequestMetadata(CALL_URI); + fail("Should not be able to use credential without exception."); + } catch (GoogleAuthException ex) { + assertTrue(ex.getMessage().contains("com.google.api.client.http.HttpResponseException: 429")); + assertTrue(ex.isRetryable()); + assertEquals(0, ex.getRetryCount()); + } } @Test - void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { + public void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); String refreshToken = MockTokenServerTransport.REFRESH_TOKEN_WITH_USER_SCOPE; @@ -796,21 +792,19 @@ void refreshAccessToken_4xx_5xx_NonRetryableFails() throws IOException { } MockLowLevelHttpResponse mockResponse = new MockLowLevelHttpResponse().setStatusCode(status); - GoogleAuthException ex = - assertThrows( - GoogleAuthException.class, - () -> { - transportFactory.transport.addResponseSequence(mockResponse); - credentials.refresh(); - }, - "Should not retry status " + status); - assertFalse(ex.isRetryable()); - assertEquals(0, ex.getRetryCount()); + try { + transportFactory.transport.addResponseSequence(mockResponse); + credentials.refresh(); + fail("Should not be able to use credential without exception."); + } catch (GoogleAuthException ex) { + assertFalse(ex.isRetryable()); + assertEquals(0, ex.getRetryCount()); + } } } @Test - void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + public void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); @@ -828,8 +822,12 @@ void IdTokenCredentials_NoUserEmailScope_throws() throws IOException { + " login'. The latter form would not work for Cloud Run, but would still generate an" + " id token."; - IOException exception = assertThrows(IOException.class, tokenCredential::refresh); - assertTrue(exception.getMessage().equals(expectedMessageContent)); + try { + tokenCredential.refresh(); + fail("Should not be able to use credential without exception."); + } catch (IOException expected) { + assertTrue(expected.getMessage().equals(expectedMessageContent)); + } } static GenericJson writeUserJson( @@ -859,12 +857,13 @@ static InputStream writeUserStream( } private static void testFromStreamException(InputStream stream, String expectedMessageContent) { - IOException exception = - assertThrows( - IOException.class, - () -> UserCredentials.fromStream(stream), - String.format( - "Should throw exception with message containing '%s'", expectedMessageContent)); - assertTrue(exception.getMessage().contains(expectedMessageContent)); + try { + UserCredentials.fromStream(stream); + fail( + String.format( + "Should throw exception with message containing '%s'", expectedMessageContent)); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedMessageContent)); + } } } 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 afe7eac7d..e70db86a2 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.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; @@ -49,10 +49,11 @@ import com.google.auth.oauth2.IdToken; import com.google.auth.oauth2.IdTokenCredentials; import com.google.auth.oauth2.IdTokenProvider; +import java.io.FileNotFoundException; import java.io.IOException; -import org.junit.jupiter.api.Test; +import org.junit.Test; -class FTServiceAccountCredentialsTest { +public final class FTServiceAccountCredentialsTest { private final String cloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"; private final String cloudTasksUrl = @@ -65,19 +66,19 @@ class FTServiceAccountCredentialsTest { "https://compute.googleapis.com/compute/v1/projects/gcloud-devel/zones/us-central1-a/instances"; @Test - void NoScopeNoAudienceComputeTest() throws Exception { + public void NoScopeNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(computeUrl); assertEquals(200, response.getStatusCode()); } @Test - void NoScopeNoAudienceBigQueryTest() throws Exception { + public void NoScopeNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(bigQueryUrl); assertEquals(200, response.getStatusCode()); } @Test - void NoScopeNoAudienceOnePlatformTest() throws Exception { + public void NoScopeNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithoutScope(cloudTasksUrl); assertEquals(200, response.getStatusCode()); } @@ -85,7 +86,7 @@ void NoScopeNoAudienceOnePlatformTest() throws Exception { // TODO: add Storage case @Test - void AudienceSetNoScopeTest() throws Exception { + public void AudienceSetNoScopeTest() throws Exception { final GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); IdTokenCredentials tokenCredential = @@ -106,62 +107,62 @@ void AudienceSetNoScopeTest() throws Exception { } @Test - void ScopeSetNoAudienceStorageTest() throws Exception { + public void ScopeSetNoAudienceStorageTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(storageUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - void ScopeSetNoAudienceComputeTest() throws Exception { + public void ScopeSetNoAudienceComputeTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(computeUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - void ScopeSetNoAudienceBigQueryTest() throws Exception { + public void ScopeSetNoAudienceBigQueryTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(bigQueryUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - void ScopeSetNoAudienceOnePlatformTest() throws Exception { + public void ScopeSetNoAudienceOnePlatformTest() throws Exception { HttpResponse response = executeRequestWithCredentialsWithScope(cloudTasksUrl, cloudPlatformScope); assertEquals(200, response.getStatusCode()); } @Test - void WrongScopeComputeTest() throws Exception { + public void WrongScopeComputeTest() throws Exception { executeRequestWrongScope(computeUrl); } @Test - void WrongScopeStorageTest() throws Exception { + public void WrongScopeStorageTest() throws Exception { executeRequestWrongScope(storageUrl); } @Test - void WrongScopeBigQueryTest() throws Exception { + public void WrongScopeBigQueryTest() throws Exception { executeRequestWrongScope(bigQueryUrl); } @Test - void WrongScopeOnePlatformTest() throws Exception { + public void WrongScopeOnePlatformTest() throws Exception { executeRequestWrongScope(cloudTasksUrl); } - private void executeRequestWrongScope(String serviceUri) { + private void executeRequestWrongScope(String serviceUri) + throws FileNotFoundException, IOException { String expectedMessage = "403 Forbidden"; - IOException exception = - assertThrows( - IOException.class, - () -> - executeRequestWithCredentialsWithScope( - serviceUri, "https://www.googleapis.com/auth/adexchange.buyer"), - "Should throw exception: " + expectedMessage); - assertTrue(exception.getMessage().contains(expectedMessage)); + try { + executeRequestWithCredentialsWithScope( + serviceUri, "https://www.googleapis.com/auth/adexchange.buyer"); + fail("Should throw exception: " + expectedMessage); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains(expectedMessage)); + } } private HttpResponse executeRequestWithCredentialsWithoutScope(String serviceUrl) diff --git a/oauth2_http/pom.xml b/oauth2_http/pom.xml index d9bd261b5..81fd60d3e 100644 --- a/oauth2_http/pom.xml +++ b/oauth2_http/pom.xml @@ -74,6 +74,7 @@ org.apache.maven.plugins maven-surefire-plugin + 3.0.0-M5 @@ -82,6 +83,13 @@ sponge_log + + + org.apache.maven.surefire + surefire-junit47 + 3.0.0-M5 + + org.apache.maven.plugins @@ -124,8 +132,8 @@ guava - org.junit.jupiter - junit-jupiter-api + junit + junit test diff --git a/pom.xml b/pom.xml index 46e761589..325d81032 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,7 @@ UTF-8 1.42.2 - 5.9.0 + 4.13.2 31.0.1-android 2.0.5 3.0.2 @@ -71,13 +71,6 @@ - - org.junit - junit-bom - ${project.junit.bom.version} - pom - import - com.google.auth google-auth-library-credentials @@ -120,6 +113,12 @@ auto-value-annotations ${auto-value-annotation.version} + + junit + junit + ${project.junit.version} + test + com.google.appengine appengine