aboutsummaryrefslogtreecommitdiffhomepage
path: root/Example/Database/Tests/Integration/FIRDatabaseTests.m
blob: 27bf9d470a8fec193a344f562488a5037cdc5a31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
 * Copyright 2017 Google
 *
 * 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.
 */

#import <XCTest/XCTest.h>
#import "FirebaseCore/FIRApp.h"
#import "FIRDatabaseReference.h"
#import "FIRDatabaseReference_Private.h"
#import "FIRDatabase.h"
#import "FIRDatabaseConfig_Private.h"
#import "FIROptions.h"
#import "FTestHelpers.h"
#import "FMockStorageEngine.h"
#import "FTestBase.h"
#import "FTestHelpers.h"
#import "FIRFakeApp.h"

@interface FIRDatabaseTests : FTestBase

@end

static const NSInteger kFErrorCodeWriteCanceled = 3;
static NSString *kFirebaseTestAltNamespace = @"https://foobar.firebaseio.com";

@implementation FIRDatabaseTests

- (void) testFIRDatabaseForNilApp {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
    XCTAssertThrowsSpecificNamed([FIRDatabase databaseForApp:nil], NSException, @"InvalidFIRApp");
#pragma clang diagnostic pop
}

- (void) testDatabaseForApp {
    FIRDatabase *database = [self databaseForURL:self.databaseURL];
    XCTAssertEqualObjects(self.databaseURL, [database reference].URL);
}

- (void) testDatabaseForAppWithInvalidURLs {
    XCTAssertThrows([self databaseForURL:nil]);
    XCTAssertThrows([self databaseForURL:@"not-a-url"]);
    XCTAssertThrows([self databaseForURL:@"http://fblocal.com"]);
    XCTAssertThrows([self databaseForURL:@"http://x.example.com/paths/are/bad"]);
}

- (void)testDatabaseForAppWithURL {
    id app = [[FIRFakeApp alloc] initWithName:@"testDatabaseForAppWithURL" URL:kFirebaseTestAltNamespace];
    FIRDatabase *database = [FIRDatabase databaseForApp:app URL:@"http://foo.bar.com"];
    XCTAssertEqualObjects(@"https://foo.bar.com", [database reference].URL);
}

- (void)testDatabaseForAppWithURLAndPort {
    id app = [[FIRFakeApp alloc] initWithName:@"testDatabaseForAppWithURLAndPort"
                                          URL:kFirebaseTestAltNamespace];
    FIRDatabase *database = [FIRDatabase databaseForApp:app URL:@"http://foo.bar.com:80"];
    XCTAssertEqualObjects(@"http://foo.bar.com:80", [database reference].URL);
}

- (void)testDatabaseForAppWithHttpsURL {
    id app = [[FIRFakeApp alloc] initWithName:@"testDatabaseForAppWithHttpsURL"
                                          URL:kFirebaseTestAltNamespace];
    FIRDatabase *database = [FIRDatabase databaseForApp:app URL:@"https://foo.bar.com"];
    XCTAssertEqualObjects(@"https://foo.bar.com", [database reference].URL);
}

- (void)testDifferentInstanceForAppWithURL {
    id app = [[FIRFakeApp alloc] initWithName:@"testDifferentInstanceForAppWithURL"
                                          URL:kFirebaseTestAltNamespace];
    FIRDatabase *database1 = [FIRDatabase databaseForApp:app URL:@"https://foo1.bar.com"];
    FIRDatabase *database2 = [FIRDatabase databaseForApp:app URL:@"https://foo1.bar.com/"];
    FIRDatabase *database3 = [FIRDatabase databaseForApp:app URL:@"https://foo2.bar.com"];
    XCTAssertEqual(database1, database2);
    XCTAssertNotEqual(database1, database3);
}

