Skip to content

Commit 36e728a

Browse files
Adding the Firebase Storage Unit Test App (#303)
1 parent bae84c7 commit 36e728a

File tree

109 files changed

+2556
-1017
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

109 files changed

+2556
-1017
lines changed

firebase-storage/README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,40 @@ Storage, to access the same files.
1111
All Gradle commands should be run from the source root (which is one level up
1212
from this folder). See the README.md in the source root for instructions on
1313
publishing/testing Firebase Storage.
14+
15+
## Unit Tests
16+
17+
The Firebase Storage Unit tests exercise the public API endpoints and mock the associated network
18+
activity. For each test, the unit tests verify all network traffic and state changes by comparing
19+
them to pre-recorded activity. The network traffic as well as the expected states are defined in the
20+
resource files included under `src/test/resources/activitylogs`.
21+
22+
To add new tests, use the the test app provided under `../firebase-storage-app`. You
23+
can run this test app in a simulator or on a device. The app's various test cases can be activated
24+
through the UI and record all network traffic and state transitions. After each test run, the
25+
captured network traffic and all state changes are written to the app's local storage directory. You
26+
can use this captured state to add additional unit tests for the storage client.
27+
28+
The app reads both from the network and from the device. To run existing test cases, you need to
29+
upload the files under `src/test/resources/assets` to the Storage bucket of your Firebase project.
30+
You can use [gsutil](https://cloud.google.com/storage/docs/gsutil) or the
31+
[Firebase Console](https://console.firebase.google.com) for this. Furthermore, to make these file
32+
available locally, they should also be copied to device's local storage. The expected Storage
33+
location is shown when you run a test that requires a local file (e.g. an upload tests).
34+
35+
When a test run finishes, the test app displays the location of the test output. These files need to
36+
be copied to `src/test/resources/activitylogs` before the can be used in unit tests. Note that the
37+
captured network traffic in these files includes your Authentication Tokens and your Project ID,
38+
which need to be replaced.
39+
40+
To supply the fake authentication token used by the Unit test runner, replace any value for the
41+
`x-firebase-gmpid` request property with `fooey`. The expected header format is:
42+
43+
```
44+
setRequestProperty:x-firebase-gmpid,fooey
45+
```
46+
47+
Similarly, replace any Firebase Storage URLs (such as
48+
`https://firebasestorage.googleapis.com/v0/b/{PROJECT}.appspot.com/o/...`) with
49+
`https://firebasestorage.googleapis.com/v0/b/fooey.appspot.com/o/...`
50+

firebase-storage/firebase-storage.gradle

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ android {
3838
sourceSets {
3939
androidTest {
4040
java {
41+
srcDir 'src/androidTest'
4142
srcDir 'src/testUtil'
4243
//We need this since FirebaseApp rule is externalized
4344
//TODO(ashwinraghav) b/113079738
@@ -47,7 +48,7 @@ android {
4748

4849
test {
4950
java {
50-
srcDir 'src/testUtil'
51+
srcDir 'src/testUtil/java'
5152
//We need this since FirebaseApp rule is externalized
5253
//TODO(ashwinraghav) b/113079738
5354
srcDir '../firebase-common/src/testUtil'
@@ -86,3 +87,11 @@ dependencies {
8687
testImplementation "com.google.truth:truth:$googleTruthVersion"
8788
testImplementation 'com.android.support.test:rules:1.0.2'
8889
}
90+
91+
// ==========================================================================
92+
// Copy from here down if you want to use the google-services plugin in your
93+
// androidTest integration tests.
94+
// ==========================================================================
95+
ext.packageName = "com.google.firebase.storage"
96+
apply from: '../gradle/googleServices.gradle'
97+

firebase-storage/src/androidTest/AndroidManifest.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
<!-- limitations under the License. -->
1414

1515
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
16-
package="com.google.firebase.storage.integration">
16+
package="com.google.firebase.storage">
1717
<!--Although the *SdkVersion is captured in gradle build files, this is required for non gradle builds-->
1818
<!--<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="23" />-->
1919
<uses-permission android:name="android.permission.INTERNET"/>
@@ -25,5 +25,5 @@
2525

2626
<instrumentation
2727
android:name="androidx.test.runner.AndroidJUnitRunner"
28-
android:targetPackage="com.google.firebase.storage.integration" />
28+
android:targetPackage="com.google.firebase.storage" />
2929
</manifest>
Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,25 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
package com.google.firebase.storage.integration;
15+
package com.google.firebase.storage;
1616

1717
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
1818
import static com.google.common.truth.Truth.assertThat;
1919

2020
import android.net.Uri;
2121
import android.os.Environment;
22+
import android.support.annotation.NonNull;
2223
import android.support.test.InstrumentationRegistry;
2324
import android.support.test.rule.GrantPermissionRule;
2425
import android.support.test.runner.AndroidJUnit4;
2526
import com.google.android.gms.tasks.Task;
2627
import com.google.android.gms.tasks.Tasks;
2728
import com.google.firebase.FirebaseApp;
28-
import com.google.firebase.FirebaseOptions;
29-
import com.google.firebase.storage.FileDownloadTask;
30-
import com.google.firebase.storage.FirebaseStorage;
31-
import com.google.firebase.storage.StorageMetadata;
32-
import com.google.firebase.storage.StorageReference;
3329
import com.google.firebase.storage.StreamDownloadTask.TaskSnapshot;
3430
import java.io.File;
3531
import java.io.IOException;
3632
import java.io.InputStream;
33+
import java.util.UUID;
3734
import java.util.concurrent.ExecutionException;
3835
import org.junit.Before;
3936
import org.junit.Rule;
@@ -47,40 +44,38 @@ public class IntegrationTest {
4744
GrantPermissionRule.grant(WRITE_EXTERNAL_STORAGE);
4845

4946
// The file size in bytes of "1.1mb.dat"
50-
private static final int LARGE_FILE_SIZE = 1100000;
47+
private static final int LARGE_FILE_SIZE_BYTES = 10 * 1024;
5148

52-
private static FirebaseStorage storageClient;
49+
private FirebaseStorage storageClient;
50+
51+
private final String randomPrefix = UUID.randomUUID().toString();
5352

5453
@Before
55-
public void before() {
54+
public void before() throws ExecutionException, InterruptedException {
5655
if (storageClient == null) {
57-
FirebaseApp app =
58-
FirebaseApp.initializeApp(
59-
InstrumentationRegistry.getContext(),
60-
new FirebaseOptions.Builder()
61-
.setApplicationId("1:196403931065:android:60949756fbe381ea")
62-
.setApiKey("AIzaSyDMAScliyLx7F0NPDEJi1QmyCgHIAODrlU")
63-
.setStorageBucket("project-5516366556574091405.appspot.com")
64-
.build());
56+
FirebaseApp app = FirebaseApp.initializeApp(InstrumentationRegistry.getContext());
6557
storageClient = FirebaseStorage.getInstance(app);
58+
59+
Tasks.await(getReference("metadata.dat").putBytes(new byte[0]));
60+
Tasks.await(getReference("download.dat").putBytes(new byte[LARGE_FILE_SIZE_BYTES]));
6661
}
6762
}
6863

6964
@Test
7065
public void downloadFile() throws ExecutionException, InterruptedException, IOException {
71-
File tempFile = new File(Environment.getExternalStorageDirectory(), "1.1mb.dat");
66+
File tempFile = new File(Environment.getExternalStorageDirectory(), "download.dat");
7267

7368
FileDownloadTask.TaskSnapshot fileTask =
74-
Tasks.await(storageClient.getReference("1.1mb.dat").getFile(tempFile));
69+
Tasks.await(getReference("download.dat").getFile(tempFile));
7570

7671
assertThat(tempFile.exists()).isTrue();
77-
assertThat(tempFile.length()).isEqualTo(LARGE_FILE_SIZE);
78-
assertThat(fileTask.getBytesTransferred()).isEqualTo(LARGE_FILE_SIZE);
72+
assertThat(tempFile.length()).isEqualTo(LARGE_FILE_SIZE_BYTES);
73+
assertThat(fileTask.getBytesTransferred()).isEqualTo(LARGE_FILE_SIZE_BYTES);
7974
}
8075

8176
@Test
8277
public void streamFile() throws ExecutionException, InterruptedException, IOException {
83-
TaskSnapshot streamTask = Tasks.await(storageClient.getReference("1.1mb.dat").getStream());
78+
TaskSnapshot streamTask = Tasks.await(getReference("download.dat").getStream());
8479

8580
byte[] data = new byte[255];
8681

@@ -92,13 +87,13 @@ public void streamFile() throws ExecutionException, InterruptedException, IOExce
9287
totalBytesRead += currentBytesRead;
9388
}
9489

95-
assertThat(totalBytesRead).isEqualTo(LARGE_FILE_SIZE);
90+
assertThat(totalBytesRead).isEqualTo(LARGE_FILE_SIZE_BYTES);
9691
}
9792

9893
@Test
9994
public void uploadBytesThenGetDownloadUrl() throws ExecutionException, InterruptedException {
10095
byte[] data = new byte[] {1, 2, 3};
101-
StorageReference reference = storageClient.getReference("bytes.dat");
96+
StorageReference reference = getReference("upload.dat");
10297

10398
Uri downloadUrl =
10499
Tasks.await(
@@ -123,15 +118,20 @@ public void updateMetadata() throws ExecutionException, InterruptedException {
123118
.build();
124119

125120
Task<StorageMetadata> storageMetadataTask =
126-
storageClient.getReference("metadata.dat").updateMetadata(randomMetadata);
121+
getReference("metadata.dat").updateMetadata(randomMetadata);
127122
StorageMetadata metadata = Tasks.await(storageMetadataTask);
128123

129124
assertThat(metadata.getCustomMetadata("rand"))
130125
.isEqualTo(randomMetadata.getCustomMetadata("rand"));
131126

132-
metadata = Tasks.await(storageClient.getReference("metadata.dat").getMetadata());
127+
metadata = Tasks.await(getReference("metadata.dat").getMetadata());
133128

134129
assertThat(metadata.getCustomMetadata("rand"))
135130
.isEqualTo(randomMetadata.getCustomMetadata("rand"));
136131
}
132+
133+
@NonNull
134+
private StorageReference getReference(String filename) {
135+
return storageClient.getReference(randomPrefix + "/" + filename);
136+
}
137137
}

firebase-storage/src/test/java/com/google/firebase/storage/DownloadTest.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,9 +111,7 @@ public void streamDownloadStateVerification() throws Exception {
111111
NetworkLayerMock.ensureNetworkMock("streamDownload", true);
112112
final Semaphore semaphore = new Semaphore(0);
113113

114-
StorageReference storage =
115-
FirebaseStorage.getInstance()
116-
.getReferenceFromUrl("gs://project-5516366556574091405.appspot.com/image.jpg");
114+
StorageReference storage = FirebaseStorage.getInstance().getReference("image.jpg");
117115

118116
final AtomicLong bytesDownloaded = new AtomicLong();
119117
final AtomicLong bytesTransferred = new AtomicLong();

firebase-storage/src/test/java/com/google/firebase/storage/PathingTest.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,7 @@ public void setUp() throws Exception {
5151
app =
5252
FirebaseApp.initializeApp(
5353
RuntimeEnvironment.application.getApplicationContext(),
54-
new FirebaseOptions.Builder()
55-
.setApiKey("AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM")
56-
.setApplicationId("fooey")
57-
.build());
54+
new FirebaseOptions.Builder().setApiKey("fooey").setApplicationId("fooey").build());
5855
}
5956

6057
@After

firebase-storage/src/test/java/com/google/firebase/storage/StorageReferenceTest.java

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public void retainsProperties() throws Exception {
7676
@Test
7777
public void defaultInitTest() throws Exception {
7878
StorageReference ref = FirebaseStorage.getInstance().getReference();
79-
Assert.assertEquals("gs://project-5516366556574091405.appspot.com/", ref.toString());
79+
Assert.assertEquals("gs://fooey.appspot.com/", ref.toString());
8080
}
8181

8282
@Test
@@ -88,18 +88,13 @@ public void initWithCustomUriTest() throws Exception {
8888
@Test
8989
public void allStorageObjectsAreEqual() throws Exception {
9090
FirebaseStorage original = FirebaseStorage.getInstance();
91-
FirebaseStorage copy =
92-
FirebaseStorage.getInstance("gs://project-5516366556574091405.appspot.com/");
91+
FirebaseStorage copy = FirebaseStorage.getInstance("gs://fooey.appspot.com/");
9392
Assert.assertSame(copy, original); // Pointer comparison intended
94-
copy = FirebaseStorage.getInstance("gs://project-5516366556574091405.appspot.com");
93+
copy = FirebaseStorage.getInstance("gs://fooey.appspot.com");
9594
Assert.assertSame(copy, original);
96-
copy =
97-
FirebaseStorage.getInstance(
98-
FirebaseApp.getInstance(), "gs://project-5516366556574091405.appspot.com/");
95+
copy = FirebaseStorage.getInstance(FirebaseApp.getInstance(), "gs://fooey.appspot.com/");
9996
Assert.assertSame(copy, original);
100-
Assert.assertEquals(
101-
"gs://project-5516366556574091405.appspot.com/",
102-
copy.getReference().getStorageUri().toString());
97+
Assert.assertEquals("gs://fooey.appspot.com/", copy.getReference().getStorageUri().toString());
10398
}
10499

105100
@Test
@@ -116,7 +111,7 @@ public void initWithBadUriTest() throws Exception {
116111
@Test
117112
public void initWithPathTest() throws Exception {
118113
try {
119-
FirebaseStorage.getInstance("gs://project-5516366556574091405.appspot.com/foo");
114+
FirebaseStorage.getInstance("gs://fooey.appspot.com/foo");
120115
Assert.fail("Expected exception");
121116
} catch (IllegalArgumentException e) {
122117
Assert.assertEquals("The storage Uri cannot contain a path element.", e.getMessage());
@@ -139,14 +134,13 @@ public void initWithDefaultAndCustomUriTest() throws Exception {
139134
StorageReference defaultRef = FirebaseStorage.getInstance().getReference();
140135
StorageReference customRef =
141136
FirebaseStorage.getInstance("gs://foo-bar.appspot.com/").getReference();
142-
Assert.assertEquals("gs://project-5516366556574091405.appspot.com/", defaultRef.toString());
137+
Assert.assertEquals("gs://fooey.appspot.com/", defaultRef.toString());
143138
Assert.assertEquals("gs://foo-bar.appspot.com/", customRef.toString());
144139
}
145140

146141
@Test(expected = IllegalArgumentException.class)
147142
public void badInitTest() throws Exception {
148-
FirebaseStorage.getInstance()
149-
.getReference("gs://project-5516366556574091405.appspot.com/child");
143+
FirebaseStorage.getInstance().getReference("gs://fooey.appspot.com/child");
150144
}
151145

152146
@Test
@@ -161,15 +155,15 @@ public void initWithApp() throws Exception {
161155
FirebaseApp.initializeApp(
162156
RuntimeEnvironment.application.getApplicationContext(),
163157
new FirebaseOptions.Builder()
164-
.setApiKey("AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM")
158+
.setApiKey("fooey")
165159
.setApplicationId("fooey")
166-
.setStorageBucket("benwu-test2.storage.firebase.com")
160+
.setStorageBucket("fooey.storage.firebase.com")
167161
.build(),
168162
"app2");
169163

170164
StorageReference ref =
171165
FirebaseStorage.getInstance(app2)
172-
.getReferenceFromUrl("gs://benwu-test2.storage.firebase.com/child");
166+
.getReferenceFromUrl("gs://fooey.storage.firebase.com/child");
173167

174168
Assert.assertEquals("child", ref.getName());
175169
}
@@ -188,26 +182,24 @@ public void badInitWithApp2() throws Exception {
188182
@Test
189183
public void urlUriEquivalence() throws Exception {
190184
StorageReference ref =
191-
FirebaseStorage.getInstance()
192-
.getReferenceFromUrl("gs://project-5516366556574091405.appspot.com/child/image.png");
185+
FirebaseStorage.getInstance().getReferenceFromUrl("gs://fooey.appspot.com/child/image.png");
193186
StorageReference ref2 =
194187
FirebaseStorage.getInstance()
195188
.getReferenceFromUrl(
196-
"https://firebasestorage.googleapis.com/v0/b/project-"
197-
+ "5516366556574091405.appspot.com/o/child%2Fimage.png?alt=media&"
189+
"https://firebasestorage.googleapis.com/v0/b/"
190+
+ "fooey.appspot.com/o/child%2Fimage.png?alt=media&"
198191
+ "token=42a1b22e-5e56-4337-bd61-f177233b40bc");
199192

200193
Assert.assertEquals(ref, ref2);
201194
Assert.assertEquals("/child/image.png", ref.getPath());
202-
Assert.assertEquals("project-5516366556574091405.appspot.com", ref.getBucket());
195+
Assert.assertEquals("fooey.appspot.com", ref.getBucket());
203196
}
204197

205198
@Test
206199
public void badGSUriScheme() throws Exception {
207200
boolean thrown = false;
208201
try {
209-
FirebaseStorage.getInstance()
210-
.getReferenceFromUrl("gs2://project-5516366556574091405.appspot.com/child/image.png");
202+
FirebaseStorage.getInstance().getReferenceFromUrl("gs2://fooey.appspot.com/child/image.png");
211203
} catch (IllegalArgumentException e) {
212204
thrown = true;
213205
}
@@ -244,7 +236,7 @@ public void badURL1() throws Exception {
244236
try {
245237
FirebaseStorage.getInstance()
246238
.getReferenceFromUrl(
247-
"https://www.googleapis.com/v0/b/project-5516366556574091405.appspot"
239+
"https://www.googleapis.com/v0/b/fooey.appspot"
248240
+ ".com/o/child%2Fimage.png?alt=media&token=42a1b22e-5e56-4337-bd61-f177233b40bc");
249241
} catch (IllegalArgumentException e) {
250242
thrown = true;

firebase-storage/src/test/java/com/google/firebase/storage/TestUtil.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ static FirebaseApp createApp() {
3232
return FirebaseApp.initializeApp(
3333
RuntimeEnvironment.application.getApplicationContext(),
3434
new FirebaseOptions.Builder()
35-
.setApiKey("AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM")
35+
.setApiKey("fooey")
3636
.setApplicationId("fooey")
37-
.setStorageBucket("project-5516366556574091405.appspot.com")
37+
.setStorageBucket("fooey.appspot.com")
3838
.build());
3939
// Point to staging:
4040
// NetworkRequest.sNetworkRequestUrl = "https://staging-firebasestorage.sandbox.googleapis"
@@ -47,19 +47,19 @@ static void verifyTaskStateChanges(
4747
ClassLoader classLoader = TestUtil.class.getClassLoader();
4848

4949
System.out.println("Verifying task file.");
50-
String filename = "assets/" + testName + "_task.txt";
50+
String filename = "activitylogs/" + testName + "_task.txt";
5151
InputStream inputStream = classLoader.getResourceAsStream(filename);
5252
verifyTaskStateChanges(inputStream, response.mainTask.toString());
5353

5454
System.out.println("Verifying background file.");
55-
filename = "assets/" + testName + "_background.txt";
55+
filename = "activitylogs/" + testName + "_background.txt";
5656
inputStream = classLoader.getResourceAsStream(filename);
5757
verifyTaskStateChanges(inputStream, response.backgroundTask.toString());
5858
}
5959

6060
static void verifyTaskStateChanges(String testName, String contents) {
6161
ClassLoader classLoader = TestUtil.class.getClassLoader();
62-
String filename = "assets/" + testName + "_task.txt";
62+
String filename = "activitylogs/" + testName + "_task.txt";
6363

6464
InputStream inputStream = classLoader.getResourceAsStream(filename);
6565
verifyTaskStateChanges(inputStream, contents);

0 commit comments

Comments
 (0)