FIRServerTimestampTests.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. }
  37. - (void)setUp {
  38. [super setUp];
  39. // Data written in tests via set.
  40. _setData = @{
  41. @"a" : @42,
  42. @"when" : [FIRFieldValue fieldValueForServerTimestamp],
  43. @"deep" : @{@"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  44. };
  45. // Base and update data used for update tests.
  46. _initialData = @{@"a" : @42};
  47. _updateData = @{
  48. @"when" : [FIRFieldValue fieldValueForServerTimestamp],
  49. @"deep" : @{@"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  50. };
  51. _docRef = [self documentRef];
  52. _accumulator = [FSTEventAccumulator accumulatorForTest:self];
  53. _listenerRegistration = [_docRef addSnapshotListener:_accumulator.valueEventHandler];
  54. // Wait for initial nil snapshot to avoid potential races.
  55. FIRDocumentSnapshot *initialSnapshot = [_accumulator awaitEventWithName:@"initial event"];
  56. XCTAssertFalse(initialSnapshot.exists);
  57. }
  58. - (void)tearDown {
  59. [_listenerRegistration remove];
  60. [super tearDown];
  61. }
  62. #pragma mark - Test Helpers
  63. /** Returns the expected data, with the specified timestamp substituted in. */
  64. - (NSDictionary *)expectedDataWithTimestamp:(nullable id)timestamp {
  65. return @{@"a" : @42, @"when" : timestamp, @"deep" : @{@"when" : timestamp}};
  66. }
  67. /** Writes _initialData and waits for the corresponding snapshot. */
  68. - (void)writeInitialData {
  69. [self writeDocumentRef:_docRef data:_initialData];
  70. FIRDocumentSnapshot *initialDataSnap = [_accumulator awaitEventWithName:@"Initial data event."];
  71. XCTAssertEqualObjects(initialDataSnap.data, _initialData);
  72. }
  73. /** Verifies a snapshot containing _setData but with NSNull for the timestamps. */
  74. - (void)verifyTimestampsAreNullInSnapshot:(FIRDocumentSnapshot *)snapshot {
  75. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:[NSNull null]]);
  76. }
  77. /** Verifies a snapshot containing _setData but with a local estimate for the timestamps. */
  78. - (void)verifyTimestampsAreEstimatedInSnapshot:(FIRDocumentSnapshot *)snapshot {
  79. id timestamp = [snapshot valueForField:@"when"
  80. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate];
  81. XCTAssertTrue([timestamp isKindOfClass:[FIRTimestamp class]]);
  82. XCTAssertEqualObjects(
  83. [snapshot dataWithServerTimestampBehavior:FIRServerTimestampBehaviorEstimate],
  84. [self expectedDataWithTimestamp:timestamp]);
  85. }
  86. /**
  87. * Verifies a snapshot containing _setData but using the previous field value for server
  88. * timestamps.
  89. */
  90. - (void)verifyTimestampsInSnapshot:(FIRDocumentSnapshot *)snapshot
  91. fromPreviousSnapshot:(nullable FIRDocumentSnapshot *)previousSnapshot {
  92. if (previousSnapshot == nil) {
  93. XCTAssertEqualObjects(
  94. [snapshot dataWithServerTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  95. [self expectedDataWithTimestamp:[NSNull null]]);
  96. } else {
  97. XCTAssertEqualObjects(
  98. [snapshot dataWithServerTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  99. [self expectedDataWithTimestamp:previousSnapshot[@"when"]]);
  100. }
  101. }
  102. /** Verifies a snapshot containing _setData but with resolved server timestamps. */
  103. - (void)verifySnapshotWithResolvedTimestamps:(FIRDocumentSnapshot *)snapshot {
  104. XCTAssertTrue(snapshot.exists);
  105. FIRTimestamp *when = snapshot[@"when"];
  106. XCTAssertTrue([when isKindOfClass:[FIRTimestamp class]]);
  107. // Tolerate up to 10 seconds of clock skew between client and server.
  108. XCTAssertEqualWithAccuracy(when.seconds, [FIRTimestamp timestamp].seconds, 10);
  109. // Validate the rest of the document.
  110. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:when]);
  111. }
  112. /** Runs a transaction block. */
  113. - (void)runTransactionBlock:(void (^)(FIRTransaction *transaction))transactionBlock {
  114. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  115. [_docRef.firestore
  116. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  117. transactionBlock(transaction);
  118. return nil;
  119. }
  120. completion:^(id result, NSError *error) {
  121. XCTAssertNil(error);
  122. [expectation fulfill];
  123. }];
  124. [self awaitExpectations];
  125. }
  126. #pragma mark - Test Cases
  127. - (void)testServerTimestampsWorkViaSet {
  128. [self writeDocumentRef:_docRef data:_setData];
  129. [self verifyTimestampsAreNullInSnapshot:[_accumulator awaitLocalEvent]];
  130. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  131. }
  132. - (void)testServerTimestampsWorkViaUpdate {
  133. [self writeInitialData];
  134. [self updateDocumentRef:_docRef data:_updateData];
  135. [self verifyTimestampsAreNullInSnapshot:[_accumulator awaitLocalEvent]];
  136. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  137. }
  138. - (void)testServerTimestampsWithEstimatedValue {
  139. [self writeDocumentRef:_docRef data:_setData];
  140. [self verifyTimestampsAreEstimatedInSnapshot:[_accumulator awaitLocalEvent]];
  141. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  142. }
  143. - (void)testServerTimestampsWithPreviousValue {
  144. [self writeDocumentRef:_docRef data:_setData];
  145. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  146. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  147. [_docRef updateData:_updateData];
  148. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent]
  149. fromPreviousSnapshot:remoteSnapshot];
  150. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  151. }
  152. - (void)testServerTimestampsWithPreviousValueOfDifferentType {
  153. [self writeDocumentRef:_docRef data:_setData];
  154. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  155. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  156. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  157. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  158. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], [NSNull null]);
  159. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  160. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  161. @42);
  162. XCTAssertTrue([[localSnapshot valueForField:@"a"
  163. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  164. isKindOfClass:[FIRTimestamp class]]);
  165. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  166. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  167. XCTAssertTrue([[remoteSnapshot valueForField:@"a"
  168. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious]
  169. isKindOfClass:[FIRTimestamp class]]);
  170. XCTAssertTrue([[remoteSnapshot valueForField:@"a"
  171. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  172. isKindOfClass:[FIRTimestamp class]]);
  173. }
  174. - (void)testServerTimestampsWithConsecutiveUpdates {
  175. [self writeDocumentRef:_docRef data:_setData];
  176. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  177. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  178. [self disableNetwork];
  179. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  180. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  181. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  182. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  183. @42);
  184. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  185. localSnapshot = [_accumulator awaitLocalEvent];
  186. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  187. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  188. @42);
  189. [self enableNetwork];
  190. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  191. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  192. }
  193. - (void)testServerTimestampsPreviousValueFromLocalMutation {
  194. [self writeDocumentRef:_docRef data:_setData];
  195. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  196. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  197. [self disableNetwork];
  198. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  199. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  200. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  201. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  202. @42);
  203. [_docRef updateData:@{@"a" : @1337}];
  204. localSnapshot = [_accumulator awaitLocalEvent];
  205. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], @1337);
  206. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  207. localSnapshot = [_accumulator awaitLocalEvent];
  208. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  209. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  210. @1337);
  211. [self enableNetwork];
  212. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  213. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  214. }
  215. - (void)testServerTimestampsWorkViaTransactionSet {
  216. [self runTransactionBlock:^(FIRTransaction *transaction) {
  217. [transaction setData:_setData forDocument:_docRef];
  218. }];
  219. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  220. }
  221. - (void)testServerTimestampsWorkViaTransactionUpdate {
  222. [self writeInitialData];
  223. [self runTransactionBlock:^(FIRTransaction *transaction) {
  224. [transaction updateData:_updateData forDocument:_docRef];
  225. }];
  226. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  227. }
  228. - (void)testServerTimestampsFailViaUpdateOnNonexistentDocument {
  229. XCTestExpectation *expectation = [self expectationWithDescription:@"update complete"];
  230. [_docRef updateData:_updateData
  231. completion:^(NSError *error) {
  232. XCTAssertNotNil(error);
  233. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  234. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  235. [expectation fulfill];
  236. }];
  237. [self awaitExpectations];
  238. }
  239. - (void)testServerTimestampsFailViaTransactionUpdateOnNonexistentDocument {
  240. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  241. [_docRef.firestore
  242. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  243. [transaction updateData:_updateData forDocument:_docRef];
  244. return nil;
  245. }
  246. completion:^(id result, NSError *error) {
  247. XCTAssertNotNil(error);
  248. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  249. // TODO(b/35201829): This should be NotFound, but right now we retry transactions on any
  250. // error and so this turns into Aborted instead.
  251. // TODO(mikelehen): Actually it's FailedPrecondition, unlike Android. What do we want???
  252. XCTAssertEqual(error.code, FIRFirestoreErrorCodeFailedPrecondition);
  253. [expectation fulfill];
  254. }];
  255. [self awaitExpectations];
  256. }
  257. @end