- (void)testDatabaseForAppWithInvalidCustomURLs {
    id app = [[FIRFakeApp alloc] initWithName:@"testDatabaseForAppWithInvalidCustomURLs"
                                        URL:kFirebaseTestAltNamespace];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
    XCTAssertThrows([FIRDatabase databaseForApp:app URL:nil]);
#pragma clang diagnostic pop
    XCTAssertThrows([FIRDatabase databaseForApp:app URL:@"not-a-url"]);
    XCTAssertThrows([FIRDatabase databaseForApp:app URL:@"http://fblocal.com"]);
    XCTAssertThrows([FIRDatabase databaseForApp:app URL:@"http://x.fblocal.com:9000/paths/are/bad"]);
}

- (void) testDeleteDatabase {
    // Set up a custom FIRApp with a custom database based on it.
    FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:@"1:123:ios:123abc"
                                                      GCMSenderID:@"gcm_sender_id"];
    options.databaseURL = self.databaseURL;
    NSString *customAppName = @"MyCustomApp";
    [FIRApp configureWithName:customAppName options:options];
    FIRApp *customApp = [FIRApp appNamed:customAppName];
    FIRDatabase *customDatabase = [FIRDatabase databaseForApp:customApp];
    XCTAssertNotNil(customDatabase);

    // Delete the custom app and wait for it to be done.
    XCTestExpectation *customAppDeletedExpectation =
        [self expectationWithDescription:@"Deleting the custom app should be successful."];
    [customApp deleteApp:^(BOOL success) {
        // The app shouldn't exist anymore, ensure that the databaseForApp throws.
        XCTAssertThrows([FIRDatabase databaseForApp:[FIRApp appNamed:customAppName]]);

        [customAppDeletedExpectation fulfill];
    }];

    // Wait for the custom app to be deleted.
    [self waitForExpectations:@[customAppDeletedExpectation] timeout:2];

    // Configure the app again, then grab a reference to the database. Assert it's different.
    [FIRApp configureWithName:customAppName options:options];
    FIRApp *secondCustomApp = [FIRApp appNamed:customAppName];
    FIRDatabase *secondCustomDatabase = [FIRDatabase databaseForApp:secondCustomApp];
    XCTAssertNotNil(secondCustomDatabase);
    XCTAssertNotEqualObjects(customDatabase, secondCustomDatabase);
}

- (void) testReferenceWithPath {
    FIRDatabase *db = [self defaultDatabase];
    NSString *expectedURL = [NSString stringWithFormat:@"%@/foo", self.databaseURL];
    XCTAssertEqualObjects(expectedURL, [db referenceWithPath:@"foo"].URL);
}

- (void) testReferenceFromURLWithEmptyPath {
    FIRDatabaseReference *ref = [[self defaultDatabase] referenceFromURL:self.databaseURL];
    XCTAssertEqualObjects(self.databaseURL, ref.URL);
}

- (void) testReferenceFromURLWithPath {
    NSString *url = [NSString stringWithFormat:@"%@/foo/bar", self.databaseURL];
    FIRDatabaseReference *ref = [[self defaultDatabase] referenceFromURL:url];
    XCTAssertEqualObjects(url, ref.URL);
}

- (void) testReferenceFromURLWithWrongURL {
    NSString *url = [NSString stringWithFormat:@"%@/foo/bar", @"https://foobar.firebaseio.com"];
    XCTAssertThrows([[self defaultDatabase] referenceFromURL:url]);
}

- (void) testReferenceEqualityForFIRDatabase {
    FIRDatabase *db1 = [self databaseForURL:self.databaseURL name:@"db1"];
    FIRDatabase *db2 = [self databaseForURL:self.databaseURL name:@"db2"];
    FIRDatabase *altDb = [self databaseForURL:self.databaseURL name:@"altDb"];
    FIRDatabase *wrongHostDb = [self databaseForURL:@"http://tests.example.com"];

    FIRDatabaseReference *testRef1 = [db1 reference];
    FIRDatabaseReference *testRef2 = [db1 referenceWithPath:@"foo"];
    FIRDatabaseReference *testRef3 = [altDb reference];
    FIRDatabaseReference *testRef4 = [wrongHostDb reference];
    FIRDatabaseReference *testRef5 = [db2 reference];
    FIRDatabaseReference *testRef6 = [db2 reference];

    // Referential equality
    XCTAssertTrue(testRef1.database == testRef2.database);
    XCTAssertFalse(testRef1.database == testRef3.database);
    XCTAssertFalse(testRef1.database == testRef4.database);
    XCTAssertFalse(testRef1.database == testRef5.database);
    XCTAssertFalse(testRef1.database == testRef6.database);

    // references from same FIRDatabase same identical .database references.
    XCTAssertTrue(testRef5.database == testRef6.database);

    [db1 goOffline];
    [db2 goOffline];
    [altDb goOffline];
    [wrongHostDb goOffline];
}

