FIRServerTimestampTests.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <FirebaseFirestore/FirebaseFirestore.h>
  17. #import <XCTest/XCTest.h>
  18. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  19. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  20. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  21. #import "Firestore/Source/Core/FSTFirestoreClient.h"
  22. @interface FIRServerTimestampTests : FSTIntegrationTestCase
  23. @end
  24. @implementation FIRServerTimestampTests {
  25. // Data written in tests via set.
  26. NSDictionary *_setData;
  27. // Base and update data used for update tests.
  28. NSDictionary *_initialData;
  29. NSDictionary *_updateData;
  30. // A document reference to read and write to.
  31. FIRDocumentReference *_docRef;
  32. // Accumulator used to capture events during the test.
  33. FSTEventAccumulator *_accumulator;
  34. // Listener registration for a listener maintained during the course of the test.
  35. id<FIRListenerRegistration> _listenerRegistration;
  36. // Snapshot options that return the previous value for pending server timestamps.
  37. FIRSnapshotOptions *_returnPreviousValue;
  38. FIRSnapshotOptions *_returnEstimatedValue;
  39. }
  40. - (void)setUp {
  41. [super setUp];
  42. _returnPreviousValue =
  43. [FIRSnapshotOptions serverTimestampBehavior:FIRServerTimestampBehaviorPrevious];
  44. _returnEstimatedValue =
  45. [FIRSnapshotOptions serverTimestampBehavior:FIRServerTimestampBehaviorEstimate];
  46. // Data written in tests via set.
  47. _setData = @{
  48. @"a" : @42,
  49. @"when" : [FIRFieldValue fieldValueForServerTimestamp],
  50. @"deep" : @{@"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  51. };
  52. // Base and update data used for update tests.
  53. _initialData = @{ @"a" : @42 };
  54. _updateData = @{
  55. @"when" : [FIRFieldValue fieldValueForServerTimestamp],
  56. @"deep" : @{@"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  57. };
  58. _docRef = [self documentRef];
  59. _accumulator = [FSTEventAccumulator accumulatorForTest:self];
  60. _listenerRegistration = [_docRef addSnapshotListener:_accumulator.valueEventHandler];
  61. // Wait for initial nil snapshot to avoid potential races.
  62. FIRDocumentSnapshot *initialSnapshot = [_accumulator awaitEventWithName:@"initial event"];
  63. XCTAssertFalse(initialSnapshot.exists);
  64. }
  65. - (void)tearDown {
  66. [_listenerRegistration remove];
  67. [super tearDown];
  68. }
  69. #pragma mark - Test Helpers
  70. /** Returns the expected data, with the specified timestamp substituted in. */
  71. - (NSDictionary *)expectedDataWithTimestamp:(nullable id)timestamp {
  72. return @{ @"a" : @42, @"when" : timestamp, @"deep" : @{@"when" : timestamp} };
  73. }
  74. /** Writes _initialData and waits for the corresponding snapshot. */
  75. - (void)writeInitialData {
  76. [self writeDocumentRef:_docRef data:_initialData];
  77. FIRDocumentSnapshot *initialDataSnap = [_accumulator awaitEventWithName:@"Initial data event."];
  78. XCTAssertEqualObjects(initialDataSnap.data, _initialData);
  79. }
  80. /** Waits for a snapshot with local writes. */
  81. - (FIRDocumentSnapshot *)waitForLocalEvent {
  82. FIRDocumentSnapshot *snapshot;
  83. do {
  84. snapshot = [_accumulator awaitEventWithName:@"Local event."];
  85. } while (!snapshot.metadata.hasPendingWrites);
  86. return snapshot;
  87. }
  88. /** Waits for a snapshot that has no pending writes */
  89. - (FIRDocumentSnapshot *)waitForRemoteEvent {
  90. FIRDocumentSnapshot *snapshot;
  91. do {
  92. snapshot = [_accumulator awaitEventWithName:@"Remote event."];
  93. } while (snapshot.metadata.hasPendingWrites);
  94. return snapshot;
  95. }
  96. /** Verifies a snapshot containing _setData but with NSNull for the timestamps. */
  97. - (void)verifyTimestampsAreNullInSnapshot:(FIRDocumentSnapshot *)snapshot {
  98. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:[NSNull null]]);
  99. }
  100. /** Verifies a snapshot containing _setData but with a local estimate for the timestamps. */
  101. - (void)verifyTimestampsAreEstimatedInSnapshot:(FIRDocumentSnapshot *)snapshot {
  102. id timestamp = [snapshot valueForField:@"when" options:_returnEstimatedValue];
  103. XCTAssertTrue([timestamp isKindOfClass:[NSDate class]]);
  104. XCTAssertEqualObjects([snapshot dataWithOptions:_returnEstimatedValue],
  105. [self expectedDataWithTimestamp:timestamp]);
  106. }
  107. /**
  108. * Verifies a snapshot containing _setData but using the previous field value for server
  109. * timestamps.
  110. */
  111. - (void)verifyTimestampsInSnapshot:(FIRDocumentSnapshot *)snapshot
  112. fromPreviousSnapshot:(nullable FIRDocumentSnapshot *)previousSnapshot {
  113. if (previousSnapshot == nil) {
  114. XCTAssertEqualObjects([snapshot dataWithOptions:_returnPreviousValue],
  115. [self expectedDataWithTimestamp:[NSNull null]]);
  116. } else {
  117. XCTAssertEqualObjects([snapshot dataWithOptions:_returnPreviousValue],
  118. [self expectedDataWithTimestamp:previousSnapshot[@"when"]]);
  119. }
  120. }
  121. /** Verifies a snapshot containing _setData but with resolved server timestamps. */
  122. - (void)verifySnapshotWithResolvedTimestamps:(FIRDocumentSnapshot *)snapshot {
  123. XCTAssertTrue(snapshot.exists);
  124. NSDate *when = snapshot[@"when"];
  125. XCTAssertTrue([when isKindOfClass:[NSDate class]]);
  126. // Tolerate up to 10 seconds of clock skew between client and server.
  127. XCTAssertEqualWithAccuracy(when.timeIntervalSinceNow, 0, 10);
  128. // Validate the rest of the document.
  129. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:when]);
  130. }
  131. /** Runs a transaction block. */
  132. - (void)runTransactionBlock:(void (^)(FIRTransaction *transaction))transactionBlock {
  133. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  134. [_docRef.firestore runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  135. transactionBlock(transaction);
  136. return nil;
  137. }
  138. completion:^(id result, NSError *error) {
  139. XCTAssertNil(error);
  140. [expectation fulfill];
  141. }];
  142. [self awaitExpectations];
  143. }
  144. #pragma mark - Test Cases
  145. - (void)testServerTimestampsWorkViaSet {
  146. [self writeDocumentRef:_docRef data:_setData];
  147. [self verifyTimestampsAreNullInSnapshot:[self waitForLocalEvent]];
  148. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  149. }
  150. - (void)testServerTimestampsWorkViaUpdate {
  151. [self writeInitialData];
  152. [self updateDocumentRef:_docRef data:_updateData];
  153. [self verifyTimestampsAreNullInSnapshot:[self waitForLocalEvent]];
  154. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  155. }
  156. - (void)testServerTimestampsWithEstimatedValue {
  157. [self writeDocumentRef:_docRef data:_setData];
  158. [self verifyTimestampsAreEstimatedInSnapshot:[self waitForLocalEvent]];
  159. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  160. }
  161. - (void)testServerTimestampsWithPreviousValue {
  162. [self writeDocumentRef:_docRef data:_setData];
  163. [self verifyTimestampsInSnapshot:[self waitForLocalEvent] fromPreviousSnapshot:nil];
  164. FIRDocumentSnapshot *remoteSnapshot = [self waitForRemoteEvent];
  165. [_docRef updateData:_updateData];
  166. [self verifyTimestampsInSnapshot:[self waitForLocalEvent] fromPreviousSnapshot:remoteSnapshot];
  167. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  168. }
  169. - (void)testServerTimestampsWithPreviousValueOfDifferentType {
  170. [self writeDocumentRef:_docRef data:_setData];
  171. [self verifyTimestampsInSnapshot:[self waitForLocalEvent] fromPreviousSnapshot:nil];
  172. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  173. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  174. FIRDocumentSnapshot *localSnapshot = [self waitForLocalEvent];
  175. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], [NSNull null]);
  176. XCTAssertEqualObjects([localSnapshot valueForField:@"a" options:_returnPreviousValue], @42);
  177. XCTAssertTrue([[localSnapshot valueForField:@"a" options:_returnEstimatedValue]
  178. isKindOfClass:[NSDate class]]);
  179. FIRDocumentSnapshot *remoteSnapshot = [self waitForRemoteEvent];
  180. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[NSDate class]]);
  181. XCTAssertTrue([[remoteSnapshot valueForField:@"a" options:_returnPreviousValue]
  182. isKindOfClass:[NSDate class]]);
  183. XCTAssertTrue([[remoteSnapshot valueForField:@"a" options:_returnEstimatedValue]
  184. isKindOfClass:[NSDate class]]);
  185. }
  186. - (void)testServerTimestampsWithConsecutiveUpdates {
  187. [self writeDocumentRef:_docRef data:_setData];
  188. [self verifyTimestampsInSnapshot:[self waitForLocalEvent] fromPreviousSnapshot:nil];
  189. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  190. [self disableNetwork];
  191. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  192. FIRDocumentSnapshot *localSnapshot = [self waitForLocalEvent];
  193. XCTAssertEqualObjects([localSnapshot valueForField:@"a" options:_returnPreviousValue], @42);
  194. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  195. localSnapshot = [self waitForLocalEvent];
  196. XCTAssertEqualObjects([localSnapshot valueForField:@"a" options:_returnPreviousValue], @42);
  197. [self enableNetwork];
  198. FIRDocumentSnapshot *remoteSnapshot = [self waitForRemoteEvent];
  199. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[NSDate class]]);
  200. }
  201. - (void)testServerTimestampsPreviousValueFromLocalMutation {
  202. [self writeDocumentRef:_docRef data:_setData];
  203. [self verifyTimestampsInSnapshot:[self waitForLocalEvent] fromPreviousSnapshot:nil];
  204. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  205. [self disableNetwork];
  206. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  207. FIRDocumentSnapshot *localSnapshot = [self waitForLocalEvent];
  208. XCTAssertEqualObjects([localSnapshot valueForField:@"a" options:_returnPreviousValue], @42);
  209. [_docRef updateData:@{ @"a" : @1337 }];
  210. localSnapshot = [self waitForLocalEvent];
  211. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], @1337);
  212. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  213. localSnapshot = [self waitForLocalEvent];
  214. XCTAssertEqualObjects([localSnapshot valueForField:@"a" options:_returnPreviousValue], @1337);
  215. [self enableNetwork];
  216. FIRDocumentSnapshot *remoteSnapshot = [self waitForRemoteEvent];
  217. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[NSDate class]]);
  218. }
  219. - (void)testServerTimestampsWorkViaTransactionSet {
  220. [self runTransactionBlock:^(FIRTransaction *transaction) {
  221. [transaction setData:_setData forDocument:_docRef];
  222. }];
  223. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  224. }
  225. - (void)testServerTimestampsWorkViaTransactionUpdate {
  226. [self writeInitialData];
  227. [self runTransactionBlock:^(FIRTransaction *transaction) {
  228. [transaction updateData:_updateData forDocument:_docRef];
  229. }];
  230. [self verifySnapshotWithResolvedTimestamps:[self waitForRemoteEvent]];
  231. }
  232. - (void)testServerTimestampsFailViaUpdateOnNonexistentDocument {
  233. XCTestExpectation *expectation = [self expectationWithDescription:@"update complete"];
  234. [_docRef updateData:_updateData
  235. completion:^(NSError *error) {
  236. XCTAssertNotNil(error);
  237. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  238. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  239. [expectation fulfill];
  240. }];
  241. [self awaitExpectations];
  242. }
  243. - (void)testServerTimestampsFailViaTransactionUpdateOnNonexistentDocument {
  244. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  245. [_docRef.firestore runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  246. [transaction updateData:_updateData forDocument:_docRef];
  247. return nil;
  248. }
  249. completion:^(id result, NSError *error) {
  250. XCTAssertNotNil(error);
  251. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  252. // TODO(b/35201829): This should be NotFound, but right now we retry transactions on any
  253. // error and so this turns into Aborted instead.
  254. // TODO(mikelehen): Actually it's FailedPrecondition, unlike Android. What do we want???
  255. XCTAssertEqual(error.code, FIRFirestoreErrorCodeFailedPrecondition);
  256. [expectation fulfill];
  257. }];
  258. [self awaitExpectations];
  259. }
  260. @end