FIRServerTimestampTests.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. @interface FIRServerTimestampTests : FSTIntegrationTestCase
  22. @end
  23. @implementation FIRServerTimestampTests {
  24. // Data written in tests via set.
  25. NSDictionary *_setData;
  26. // Base and update data used for update tests.
  27. NSDictionary *_initialData;
  28. NSDictionary *_updateData;
  29. // A document reference to read and write to.
  30. FIRDocumentReference *_docRef;
  31. // Accumulator used to capture events during the test.
  32. FSTEventAccumulator *_accumulator;
  33. // Listener registration for a listener maintained during the course of the test.
  34. id<FIRListenerRegistration> _listenerRegistration;
  35. }
  36. - (void)setUp {
  37. [super setUp];
  38. // Data written in tests via set.
  39. _setData = @{
  40. @"a" : @42,
  41. @"when" : [FIRFieldValue fieldValueForServerTimestamp],
  42. @"deep" : @{@"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  43. };
  44. // Base and update data used for update tests.
  45. _initialData = @{@"a" : @42};
  46. _updateData = @{
  47. @"when" : [FIRFieldValue fieldValueForServerTimestamp],
  48. @"deep" : @{@"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  49. };
  50. _docRef = [self documentRef];
  51. _accumulator = [FSTEventAccumulator accumulatorForTest:self];
  52. _listenerRegistration = [_docRef addSnapshotListener:_accumulator.valueEventHandler];
  53. // Wait for initial nil snapshot to avoid potential races.
  54. FIRDocumentSnapshot *initialSnapshot = [_accumulator awaitEventWithName:@"initial event"];
  55. XCTAssertFalse(initialSnapshot.exists);
  56. }
  57. - (void)tearDown {
  58. [_listenerRegistration remove];
  59. [super tearDown];
  60. }
  61. #pragma mark - Test Helpers
  62. /** Returns the expected data, with the specified timestamp substituted in. */
  63. - (NSDictionary *)expectedDataWithTimestamp:(nullable id)timestamp {
  64. return @{@"a" : @42, @"when" : timestamp, @"deep" : @{@"when" : timestamp}};
  65. }
  66. /** Writes _initialData and waits for the corresponding snapshot. */
  67. - (void)writeInitialData {
  68. [self writeDocumentRef:_docRef data:_initialData];
  69. FIRDocumentSnapshot *initialDataSnap = [_accumulator awaitEventWithName:@"Initial data event."];
  70. XCTAssertEqualObjects(initialDataSnap.data, _initialData);
  71. }
  72. /** Verifies a snapshot containing _setData but with NSNull for the timestamps. */
  73. - (void)verifyTimestampsAreNullInSnapshot:(FIRDocumentSnapshot *)snapshot {
  74. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:[NSNull null]]);
  75. }
  76. /** Verifies a snapshot containing _setData but with a local estimate for the timestamps. */
  77. - (void)verifyTimestampsAreEstimatedInSnapshot:(FIRDocumentSnapshot *)snapshot {
  78. id timestamp = [snapshot valueForField:@"when"
  79. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate];
  80. XCTAssertTrue([timestamp isKindOfClass:[FIRTimestamp class]]);
  81. XCTAssertEqualObjects(
  82. [snapshot dataWithServerTimestampBehavior:FIRServerTimestampBehaviorEstimate],
  83. [self expectedDataWithTimestamp:timestamp]);
  84. }
  85. /**
  86. * Verifies a snapshot containing _setData but using the previous field value for server
  87. * timestamps.
  88. */
  89. - (void)verifyTimestampsInSnapshot:(FIRDocumentSnapshot *)snapshot
  90. fromPreviousSnapshot:(nullable FIRDocumentSnapshot *)previousSnapshot {
  91. if (previousSnapshot == nil) {
  92. XCTAssertEqualObjects(
  93. [snapshot dataWithServerTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  94. [self expectedDataWithTimestamp:[NSNull null]]);
  95. } else {
  96. XCTAssertEqualObjects(
  97. [snapshot dataWithServerTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  98. [self expectedDataWithTimestamp:previousSnapshot[@"when"]]);
  99. }
  100. }
  101. /** Verifies a snapshot containing _setData but with resolved server timestamps. */
  102. - (void)verifySnapshotWithResolvedTimestamps:(FIRDocumentSnapshot *)snapshot {
  103. XCTAssertTrue(snapshot.exists);
  104. FIRTimestamp *when = snapshot[@"when"];
  105. XCTAssertTrue([when isKindOfClass:[FIRTimestamp class]]);
  106. // Tolerate up to 10 seconds of clock skew between client and server.
  107. XCTAssertEqualWithAccuracy(when.seconds, [FIRTimestamp timestamp].seconds, 10);
  108. // Validate the rest of the document.
  109. XCTAssertEqualObjects(snapshot.data, [self expectedDataWithTimestamp:when]);
  110. }
  111. /** Runs a transaction block. */
  112. - (void)runTransactionBlock:(void (^)(FIRTransaction *transaction))transactionBlock {
  113. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  114. [_docRef.firestore
  115. 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. // The following test includes an update of the nested map "deep", which updates it to contain
  144. // a single ServerTimestamp. This update is split into two mutations: One that sets "deep" to
  145. // an empty map and overwrites the previous ServerTimestamp value and a second transform that
  146. // writes the new ServerTimestamp. This step in the test verifies that we can still access the
  147. // old ServerTimestamp value (from `previousSnapshot`) even though it was removed in an
  148. // intermediate step.
  149. [self writeDocumentRef:_docRef data:_setData];
  150. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  151. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  152. [_docRef updateData:_updateData];
  153. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent]
  154. fromPreviousSnapshot:remoteSnapshot];
  155. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  156. }
  157. - (void)testServerTimestampsWithPreviousValueOfDifferentType {
  158. [self writeDocumentRef:_docRef data:_setData];
  159. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  160. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  161. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  162. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  163. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], [NSNull null]);
  164. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  165. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  166. @42);
  167. XCTAssertTrue([[localSnapshot valueForField:@"a"
  168. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  169. isKindOfClass:[FIRTimestamp class]]);
  170. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  171. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  172. XCTAssertTrue([[remoteSnapshot valueForField:@"a"
  173. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious]
  174. isKindOfClass:[FIRTimestamp class]]);
  175. XCTAssertTrue([[remoteSnapshot valueForField:@"a"
  176. serverTimestampBehavior:FIRServerTimestampBehaviorEstimate]
  177. isKindOfClass:[FIRTimestamp class]]);
  178. }
  179. - (void)testServerTimestampsWithConsecutiveUpdates {
  180. [self writeDocumentRef:_docRef data:_setData];
  181. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  182. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  183. [self disableNetwork];
  184. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  185. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  186. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  187. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  188. @42);
  189. // include b=1 to ensure there's a change resulting in a new snapshot.
  190. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp], @"b" : @1}];
  191. localSnapshot = [_accumulator awaitLocalEvent];
  192. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  193. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  194. @42);
  195. [self enableNetwork];
  196. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  197. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  198. }
  199. - (void)testServerTimestampsPreviousValueFromLocalMutation {
  200. [self writeDocumentRef:_docRef data:_setData];
  201. [self verifyTimestampsInSnapshot:[_accumulator awaitLocalEvent] fromPreviousSnapshot:nil];
  202. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  203. [self disableNetwork];
  204. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  205. FIRDocumentSnapshot *localSnapshot = [_accumulator awaitLocalEvent];
  206. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  207. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  208. @42);
  209. [_docRef updateData:@{@"a" : @1337}];
  210. localSnapshot = [_accumulator awaitLocalEvent];
  211. XCTAssertEqualObjects([localSnapshot valueForField:@"a"], @1337);
  212. [_docRef updateData:@{@"a" : [FIRFieldValue fieldValueForServerTimestamp]}];
  213. localSnapshot = [_accumulator awaitLocalEvent];
  214. XCTAssertEqualObjects([localSnapshot valueForField:@"a"
  215. serverTimestampBehavior:FIRServerTimestampBehaviorPrevious],
  216. @1337);
  217. [self enableNetwork];
  218. FIRDocumentSnapshot *remoteSnapshot = [_accumulator awaitRemoteEvent];
  219. XCTAssertTrue([[remoteSnapshot valueForField:@"a"] isKindOfClass:[FIRTimestamp class]]);
  220. }
  221. - (void)testServerTimestampsWorkViaTransactionSet {
  222. [self runTransactionBlock:^(FIRTransaction *transaction) {
  223. [transaction setData:self->_setData forDocument:self->_docRef];
  224. }];
  225. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  226. }
  227. - (void)testServerTimestampsWorkViaTransactionUpdate {
  228. [self writeInitialData];
  229. [self runTransactionBlock:^(FIRTransaction *transaction) {
  230. [transaction updateData:self->_updateData forDocument:self->_docRef];
  231. }];
  232. [self verifySnapshotWithResolvedTimestamps:[_accumulator awaitRemoteEvent]];
  233. }
  234. - (void)testServerTimestampsFailViaUpdateOnNonexistentDocument {
  235. XCTestExpectation *expectation = [self expectationWithDescription:@"update complete"];
  236. [_docRef updateData:_updateData
  237. completion:^(NSError *error) {
  238. XCTAssertNotNil(error);
  239. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  240. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  241. [expectation fulfill];
  242. }];
  243. [self awaitExpectations];
  244. }
  245. - (void)testServerTimestampsFailViaTransactionUpdateOnNonexistentDocument {
  246. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction complete"];
  247. [_docRef.firestore
  248. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  249. [transaction updateData:self->_updateData forDocument:self->_docRef];
  250. return nil;
  251. }
  252. completion:^(id result, NSError *error) {
  253. XCTAssertNotNil(error);
  254. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  255. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  256. [expectation fulfill];
  257. }];
  258. [self awaitExpectations];
  259. }
  260. @end