- (FIRDatabaseReference *)rootRefWithEngine:(id<FStorageEngine>)engine name:(NSString *)name {
    FIRDatabaseConfig *config = [FIRDatabaseConfig configForName:name];
    config.persistenceEnabled = YES;
    config.forceStorageEngine = engine;
    return [[FIRDatabaseReference alloc] initWithConfig:config];
}

- (void) testPurgeWritesPurgesAllWrites {
    FMockStorageEngine *engine = [[FMockStorageEngine alloc] init];
    FIRDatabaseReference *ref = [self rootRefWithEngine:engine name:@"purgeWritesPurgesAllWrites"];
    FIRDatabase *database = ref.database;

    [database goOffline];

    [[ref childByAutoId] setValue:@"test-value-1"];
    [[ref childByAutoId] setValue:@"test-value-2"];
    [[ref childByAutoId] setValue:@"test-value-3"];
    [[ref childByAutoId] setValue:@"test-value-4"];

    [self waitForEvents:ref];

    XCTAssertEqual(engine.userWrites.count, (NSUInteger)4);

    [database purgeOutstandingWrites];
    [self waitForEvents:ref];
    XCTAssertEqual(engine.userWrites.count, (NSUInteger)0);

    [database goOnline];
}

- (void) testPurgeWritesAreCanceledInOrder {
    FMockStorageEngine *engine = [[FMockStorageEngine alloc] init];
    FIRDatabaseReference *ref = [self rootRefWithEngine:engine name:@"purgeWritesAndCanceledInOrder"];
    FIRDatabase *database = ref.database;

    [database goOffline];

    NSMutableArray *order = [NSMutableArray array];

    [[ref childByAutoId] setValue:@"test-value-1" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [order addObject:@"1"];
    }];
    [[ref childByAutoId] setValue:@"test-value-2" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [order addObject:@"2"];
    }];
    [[ref childByAutoId] setValue:@"test-value-3" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [order addObject:@"3"];
    }];
    [[ref childByAutoId] setValue:@"test-value-4" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [order addObject:@"4"];
    }];

    [self waitForEvents:ref];

    XCTAssertEqual(engine.userWrites.count, (NSUInteger)4);

    [database purgeOutstandingWrites];
    [self waitForEvents:ref];
    XCTAssertEqual(engine.userWrites.count, (NSUInteger)0);
    XCTAssertEqualObjects(order, (@[@"1", @"2", @"3", @"4"]));

    [database goOnline];
}

- (void)testPurgeWritesCancelsOnDisconnects {
    FMockStorageEngine *engine = [[FMockStorageEngine alloc] init];
    FIRDatabaseReference *ref = [self rootRefWithEngine:engine name:@"purgeWritesCancelsOnDisconnects"];
    FIRDatabase *database = ref.database;

    [database goOffline];

    NSMutableArray *events = [NSMutableArray array];

    [[ref childByAutoId] onDisconnectSetValue:@"test-value-1" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [events addObject:@"1"];
    }];

    [[ref childByAutoId] onDisconnectSetValue:@"test-value-2" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [events addObject:@"2"];
    }];

    [self waitForEvents:ref];

    [database purgeOutstandingWrites];

    [self waitForEvents:ref];

    XCTAssertEqualObjects(events, (@[@"1", @"2"]));
}

