Skip to content

getId() implementation with instrumented tests. #703

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Aug 30, 2019
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
30cf6ed
getId() implementation with instrumented tests.
ankitaj224 Aug 13, 2019
d034bbb
Addressing rayo's comments.
ankitaj224 Aug 14, 2019
f8b468c
Addressing rayo's comments.
ankitaj224 Aug 14, 2019
8db7967
Merge branch 'ankita_fis' of github.com:firebase/firebase-android-sdk…
ankitaj224 Aug 14, 2019
b507a3c
Merge branch 'create_fis' of github.com:firebase/firebase-android-sdk…
ankitaj224 Aug 14, 2019
f5a7c05
Merge branch 'ankita_fis' of github.com:firebase/firebase-android-sdk…
ankitaj224 Aug 14, 2019
90cdbaa
Addresing comments to resoleve the following:
ankitaj224 Aug 16, 2019
0dfa987
Addressing Ciaran and Rayo's comments.
ankitaj224 Aug 26, 2019
a71a1f3
Addressing Ciaran's comments
ankitaj224 Aug 27, 2019
0a92e2d
Addressing Ciaran's comments
ankitaj224 Aug 27, 2019
4cc0cee
Merge branch 'create_fis' of github.com:firebase/firebase-android-sdk…
ankitaj224 Aug 28, 2019
f16db3f
Merge branch 'ankita_fis' of github.com:firebase/firebase-android-sdk…
ankitaj224 Aug 29, 2019
f8e75fd
Adding param comments and checking if registration status is valid.
ankitaj224 Aug 30, 2019
227bf3b
Correcting lint warning: uses-permission should be declared before
ankitaj224 Aug 30, 2019
4be3847
Adding custom assertThat with more readable assertions
ankitaj224 Aug 30, 2019
68acde5
Correcting instrumented tests to be reliable.
ankitaj224 Aug 30, 2019
16544a6
Merge branch 'ankita_fis' of github.com:firebase/firebase-android-sdk…
ankitaj224 Aug 30, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions firebase-installations/firebase-installations.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,6 @@ dependencies {
androidTestImplementation "com.google.truth:truth:$googleTruthVersion"
androidTestImplementation 'junit:junit:4.12'
androidTestImplementation "androidx.annotation:annotation:1.0.0"
androidTestImplementation 'org.mockito:mockito-core:2.25.0'
androidTestImplementation 'org.mockito:mockito-android:2.25.0'
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,43 @@

package com.google.firebase.installations;

import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_APP_ID_1;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_AUTH_TOKEN;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_CREATION_TIMESTAMP_1;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_FID_1;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_PROJECT_ID;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_REFRESH_TOKEN;
import static com.google.firebase.installations.FisAndroidTestConstants.TEST_TOKEN_EXPIRATION_TIMESTAMP;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.runner.AndroidJUnit4;
import com.google.android.gms.common.util.Clock;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.installations.local.PersistedFid;
import com.google.firebase.installations.local.PersistedFidEntry;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the difference between PersistedFid and PersistedFidEntry?

import com.google.firebase.installations.remote.FirebaseInstallationServiceClient;
import com.google.firebase.installations.remote.FirebaseInstallationServiceException;
import com.google.firebase.installations.remote.InstallationResponse;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/**
* Instrumented test, which will execute on an Android device.
Expand All @@ -26,4 +59,171 @@
*/
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class FirebaseInstallationsInstrumentedTest {}
public class FirebaseInstallationsInstrumentedTest {
private FirebaseApp firebaseApp;
private ExecutorService executor;
private PersistedFid persistedFid;
@Mock private FirebaseInstallationServiceClient backendClientReturnsOk;
@Mock private FirebaseInstallationServiceClient backendClientReturnsError;
@Mock private PersistedFid persistedFidReturnsError;
@Mock private Utils mockUtils;
@Mock private Clock mockClock;

@Before
public void setUp() throws FirebaseInstallationServiceException {
MockitoAnnotations.initMocks(this);
FirebaseApp.clearInstancesForTest();
executor = new ThreadPoolExecutor(0, 2, 10L, TimeUnit.SECONDS, new SynchronousQueue<>());
firebaseApp =
FirebaseApp.initializeApp(
ApplicationProvider.getApplicationContext(),
new FirebaseOptions.Builder()
.setApplicationId(TEST_APP_ID_1)
.setProjectId(TEST_PROJECT_ID)
.setApiKey("api_key")
.build());
persistedFid = new PersistedFid(firebaseApp);
when(backendClientReturnsOk.createFirebaseInstallation(
anyString(), anyString(), anyString(), anyString()))
.thenReturn(
InstallationResponse.builder()
.setName("/projects/" + TEST_PROJECT_ID + "/installations/" + TEST_FID_1)
.setRefreshToken(TEST_REFRESH_TOKEN)
.setAuthToken(
InstallationTokenResult.builder()
.setToken(TEST_AUTH_TOKEN)
.setTokenExpirationTimestampMillis(TEST_TOKEN_EXPIRATION_TIMESTAMP)
.build())
.build());
when(backendClientReturnsError.createFirebaseInstallation(
anyString(), anyString(), anyString(), anyString()))
.thenThrow(
new FirebaseInstallationServiceException(
"SDK Error", FirebaseInstallationServiceException.Status.SERVER_ERROR));
when(persistedFidReturnsError.insertOrUpdatePersistedFidEntry(any())).thenReturn(false);
when(persistedFidReturnsError.readPersistedFidEntryValue()).thenReturn(null);
when(mockUtils.createRandomFid()).thenReturn(TEST_FID_1);
when(mockClock.currentTimeMillis()).thenReturn(TEST_CREATION_TIMESTAMP_1);
}

@After
public void cleanUp() throws Exception {
persistedFid.clear();
}

@Test
public void testGetId_PersistedFidOk_BackendOk() throws Exception {
FirebaseInstallations firebaseInstallations =
new FirebaseInstallations(
mockClock, executor, firebaseApp, backendClientReturnsOk, persistedFid, mockUtils);

// No exception, means success.
assertWithMessage("getId Task fails.")
.that(Tasks.await(firebaseInstallations.getId()))
.isNotEmpty();
PersistedFidEntry entryValue = persistedFid.readPersistedFidEntryValue();
assertWithMessage("Persisted Fid doesn't match")
.that(entryValue.getFirebaseInstallationId())
.isEqualTo(TEST_FID_1);
assertWithMessage("Registration status doesn't match")
.that(entryValue.getRegistrationStatus())
.isEqualTo(PersistedFid.RegistrationStatus.PENDING);

// Waiting for Task that registers FID on the FIS Servers
executor.awaitTermination(500, TimeUnit.MILLISECONDS);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ciarand I was able to eliminate sleep entirely. Instead awaiting for the executor to complete. I am not sure if you saw these changes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice


PersistedFidEntry updatedFidEntry = persistedFid.readPersistedFidEntryValue();
assertWithMessage("Persisted Fid doesn't match")
.that(updatedFidEntry.getFirebaseInstallationId())
.isEqualTo(TEST_FID_1);
assertWithMessage("Registration status doesn't match")
.that(updatedFidEntry.getRegistrationStatus())
.isEqualTo(PersistedFid.RegistrationStatus.REGISTERED);
}

@Test
public void testGetId_multipleCalls_sameFIDReturned() throws Exception {
FirebaseInstallations firebaseInstallations =
new FirebaseInstallations(
mockClock, executor, firebaseApp, backendClientReturnsOk, persistedFid, mockUtils);

// No exception, means success.
assertWithMessage("getId Task fails.")
.that(Tasks.await(firebaseInstallations.getId()))
.isNotEmpty();
PersistedFidEntry entryValue = persistedFid.readPersistedFidEntryValue();
assertWithMessage("Persisted Fid doesn't match")
.that(entryValue.getFirebaseInstallationId())
.isEqualTo(TEST_FID_1);
assertWithMessage("Registration status doesn't match")
.that(entryValue.getRegistrationStatus())
.isEqualTo(PersistedFid.RegistrationStatus.PENDING);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what prevents the FID from being registered at this point in the test code?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, nothing. I thought about it. But the test runs have been consistent with registration taking some time. Is there a better way to test it or do i skip the status check altogether.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ciarand Your thoughts.


Tasks.await(firebaseInstallations.getId());

// Waiting for Task that registers FID on the FIS Servers
executor.awaitTermination(500, TimeUnit.MILLISECONDS);

PersistedFidEntry updatedFidEntry = persistedFid.readPersistedFidEntryValue();
assertWithMessage("Persisted Fid doesn't match")
.that(updatedFidEntry.getFirebaseInstallationId())
.isEqualTo(TEST_FID_1);
assertWithMessage("Registration status doesn't match")
.that(updatedFidEntry.getRegistrationStatus())
.isEqualTo(PersistedFid.RegistrationStatus.REGISTERED);
}

@Test
public void testGetId_PersistedFidOk_BackendError() throws Exception {
FirebaseInstallations firebaseInstallations =
new FirebaseInstallations(
mockClock, executor, firebaseApp, backendClientReturnsError, persistedFid, mockUtils);

Tasks.await(firebaseInstallations.getId());

PersistedFidEntry entryValue = persistedFid.readPersistedFidEntryValue();
assertWithMessage("Persisted Fid doesn't match")
.that(entryValue.getFirebaseInstallationId())
.isEqualTo(TEST_FID_1);
assertWithMessage("Registration Fid doesn't match")
.that(entryValue.getRegistrationStatus())
.isEqualTo(PersistedFid.RegistrationStatus.PENDING);

// Waiting for Task that registers FID on the FIS Servers
executor.awaitTermination(500, TimeUnit.MILLISECONDS);

PersistedFidEntry updatedFidEntry = persistedFid.readPersistedFidEntryValue();
assertWithMessage("Persisted Fid doesn't match")
.that(updatedFidEntry.getFirebaseInstallationId())
.isEqualTo(TEST_FID_1);
assertWithMessage("Registration Fid doesn't match")
.that(updatedFidEntry.getRegistrationStatus())
.isEqualTo(PersistedFid.RegistrationStatus.REGISTER_ERROR);
}

@Test
public void testGetId_PersistedFidError_BackendOk() throws InterruptedException {
FirebaseInstallations firebaseInstallations =
new FirebaseInstallations(
mockClock,
executor,
firebaseApp,
backendClientReturnsOk,
persistedFidReturnsError,
mockUtils);

// Expect exception
try {
Tasks.await(firebaseInstallations.getId());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

out of curiosity:
Does this framework not have "assertThrows"?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There isnt one. However, I found RC using one by adding Asssert in Test Utils.

https://github.com/firebase/firebase-android-sdk/blob/5301121df4727b357293b3b7de00555362f90170/firebase-config/src/test/java/com/google/firebase/remoteconfig/testutil/Assert.java

Rest of the firebase-android-sdk teams have handled the same way as me.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fail();
} catch (ExecutionException expected) {
Throwable cause = expected.getCause();
assertWithMessage("Exception class doesn't match")
.that(cause)
.isInstanceOf(FirebaseInstallationsException.class);
assertWithMessage("Exception status doesn't match")
.that(((FirebaseInstallationsException) cause).getStatus())
.isEqualTo(FirebaseInstallationsException.Status.CLIENT_ERROR);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.installations;

public final class FisAndroidTestConstants {
public static final String TEST_FID_1 = "cccccccccccccccccccccc";

public static final String TEST_PROJECT_ID = "777777777777";

public static final String TEST_AUTH_TOKEN = "fis.auth.token";

public static final String TEST_REFRESH_TOKEN = "1:test-refresh-token";

public static final String TEST_APP_ID_1 = "1:123456789:android:abcdef";
public static final String TEST_APP_ID_2 = "1:987654321:android:abcdef";

public static final long TEST_TOKEN_EXPIRATION_TIMESTAMP = 1000L;

public static final long TEST_CREATION_TIMESTAMP_1 = 2000L;
public static final long TEST_CREATION_TIMESTAMP_2 = 2000L;
}

This file was deleted.

Loading