Skip to content

Commit ea9a28a

Browse files
authored
Cleaning up some Firebase Auth Unit Tests (firebase#226)
* Cleaning up some auth tests * Updated tests * Cleaned up custom token tests
1 parent 4e7cfc6 commit ea9a28a

3 files changed

Lines changed: 201 additions & 226 deletions

File tree

‎src/test/java/com/google/firebase/FirebaseAppTest.java‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import static org.junit.Assert.assertEquals;
2020
import static org.junit.Assert.assertFalse;
2121
import static org.junit.Assert.assertNotSame;
22+
import static org.junit.Assert.assertNull;
2223
import static org.junit.Assert.assertSame;
2324
import static org.junit.Assert.assertTrue;
2425
import static org.junit.Assert.fail;
@@ -448,6 +449,19 @@ public void testTokenRefresherStateMachine() {
448449
assertEquals(0, refresher.cancelCalls);
449450
}
450451

452+
@Test
453+
public void testAppWithAuthVariableOverrides() {
454+
Map<String, Object> authVariableOverrides = ImmutableMap.<String, Object>of("uid", "uid1");
455+
FirebaseOptions options =
456+
new FirebaseOptions.Builder(getMockCredentialOptions())
457+
.setDatabaseAuthVariableOverride(authVariableOverrides)
458+
.build();
459+
FirebaseApp app = FirebaseApp.initializeApp(options, "testGetAppWithUid");
460+
assertEquals("uid1", app.getOptions().getDatabaseAuthVariableOverride().get("uid"));
461+
String token = TestOnlyImplFirebaseTrampolines.getToken(app, false);
462+
Assert.assertTrue(!token.isEmpty());
463+
}
464+
451465
@Test(expected = IllegalArgumentException.class)
452466
public void testEmptyFirebaseConfigFile() {
453467
setFirebaseConfigEnvironmentVariable("firebase_config_empty.json");
@@ -458,19 +472,19 @@ public void testEmptyFirebaseConfigFile() {
458472
public void testEmptyFirebaseConfigString() {
459473
setFirebaseConfigEnvironmentVariable("");
460474
FirebaseApp firebaseApp = FirebaseApp.initializeApp();
461-
assertEquals(null, firebaseApp.getOptions().getProjectId());
462-
assertEquals(null, firebaseApp.getOptions().getStorageBucket());
463-
assertEquals(null, firebaseApp.getOptions().getDatabaseUrl());
475+
assertNull(firebaseApp.getOptions().getProjectId());
476+
assertNull(firebaseApp.getOptions().getStorageBucket());
477+
assertNull(firebaseApp.getOptions().getDatabaseUrl());
464478
assertTrue(firebaseApp.getOptions().getDatabaseAuthVariableOverride().isEmpty());
465479
}
466480

467481
@Test
468482
public void testEmptyFirebaseConfigJSONObject() {
469483
setFirebaseConfigEnvironmentVariable("{}");
470484
FirebaseApp firebaseApp = FirebaseApp.initializeApp();
471-
assertEquals(null, firebaseApp.getOptions().getProjectId());
472-
assertEquals(null, firebaseApp.getOptions().getStorageBucket());
473-
assertEquals(null, firebaseApp.getOptions().getDatabaseUrl());
485+
assertNull(firebaseApp.getOptions().getProjectId());
486+
assertNull(firebaseApp.getOptions().getStorageBucket());
487+
assertNull(firebaseApp.getOptions().getDatabaseUrl());
474488
assertTrue(firebaseApp.getOptions().getDatabaseAuthVariableOverride().isEmpty());
475489
}
476490

@@ -514,9 +528,9 @@ public void testValidFirebaseConfigFile() {
514528
public void testEnvironmentVariableIgnored() {
515529
setFirebaseConfigEnvironmentVariable("firebase_config.json");
516530
FirebaseApp firebaseApp = FirebaseApp.initializeApp(OPTIONS);
517-
assertEquals(null, firebaseApp.getOptions().getProjectId());
518-
assertEquals(null, firebaseApp.getOptions().getStorageBucket());
519-
assertEquals(null, firebaseApp.getOptions().getDatabaseUrl());
531+
assertNull(firebaseApp.getOptions().getProjectId());
532+
assertNull(firebaseApp.getOptions().getStorageBucket());
533+
assertNull(firebaseApp.getOptions().getDatabaseUrl());
520534
assertTrue(firebaseApp.getOptions().getDatabaseAuthVariableOverride().isEmpty());
521535
}
522536

‎src/test/java/com/google/firebase/auth/FirebaseAuthTest.java‎

Lines changed: 15 additions & 217 deletions
Original file line numberDiff line numberDiff line change
@@ -19,137 +19,39 @@
1919
import static org.junit.Assert.assertEquals;
2020
import static org.junit.Assert.assertNotNull;
2121
import static org.junit.Assert.assertNotSame;
22-
import static org.junit.Assert.assertNull;
2322
import static org.junit.Assert.assertSame;
2423
import static org.junit.Assert.assertTrue;
2524
import static org.junit.Assert.fail;
2625

27-
import com.google.api.client.googleapis.testing.auth.oauth2.MockTokenServerTransport;
28-
import com.google.api.client.googleapis.util.Utils;
29-
import com.google.api.client.http.HttpTransport;
30-
import com.google.api.client.json.JsonFactory;
31-
import com.google.api.client.json.gson.GsonFactory;
3226
import com.google.api.core.ApiFuture;
33-
import com.google.auth.http.HttpTransportFactory;
34-
import com.google.auth.oauth2.GoogleCredentials;
35-
import com.google.auth.oauth2.ServiceAccountCredentials;
36-
import com.google.auth.oauth2.UserCredentials;
3727
import com.google.common.base.Defaults;
38-
import com.google.common.base.Strings;
3928
import com.google.firebase.FirebaseApp;
4029
import com.google.firebase.FirebaseOptions;
41-
import com.google.firebase.ImplFirebaseTrampolines;
4230
import com.google.firebase.TestOnlyImplFirebaseTrampolines;
43-
import com.google.firebase.auth.internal.FirebaseCustomAuthToken;
44-
import com.google.firebase.database.MapBuilder;
4531
import com.google.firebase.testing.ServiceAccount;
4632
import com.google.firebase.testing.TestUtils;
47-
import java.io.ByteArrayInputStream;
48-
import java.io.IOException;
49-
import java.io.InputStream;
5033
import java.lang.reflect.InvocationTargetException;
5134
import java.lang.reflect.Method;
5235
import java.lang.reflect.Modifier;
5336
import java.util.ArrayList;
54-
import java.util.Arrays;
55-
import java.util.Collection;
56-
import java.util.Collections;
57-
import java.util.HashMap;
5837
import java.util.List;
59-
import java.util.Map;
6038
import java.util.concurrent.ExecutionException;
6139
import java.util.concurrent.TimeUnit;
6240
import java.util.concurrent.TimeoutException;
6341

6442
import org.junit.After;
6543
import org.junit.Assert;
66-
import org.junit.Assume;
6744
import org.junit.Before;
6845
import org.junit.Test;
69-
import org.junit.runner.RunWith;
70-
import org.junit.runners.Parameterized;
71-
import org.junit.runners.Parameterized.Parameters;
7246

73-
@RunWith(Parameterized.class)
7447
public class FirebaseAuthTest {
7548

76-
private static final String ACCESS_TOKEN = "mockaccesstoken";
77-
private static final String CLIENT_SECRET = "mockclientsecret";
78-
private static final String CLIENT_ID = "mockclientid";
79-
private static final String REFRESH_TOKEN = "mockrefreshtoken";
80-
private static final JsonFactory JSON_FACTORY = Utils.getDefaultJsonFactory();
81-
82-
private final FirebaseOptions firebaseOptions;
83-
private final boolean isCertCredential;
84-
85-
public FirebaseAuthTest(FirebaseOptions baseOptions, boolean isCertCredential) {
86-
this.firebaseOptions = baseOptions;
87-
this.isCertCredential = isCertCredential;
88-
}
89-
90-
@Parameters
91-
public static Collection<Object[]> data() throws Exception {
92-
// Initialize this test suite with all available credential implementations.
93-
return Arrays.asList(
94-
new Object[][] {
95-
{
96-
new FirebaseOptions.Builder().setCredentials(createCertificateCredential()).build(),
97-
/* isCertCredential */ true
98-
},
99-
{
100-
new FirebaseOptions.Builder()
101-
.setCredentials(createRefreshTokenCredential())
102-
.setProjectId("test-project-id")
103-
.build(),
104-
/* isCertCredential */ false
105-
},
106-
{
107-
new FirebaseOptions.Builder()
108-
.setCredentials(TestUtils.getApplicationDefaultCredentials())
109-
.build(),
110-
/* isCertCredential */ false
111-
},
112-
});
113-
}
114-
115-
private static GoogleCredentials createRefreshTokenCredential() throws IOException {
116-
117-
final MockTokenServerTransport transport = new MockTokenServerTransport();
118-
transport.addClient(CLIENT_ID, CLIENT_SECRET);
119-
transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN);
120-
121-
Map<String, Object> secretJson = new HashMap<>();
122-
secretJson.put("client_id", CLIENT_ID);
123-
secretJson.put("client_secret", CLIENT_SECRET);
124-
secretJson.put("refresh_token", REFRESH_TOKEN);
125-
secretJson.put("type", "authorized_user");
126-
InputStream refreshTokenStream =
127-
new ByteArrayInputStream(JSON_FACTORY.toByteArray(secretJson));
128-
129-
return UserCredentials.fromStream(refreshTokenStream, new HttpTransportFactory() {
130-
@Override
131-
public HttpTransport create() {
132-
return transport;
133-
}
134-
});
135-
}
136-
137-
private static GoogleCredentials createCertificateCredential() throws IOException {
138-
final MockTokenServerTransport transport = new MockTokenServerTransport(
139-
"https://accounts.google.com/o/oauth2/token");
140-
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
141-
return ServiceAccountCredentials.fromStream(ServiceAccount.EDITOR.asStream(),
142-
new HttpTransportFactory() {
143-
@Override
144-
public HttpTransport create() {
145-
return transport;
146-
}
147-
});
148-
}
49+
private static final FirebaseOptions firebaseOptions = FirebaseOptions.builder()
50+
.setCredentials(TestUtils.getCertCredential(ServiceAccount.EDITOR.asStream()))
51+
.build();
14952

15053
@Before
15154
public void setup() {
152-
TestOnlyImplFirebaseTrampolines.clearInstancesForTest();
15355
FirebaseApp.initializeApp(firebaseOptions);
15456
}
15557

@@ -163,8 +65,6 @@ public void testGetInstance() {
16365
FirebaseAuth defaultAuth = FirebaseAuth.getInstance();
16466
assertNotNull(defaultAuth);
16567
assertSame(defaultAuth, FirebaseAuth.getInstance());
166-
String token = TestOnlyImplFirebaseTrampolines.getToken(FirebaseApp.getInstance(), false);
167-
Assert.assertTrue(!token.isEmpty());
16868
}
16969

17070
@Test
@@ -173,8 +73,6 @@ public void testGetInstanceForApp() {
17373
FirebaseAuth auth = FirebaseAuth.getInstance(app);
17474
assertNotNull(auth);
17575
assertSame(auth, FirebaseAuth.getInstance(app));
176-
String token = TestOnlyImplFirebaseTrampolines.getToken(app, false);
177-
Assert.assertTrue(!token.isEmpty());
17876
}
17977

18078
@Test
@@ -234,126 +132,26 @@ public void testInitAfterAppDelete() throws ExecutionException, InterruptedExcep
234132
assertNotNull(auth2);
235133
assertNotSame(auth1, auth2);
236134

237-
if (isCertCredential) {
238-
ApiFuture<String> future = auth2.createCustomTokenAsync("foo");
239-
assertNotNull(future);
240-
assertNotNull(future.get(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
241-
}
242-
}
243-
244-
@Test
245-
public void testAppWithAuthVariableOverrides() {
246-
Map<String, Object> authVariableOverrides = Collections.singletonMap("uid", (Object) "uid1");
247-
FirebaseOptions options =
248-
new FirebaseOptions.Builder(firebaseOptions)
249-
.setDatabaseAuthVariableOverride(authVariableOverrides)
250-
.build();
251-
FirebaseApp app = FirebaseApp.initializeApp(options, "testGetAppWithUid");
252-
assertEquals("uid1", app.getOptions().getDatabaseAuthVariableOverride().get("uid"));
253-
String token = TestOnlyImplFirebaseTrampolines.getToken(app, false);
254-
Assert.assertTrue(!token.isEmpty());
255-
}
256-
257-
@Test
258-
public void testCreateCustomToken() throws Exception {
259-
GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
260-
Assume.assumeTrue("Skipping testCredentialCertificateRequired for cert credential",
261-
credentials instanceof ServiceAccountCredentials);
262-
263-
FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testCreateCustomToken");
264-
FirebaseAuth auth = FirebaseAuth.getInstance(app);
265-
266-
String token = auth.createCustomTokenAsync("user1").get();
267-
268-
FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
269-
assertEquals(parsedToken.getPayload().getUid(), "user1");
270-
assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
271-
assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
272-
assertNull(parsedToken.getPayload().getDeveloperClaims());
273-
assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
274-
}
275-
276-
@Test
277-
public void testCreateCustomTokenWithDeveloperClaims() throws Exception {
278-
GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
279-
Assume.assumeTrue("Skipping testCredentialCertificateRequired for cert credential",
280-
credentials instanceof ServiceAccountCredentials);
281-
282-
FirebaseApp app =
283-
FirebaseApp.initializeApp(firebaseOptions, "testCreateCustomTokenWithDeveloperClaims");
284-
FirebaseAuth auth = FirebaseAuth.getInstance(app);
285-
286-
String token =
287-
auth.createCustomTokenAsync("user1", MapBuilder.of("claim", "value")).get();
288-
289-
FirebaseCustomAuthToken parsedToken = FirebaseCustomAuthToken.parse(new GsonFactory(), token);
290-
assertEquals(parsedToken.getPayload().getUid(), "user1");
291-
assertEquals(parsedToken.getPayload().getSubject(), ServiceAccount.EDITOR.getEmail());
292-
assertEquals(parsedToken.getPayload().getIssuer(), ServiceAccount.EDITOR.getEmail());
293-
assertEquals(parsedToken.getPayload().getDeveloperClaims().keySet().size(), 1);
294-
assertEquals(parsedToken.getPayload().getDeveloperClaims().get("claim"), "value");
295-
assertTrue(ServiceAccount.EDITOR.verifySignature(parsedToken));
296-
}
297-
298-
@Test
299-
public void testServiceAccountRequired() throws Exception {
300-
GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
301-
Assume.assumeFalse("Skipping testServiceAccountRequired for service account credentials",
302-
credentials instanceof ServiceAccountCredentials);
303-
304-
FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testServiceAccountRequired");
305-
try {
306-
FirebaseAuth.getInstance(app).createCustomTokenAsync("foo").get();
307-
fail("Expected exception.");
308-
} catch (IllegalStateException expected) {
309-
Assert.assertEquals(
310-
"Failed to initialize FirebaseTokenFactory. Make sure to initialize the SDK with "
311-
+ "service account credentials or specify a service account ID with "
312-
+ "iam.serviceAccounts.signBlob permission. Please refer to "
313-
+ "https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details "
314-
+ "on creating custom tokens.",
315-
expected.getMessage());
316-
}
135+
ApiFuture<String> future = auth2.createCustomTokenAsync("foo");
136+
assertNotNull(future);
137+
assertNotNull(future.get(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
317138
}
318139

319140
@Test
320-
public void testProjectIdRequired() throws Exception {
321-
FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testProjectIdRequired");
322-
String projectId = ImplFirebaseTrampolines.getProjectId(app);
323-
Assume.assumeTrue("Skipping testProjectIdRequired for settings with project ID",
324-
Strings.isNullOrEmpty(projectId));
325-
141+
public void testProjectIdRequired() {
142+
FirebaseOptions options = FirebaseOptions.builder()
143+
.setCredentials(new MockGoogleCredentials())
144+
.build();
145+
FirebaseApp app = FirebaseApp.initializeApp(options, "testProjectIdRequired");
326146
try {
327-
FirebaseAuth.getInstance(app).verifyIdTokenAsync("foo").get();
147+
FirebaseAuth.getInstance(app);
328148
fail("Expected exception.");
329149
} catch (IllegalArgumentException expected) {
330150
Assert.assertEquals(
331-
"Must initialize FirebaseApp with a project ID to call verifyIdToken()",
332-
expected.getMessage());
333-
}
334-
}
335-
336-
@Test
337-
public void testVerifyIdTokenWithExplicitProjectId() throws Exception {
338-
GoogleCredentials credentials = TestOnlyImplFirebaseTrampolines.getCredentials(firebaseOptions);
339-
Assume.assumeFalse(
340-
"Skipping testVerifyIdTokenWithExplicitProjectId for service account credentials",
341-
credentials instanceof ServiceAccountCredentials);
342-
343-
FirebaseOptions options =
344-
new FirebaseOptions.Builder(firebaseOptions)
345-
.setProjectId("mock-project-id")
346-
.build();
347-
FirebaseApp app = FirebaseApp.initializeApp(options, "testVerifyIdTokenWithExplicitProjectId");
348-
try {
349-
FirebaseAuth.getInstance(app).verifyIdTokenAsync("foo").get();
350-
fail("Expected exception.");
351-
} catch (ExecutionException expected) {
352-
Assert.assertNotEquals(
353-
"com.google.firebase.FirebaseException: Must initialize FirebaseApp with a project ID "
354-
+ "to call verifyIdToken()",
151+
"Project ID is required to access the auth service. Use a service account credential "
152+
+ "or set the project ID explicitly via FirebaseOptions. Alternatively you can "
153+
+ "also set the project ID via the GOOGLE_CLOUD_PROJECT environment variable.",
355154
expected.getMessage());
356-
assertTrue(expected.getCause() instanceof IllegalArgumentException);
357155
}
358156
}
359157

0 commit comments

Comments
 (0)