- (void) testPurgeWritesReraisesEvents {
    FMockStorageEngine *engine = [[FMockStorageEngine alloc] init];
    FIRDatabaseReference *ref = [[self rootRefWithEngine:engine name:@"purgeWritesReraiseEvents"] childByAutoId];
    FIRDatabase *database = ref.database;

    [self waitForCompletionOf:ref setValue:@{@"foo": @"foo-value", @"bar": @{@"qux": @"qux-value"}}];

    NSMutableArray *fooValues = [NSMutableArray array];
    NSMutableArray *barQuuValues = [NSMutableArray array];
    NSMutableArray *barQuxValues = [NSMutableArray array];
    NSMutableArray *cancelOrder = [NSMutableArray array];

    [[ref child:@"foo"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
        [fooValues addObject:snapshot.value];
    }];
    [[ref child:@"bar/quu"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
        [barQuuValues addObject:snapshot.value];
    }];
    [[ref child:@"bar/qux"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
        [barQuxValues addObject:snapshot.value];
    }];

    [database goOffline];

    [[ref child:@"foo"] setValue:@"new-foo-value" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        // This should be after we raised events
        XCTAssertEqualObjects(fooValues.lastObject, @"foo-value");
        [cancelOrder addObject:@"foo-1"];
    }];

    [[ref child:@"bar"] updateChildValues:@{@"quu": @"quu-value", @"qux": @"new-qux-value"}
                                     withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        // This should be after we raised events
        XCTAssertEqualObjects(barQuxValues.lastObject, @"qux-value");
        XCTAssertEqualObjects(barQuuValues.lastObject, [NSNull null]);
        [cancelOrder addObject:@"bar"];
    }];

    [[ref child:@"foo"] setValue:@"newest-foo-value" withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        // This should be after we raised events
        XCTAssertEqualObjects(fooValues.lastObject, @"foo-value");
        [cancelOrder addObject:@"foo-2"];
    }];

    [database purgeOutstandingWrites];

    [self waitForEvents:ref];

    XCTAssertEqualObjects(cancelOrder, (@[@"foo-1", @"bar", @"foo-2"]));
    XCTAssertEqualObjects(fooValues, (@[@"foo-value", @"new-foo-value", @"newest-foo-value", @"foo-value"]));
    XCTAssertEqualObjects(barQuuValues, (@[[NSNull null], @"quu-value", [NSNull null]]));
    XCTAssertEqualObjects(barQuxValues, (@[@"qux-value", @"new-qux-value", @"qux-value"]));

    [database goOnline];
    // Make sure we're back online and reconnected again
    [self waitForRoundTrip:ref];

    // No events should be reraised
    XCTAssertEqualObjects(cancelOrder, (@[@"foo-1", @"bar", @"foo-2"]));
    XCTAssertEqualObjects(fooValues, (@[@"foo-value", @"new-foo-value", @"newest-foo-value", @"foo-value"]));
    XCTAssertEqualObjects(barQuuValues, (@[[NSNull null], @"quu-value", [NSNull null]]));
    XCTAssertEqualObjects(barQuxValues, (@[@"qux-value", @"new-qux-value", @"qux-value"]));
}

