FIRServerTimestampTests.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 =
  80. [snapshot valueForField:@"when" 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 runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  116. transactionBlock(transaction);
  117. return nil;
  118. }
  119. completion:^(id result, NSError *error) {
  120. XCTAssertNil(error);
  121. [expectation fulfill];
  122. }];
  123. [self awaitExpectations];
  124. }
  125. #pragma mark - Test Cases
  126. - (void)testServerTimestampsWorkViaSet {
  127. [self writeDocumentRef:_docRef data:_setData];
  128. [self verifyTimestampsAreNullInSnapshot:[_accumulator awaitLocalEvent]];
  129. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  130. }
  131. - (void)testServerTimestampsWorkViaUpdate {
  132. [self writeInitialData];
  133. [self updateDocumentRef:_docRef data:_updateData];
  134. [self verifyTimestampsAreNullInSnapshot:[_accumulator awaitLocalEvent]];
  135. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  136. }
  137. - (void)testServerTimestampsWithEstimatedValue {
  138. [self writeDocumentRef:_docRef data:_setData];
  139. [self verifyTimestampsAreEstimatedInSnapshot:[_accumulator awaitLocalEvent]];
  140. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  141. }
  142. - (void)testServerTimestampsWithPreviousValue {
  143. [self writeDocumentRef:_docRef data:_setData];
  144. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  145. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  146. [_docRef updateData:_updateData];
  147. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent]
  148. fromPreviousSnapshot:remoteSnapshot];
  149. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  150. }
  151. - (void)testServerTimestampsWithPreviousValueOfDifferentType {
  152. [self writeDocumentRef:_docRef data:_setData];
  153. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  154. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  155. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  156. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  157. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], [NSNull null]);
  158. XCTAssertEqualObjects(
  159. [localSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  160. @42);
  161. XCTAssertTrue(
  162. [[localSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  163. isKindOfClass:[FIRTimestamp class]]);
  164. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  165. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  166. XCTAssertTrue([
  167. [remoteSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorPrevious]
  168. isKindOfClass:[FIRTimestamp class]]);
  169. XCTAssertTrue([
  170. [remoteSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  171. isKindOfClass:[FIRTimestamp class]]);
  172. }
  173. - (void)testServerTimestampsWithConsecutiveUpdates {
  174. [self writeDocumentRef:_docRef data:_setData];
  175. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  176. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  177. [self disableNetwork];
  178. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  179. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  180. XCTAssertEqualObjects(
  181. [localSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  182. @42);
  183. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  184. localSnapshot = [_accumulator awaitLocalEvent];
  185. XCTAssertEqualObjects(
  186. [localSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  187. @42);
  188. [self enableNetwork];
  189. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  190. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  191. }
  192. - (void)testServerTimestampsPreviousValueFromLocalMutation {
  193. [self writeDocumentRef:_docRef data:_setData];
  194. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  195. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  196. [self disableNetwork];
  197. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  198. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  199. XCTAssertEqualObjects(
  200. [localSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  201. @42);
  202. [_docRef updateData:@{ @"a" : @1337 }];
  203. localSnapshot = [_accumulator awaitLocalEvent];
  204. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], @1337);
  205. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  206. localSnapshot = [_accumulator awaitLocalEvent];
  207. XCTAssertEqualObjects(
  208. [localSnapshot valueForField:@"a" serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  209. @1337);
  210. [self enableNetwork];
  211. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  212. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  213. }
  214. - (void)testServerTimestampsWorkViaTransactionSet {
  215. [self runTransactionBlock:^(FIRTransaction *transaction) {
  216. [transaction setData:_setData forDocument:_docRef];
  217. }];
  218. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  219. }
  220. - (void)testServerTimestampsWorkViaTransactionUpdate {
  221. [self writeInitialData];
  222. [self runTransactionBlock:^(FIRTransaction *transaction) {
  223. [transaction updateData:_updateData forDocument:_docRef];
  224. }];
  225. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  226. }
  227. - (void)testServerTimestampsFailViaUpdateOnNonexistentDocument {
  228. XCTestExpectation *expectation = [self expectationWithDescription:@"update complete"];
  229. [_docRef updateData:_updateData
  230. completion:^(NSError *error) {
  231. XCTAssertNotNil(error);
  232. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  233. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  234. [expectation fulfill];
  235. }];
  236. [self awaitExpectations];
  237. }
  238. - (void)testServerTimestampsFailViaTransactionUpdateOnNonexistentDocument {
  239. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  240. [_docRef.firestore runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  241. [transaction updateData:_updateData forDocument:_docRef];
  242. return nil;
  243. }
  244. completion:^(id result, NSError *error) {
  245. XCTAssertNotNil(error);
  246. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  247. // TODO(b/35201829): This should be NotFound, but right now we retry transactions on any
  248. // error and so this turns into Aborted instead.
  249. // TODO(mikelehen): Actually it's FailedPrecondition, unlike Android. What do we want???
  250. XCTAssertEqual(error.code, FIRFirestoreErrorCodeFailedPrecondition);
  251. [expectation fulfill];
  252. }];
  253. [self awaitExpectations];
  254. }
  255. @end