FIRServerTimestampTests.mm 13 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 "FirebaseCore/FIRTimestamp.h"
  19. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  20. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  21. #import "Firestore/Source/API/FIRFirestore+Internal.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. // Tolerate up to 200 seconds of clock skew between client and server.
  105. NSInteger tolerance = 200;
  106. XCTAssertTrue(snapshot.exists);
  107. FIRTimestamp *when = snapshot[@"when"];
  108. XCTAssertTrue([when isKindOfClass:[FIRTimestamp class]]);
  109. XCTAssertEqualWithAccuracy(when.seconds, [FIRTimestamp timestamp].seconds, tolerance);
  110. // Validate the rest of the document.
  111. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:when]);
  112. }
  113. /** Runs a transaction block. */
  114. - (void)runTransactionBlock:(void (^)(FIRTransaction *transaction))transactionBlock {
  115. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  116. [_docRef.firestore
  117. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **) {
  118. transactionBlock(transaction);
  119. return nil;
  120. }
  121. completion:^(id, NSError *error) {
  122. XCTAssertNil(error);
  123. [expectation fulfill];
  124. }];
  125. [self awaitExpectations];
  126. }
  127. #pragma mark - Test Cases
  128. - (void)testServerTimestampsWorkViaSet {
  129. [self writeDocumentRef:_docRef data:_setData];
  130. [self verifyTimestampsAreNullInSnapshot:[_accumulator awaitLocalEvent]];
  131. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  132. }
  133. - (void)testServerTimestampsWorkViaUpdate {
  134. [self writeInitialData];
  135. [self updateDocumentRef:_docRef data:_updateData];
  136. [self verifyTimestampsAreNullInSnapshot:[_accumulator awaitLocalEvent]];
  137. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  138. }
  139. - (void)testServerTimestampsWithEstimatedValue {
  140. [self writeDocumentRef:_docRef data:_setData];
  141. [self verifyTimestampsAreEstimatedInSnapshot:[_accumulator awaitLocalEvent]];
  142. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  143. }
  144. - (void)testServerTimestampsWithPreviousValue {
  145. // The following test includes an update of the nested map "deep", which updates it to contain
  146. // a single ServerTimestamp. This update is split into two mutations: One that sets "deep" to
  147. // an empty map and overwrites the previous ServerTimestamp value and a second transform that
  148. // writes the new ServerTimestamp. This step in the test verifies that we can still access the
  149. // old ServerTimestamp value (from `previousSnapshot`) even though it was removed in an
  150. // intermediate step.
  151. [self writeDocumentRef:_docRef data:_setData];
  152. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  153. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  154. [_docRef updateData:_updateData];
  155. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent]
  156. fromPreviousSnapshot:remoteSnapshot];
  157. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  158. }
  159. - (void)testServerTimestampsWithPreviousValueOfDifferentType {
  160. [self writeDocumentRef:_docRef data:_setData];
  161. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  162. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  163. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  164. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  165. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], [NSNull null]);
  166. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  167. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  168. @42);
  169. XCTAssertTrue([[localSnapshot valueForField:@"a"
  170. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  171. isKindOfClass:[FIRTimestamp class]]);
  172. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  173. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  174. XCTAssertTrue([[remoteSnapshot valueForField:@"a"
  175. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious]
  176. isKindOfClass:[FIRTimestamp class]]);
  177. XCTAssertTrue([[remoteSnapshot valueForField:@"a"
  178. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  179. isKindOfClass:[FIRTimestamp class]]);
  180. }
  181. - (void)testServerTimestampsWithConsecutiveUpdates {
  182. [self writeDocumentRef:_docRef data:_setData];
  183. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  184. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  185. [self disableNetwork];
  186. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  187. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  188. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  189. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  190. @42);
  191. // include b=1 to ensure there's a change resulting in a new snapshot.
  192. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp], @"b" : @1}];
  193. localSnapshot = [_accumulator awaitLocalEvent];
  194. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  195. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  196. @42);
  197. [self enableNetwork];
  198. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  199. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  200. }
  201. - (void)testServerTimestampsPreviousValueFromLocalMutation {
  202. [self writeDocumentRef:_docRef data:_setData];
  203. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  204. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  205. [self disableNetwork];
  206. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  207. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  208. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  209. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  210. @42);
  211. [_docRef updateData:@{@"a" : @1337}];
  212. localSnapshot = [_accumulator awaitLocalEvent];
  213. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], @1337);
  214. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  215. localSnapshot = [_accumulator awaitLocalEvent];
  216. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  217. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  218. @1337);
  219. [self enableNetwork];
  220. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  221. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  222. }
  223. - (void)testServerTimestampsWorkViaTransactionSet {
  224. [self runTransactionBlock:^(FIRTransaction *transaction) {
  225. [transaction setData:self->_setData forDocument:self->_docRef];
  226. }];
  227. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  228. }
  229. - (void)testServerTimestampsWorkViaTransactionUpdate {
  230. [self writeInitialData];
  231. [self runTransactionBlock:^(FIRTransaction *transaction) {
  232. [transaction updateData:self->_updateData forDocument:self->_docRef];
  233. }];
  234. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  235. }
  236. - (void)testServerTimestampsFailViaUpdateOnNonexistentDocument {
  237. XCTestExpectation *expectation = [self expectationWithDescription:@"update complete"];
  238. [_docRef updateData:_updateData
  239. completion:^(NSError *error) {
  240. XCTAssertNotNil(error);
  241. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  242. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  243. [expectation fulfill];
  244. }];
  245. [self awaitExpectations];
  246. }
  247. - (void)testServerTimestampsFailViaTransactionUpdateOnNonexistentDocument {
  248. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  249. [_docRef.firestore
  250. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **) {
  251. [transaction updateData:self->_updateData forDocument:self->_docRef];
  252. return nil;
  253. }
  254. completion:^(id, NSError *error) {
  255. XCTAssertNotNil(error);
  256. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  257. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  258. [expectation fulfill];
  259. }];
  260. [self awaitExpectations];
  261. }
  262. @end