- (void)testPurgeWritesCancelsTransactions {
    FMockStorageEngine *engine = [[FMockStorageEngine alloc] init];
    FIRDatabaseReference *ref = [[self rootRefWithEngine:engine name:@"purgeWritesCancelsTransactions"] childByAutoId];
    FIRDatabase *database = ref.database;

    NSMutableArray *events = [NSMutableArray array];

    [ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
        [events addObject:[NSString stringWithFormat:@"value-%@", snapshot.value]];
    }];

    // Make sure the first value event is fired
    [self waitForRoundTrip:ref];

    [database goOffline];

    [ref runTransactionBlock:^FIRTransactionResult *(FIRMutableData *currentData) {
        [currentData setValue:@"1"];
        return [FIRTransactionResult successWithValue:currentData];
    } andCompletionBlock:^(NSError *error, BOOL committed, FIRDataSnapshot *snapshot) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [events addObject:@"cancel-1"];
    }];

    [ref runTransactionBlock:^FIRTransactionResult *(FIRMutableData *currentData) {
        [currentData setValue:@"2"];
        return [FIRTransactionResult successWithValue:currentData];
    } andCompletionBlock:^(NSError *error, BOOL committed, FIRDataSnapshot *snapshot) {
        XCTAssertEqual(error.code, kFErrorCodeWriteCanceled);
        [events addObject:@"cancel-2"];
    }];

    [database purgeOutstandingWrites];

    [self waitForEvents:ref];

    // The order should really be cancel-1 then cancel-2, but meh, to difficult to implement currently...
    XCTAssertEqualObjects(events, (@[@"value-<null>", @"value-1", @"value-2", @"value-<null>", @"cancel-2", @"cancel-1"]));
}

- (void) testPersistenceEnabled {
    id app = [[FIRFakeApp alloc] initWithName:@"testPersistenceEnabled" URL:self.databaseURL];
    FIRDatabase *database = [FIRDatabase databaseForApp:app];
    database.persistenceEnabled = YES;
    XCTAssertTrue(database.persistenceEnabled);

    // Just do a dummy observe that should get null added to the persistent cache.
    FIRDatabaseReference *ref = [[database reference] childByAutoId];
    [self waitForValueOf:ref toBe:[NSNull null]];

    // Now go offline and since null is cached offline, our observer should still complete.
    [database goOffline];
    [self waitForValueOf:ref toBe:[NSNull null]];
}

- (void) testPersistenceCacheSizeBytes {
    id app = [[FIRFakeApp alloc] initWithName:@"testPersistenceCacheSizeBytes" URL:self.databaseURL];
    FIRDatabase *database = [FIRDatabase databaseForApp:app];
    database.persistenceEnabled = YES;

    int oneMegabyte = 1 * 1024 * 1024;

    XCTAssertThrows([database setPersistenceCacheSizeBytes: 1], @"Cache must be a least 1 MB.");
    XCTAssertThrows([database setPersistenceCacheSizeBytes: 101 * oneMegabyte],
                    @"Cache must be less than 100 MB.");
    database.persistenceCacheSizeBytes = 2 * oneMegabyte;
    XCTAssertEqual(2 * oneMegabyte, database.persistenceCacheSizeBytes);

    [database reference];  // Initialize database.

    XCTAssertThrows([database setPersistenceCacheSizeBytes: 3 * oneMegabyte],
                    @"Persistence can't be changed after initialization.");
    XCTAssertEqual(2 * oneMegabyte, database.persistenceCacheSizeBytes);
}

- (void) testCallbackQueue {
    id app = [[FIRFakeApp alloc] initWithName:@"testCallbackQueue" URL:self.databaseURL];
    FIRDatabase *database = [FIRDatabase databaseForApp:app];
    dispatch_queue_t callbackQueue = dispatch_queue_create("testCallbackQueue", NULL);
    database.callbackQueue = callbackQueue;
    XCTAssertEqual(callbackQueue, database.callbackQueue);

    __block BOOL done = NO;
    [database.reference.childByAutoId observeSingleEventOfType:FIRDataEventTypeValue
                                                     withBlock:^(FIRDataSnapshot *snapshot) {
        dispatch_assert_queue(callbackQueue);
        done = YES;
    }];
    WAIT_FOR(done);
    [database goOffline];
}

- (FIRDatabase *) defaultDatabase {
    return [self databaseForURL:self.databaseURL];
}

- (FIRDatabase *) databaseForURL:(NSString *)url {
    NSString *name = [NSString stringWithFormat:@"url:%@", url];
    return [self databaseForURL:url name:name];
}

- (FIRDatabase *) databaseForURL:(NSString *)url name:(NSString *)name {
    id app = [[FIRFakeApp alloc] initWithName:name URL:url];
    return [FIRDatabase databaseForApp:app];
}
@end