FIRWriteBatchTests.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. #include <mach/mach.h>
  19. #include <cstdint>
  20. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  21. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  22. #include "Firestore/core/src/firebase/firestore/util/autoid.h"
  23. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  24. using firebase::firestore::util::CreateAutoId;
  25. using firebase::firestore::util::WrapNSString;
  26. NS_ASSUME_NONNULL_BEGIN
  27. @interface FIRWriteBatchTests : FSTIntegrationTestCase
  28. @end
  29. @implementation FIRWriteBatchTests
  30. - (void)testSupportEmptyBatches {
  31. XCTestExpectation *expectation = [self expectationWithDescription:@"batch written"];
  32. [[[self firestore] batch] commitWithCompletion:^(NSError *error) {
  33. XCTAssertNil(error);
  34. [expectation fulfill];
  35. }];
  36. [self awaitExpectations];
  37. }
  38. - (void)testCommitWithoutCompletionHandler {
  39. FIRDocumentReference *doc = [self documentRef];
  40. FIRWriteBatch *batch1 = [doc.firestore batch];
  41. [batch1 setData:@{@"aa" : @"bb"} forDocument:doc];
  42. [batch1 commitWithCompletion:nil];
  43. FIRDocumentSnapshot *snapshot1 = [self readDocumentForRef:doc];
  44. XCTAssertTrue(snapshot1.exists);
  45. XCTAssertEqualObjects(snapshot1.data, @{@"aa" : @"bb"});
  46. FIRWriteBatch *batch2 = [doc.firestore batch];
  47. [batch2 setData:@{@"cc" : @"dd"} forDocument:doc];
  48. [batch2 commit];
  49. // TODO(b/70631617): There's currently a backend bug that prevents us from using a resume token
  50. // right away (against hexa at least). So we sleep. :-( :-( Anything over ~10ms seems to be
  51. // sufficient.
  52. [NSThread sleepForTimeInterval:0.2f];
  53. FIRDocumentSnapshot *snapshot2 = [self readDocumentForRef:doc];
  54. XCTAssertTrue(snapshot2.exists);
  55. XCTAssertEqualObjects(snapshot2.data, @{@"cc" : @"dd"});
  56. }
  57. - (void)testSetDocuments {
  58. FIRDocumentReference *doc = [self documentRef];
  59. XCTestExpectation *batchExpectation = [self expectationWithDescription:@"batch written"];
  60. FIRWriteBatch *batch = [doc.firestore batch];
  61. [batch setData:@{@"a" : @"b"} forDocument:doc];
  62. [batch setData:@{@"c" : @"d"} forDocument:doc];
  63. [batch commitWithCompletion:^(NSError *error) {
  64. XCTAssertNil(error);
  65. [batchExpectation fulfill];
  66. }];
  67. [self awaitExpectations];
  68. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  69. XCTAssertTrue(snapshot.exists);
  70. XCTAssertEqualObjects(snapshot.data, @{@"c" : @"d"});
  71. }
  72. - (void)testSetDocumentWithMerge {
  73. FIRDocumentReference *doc = [self documentRef];
  74. XCTestExpectation *batchExpectation = [self expectationWithDescription:@"batch written"];
  75. FIRWriteBatch *batch = [doc.firestore batch];
  76. [batch setData:@{@"a" : @"b", @"nested" : @{@"a" : @"b"}} forDocument:doc];
  77. [batch setData:@{@"c" : @"d", @"nested" : @{@"c" : @"d"}} forDocument:doc merge:YES];
  78. [batch commitWithCompletion:^(NSError *error) {
  79. XCTAssertNil(error);
  80. [batchExpectation fulfill];
  81. }];
  82. [self awaitExpectations];
  83. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  84. XCTAssertTrue(snapshot.exists);
  85. XCTAssertEqualObjects(snapshot.data,
  86. (@{@"a" : @"b", @"c" : @"d", @"nested" : @{@"a" : @"b", @"c" : @"d"}}));
  87. }
  88. - (void)testUpdateDocuments {
  89. FIRDocumentReference *doc = [self documentRef];
  90. [self writeDocumentRef:doc data:@{@"foo" : @"bar"}];
  91. XCTestExpectation *batchExpectation = [self expectationWithDescription:@"batch written"];
  92. FIRWriteBatch *batch = [doc.firestore batch];
  93. [batch updateData:@{@"baz" : @42} forDocument:doc];
  94. [batch commitWithCompletion:^(NSError *error) {
  95. XCTAssertNil(error);
  96. [batchExpectation fulfill];
  97. }];
  98. [self awaitExpectations];
  99. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  100. XCTAssertTrue(snapshot.exists);
  101. XCTAssertEqualObjects(snapshot.data, (@{@"foo" : @"bar", @"baz" : @42}));
  102. }
  103. - (void)testCannotUpdateNonexistentDocuments {
  104. FIRDocumentReference *doc = [self documentRef];
  105. XCTestExpectation *batchExpectation = [self expectationWithDescription:@"batch written"];
  106. FIRWriteBatch *batch = [doc.firestore batch];
  107. [batch updateData:@{@"baz" : @42} forDocument:doc];
  108. [batch commitWithCompletion:^(NSError *error) {
  109. XCTAssertNotNil(error);
  110. [batchExpectation fulfill];
  111. }];
  112. [self awaitExpectations];
  113. FIRDocumentSnapshot *result = [self readDocumentForRef:doc];
  114. XCTAssertFalse(result.exists);
  115. }
  116. - (void)testUpdateFieldsWithDots {
  117. FIRDocumentReference *doc = [self documentRef];
  118. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateFieldsWithDots"];
  119. FIRWriteBatch *batch = [doc.firestore batch];
  120. [batch setData:@{@"a.b" : @"old", @"c.d" : @"old"} forDocument:doc];
  121. [batch updateData:@{[[FIRFieldPath alloc] initWithFields:@[ @"a.b" ]] : @"new"} forDocument:doc];
  122. [batch commitWithCompletion:^(NSError *_Nullable error) {
  123. XCTAssertNil(error);
  124. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  125. XCTAssertNil(error);
  126. XCTAssertEqualObjects(snapshot.data, (@{@"a.b" : @"new", @"c.d" : @"old"}));
  127. }];
  128. [expectation fulfill];
  129. }];
  130. [self awaitExpectations];
  131. }
  132. - (void)testUpdateNestedFields {
  133. FIRDocumentReference *doc = [self documentRef];
  134. XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdateNestedFields"];
  135. FIRWriteBatch *batch = [doc.firestore batch];
  136. [batch setData:@{@"a" : @{@"b" : @"old"}, @"c" : @{@"d" : @"old"}, @"e" : @{@"f" : @"old"}}
  137. forDocument:doc];
  138. [batch
  139. updateData:@{@"a.b" : @"new", [[FIRFieldPath alloc] initWithFields:@[ @"c", @"d" ]] : @"new"}
  140. forDocument:doc];
  141. [batch commitWithCompletion:^(NSError *_Nullable error) {
  142. XCTAssertNil(error);
  143. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  144. XCTAssertNil(error);
  145. XCTAssertEqualObjects(snapshot.data, (@{
  146. @"a" : @{@"b" : @"new"},
  147. @"c" : @{@"d" : @"new"},
  148. @"e" : @{@"f" : @"old"}
  149. }));
  150. }];
  151. [expectation fulfill];
  152. }];
  153. [self awaitExpectations];
  154. }
  155. - (void)testDeleteDocuments {
  156. FIRDocumentReference *doc = [self documentRef];
  157. [self writeDocumentRef:doc data:@{@"foo" : @"bar"}];
  158. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  159. XCTAssertTrue(snapshot.exists);
  160. XCTestExpectation *batchExpectation = [self expectationWithDescription:@"batch written"];
  161. FIRWriteBatch *batch = [doc.firestore batch];
  162. [batch deleteDocument:doc];
  163. [batch commitWithCompletion:^(NSError *error) {
  164. XCTAssertNil(error);
  165. [batchExpectation fulfill];
  166. }];
  167. [self awaitExpectations];
  168. snapshot = [self readDocumentForRef:doc];
  169. XCTAssertFalse(snapshot.exists);
  170. }
  171. - (void)testBatchesCommitAtomicallyRaisingCorrectEvents {
  172. FIRCollectionReference *collection = [self collectionRef];
  173. FIRDocumentReference *docA = [collection documentWithPath:@"a"];
  174. FIRDocumentReference *docB = [collection documentWithPath:@"b"];
  175. FSTEventAccumulator *accumulator = [FSTEventAccumulator accumulatorForTest:self];
  176. [collection addSnapshotListenerWithIncludeMetadataChanges:YES
  177. listener:accumulator.valueEventHandler];
  178. FIRQuerySnapshot *initialSnap = [accumulator awaitEventWithName:@"initial event"];
  179. XCTAssertEqual(initialSnap.count, 0);
  180. // Atomically write two documents.
  181. XCTestExpectation *expectation = [self expectationWithDescription:@"batch written"];
  182. FIRWriteBatch *batch = [collection.firestore batch];
  183. [batch setData:@{@"a" : @1} forDocument:docA];
  184. [batch setData:@{@"b" : @2} forDocument:docB];
  185. [batch commitWithCompletion:^(NSError *_Nullable error) {
  186. XCTAssertNil(error);
  187. [expectation fulfill];
  188. }];
  189. [self awaitExpectations];
  190. FIRQuerySnapshot *localSnap = [accumulator awaitEventWithName:@"local event"];
  191. XCTAssertTrue(localSnap.metadata.hasPendingWrites);
  192. XCTAssertEqualObjects(FIRQuerySnapshotGetData(localSnap), (@[ @{@"a" : @1}, @{@"b" : @2} ]));
  193. FIRQuerySnapshot *serverSnap = [accumulator awaitEventWithName:@"server event"];
  194. XCTAssertFalse(serverSnap.metadata.hasPendingWrites);
  195. XCTAssertEqualObjects(FIRQuerySnapshotGetData(serverSnap), (@[ @{@"a" : @1}, @{@"b" : @2} ]));
  196. }
  197. - (void)testBatchesFailAtomicallyRaisingCorrectEvents {
  198. FIRCollectionReference *collection = [self collectionRef];
  199. FIRDocumentReference *docA = [collection documentWithPath:@"a"];
  200. FIRDocumentReference *docB = [collection documentWithPath:@"b"];
  201. FSTEventAccumulator *accumulator = [FSTEventAccumulator accumulatorForTest:self];
  202. [collection addSnapshotListenerWithIncludeMetadataChanges:YES
  203. listener:accumulator.valueEventHandler];
  204. FIRQuerySnapshot *initialSnap = [accumulator awaitEventWithName:@"initial event"];
  205. XCTAssertEqual(initialSnap.count, 0);
  206. // Atomically write 1 document and update a nonexistent document.
  207. XCTestExpectation *expectation = [self expectationWithDescription:@"batch failed"];
  208. FIRWriteBatch *batch = [collection.firestore batch];
  209. [batch setData:@{@"a" : @1} forDocument:docA];
  210. [batch updateData:@{@"b" : @2} forDocument:docB];
  211. [batch commitWithCompletion:^(NSError *_Nullable error) {
  212. XCTAssertNotNil(error);
  213. XCTAssertEqualObjects(error.domain, FIRFirestoreErrorDomain);
  214. XCTAssertEqual(error.code, FIRFirestoreErrorCodeNotFound);
  215. [expectation fulfill];
  216. }];
  217. [self awaitExpectations];
  218. // Local event with the set document.
  219. FIRQuerySnapshot *localSnap = [accumulator awaitEventWithName:@"local event"];
  220. XCTAssertTrue(localSnap.metadata.hasPendingWrites);
  221. XCTAssertEqualObjects(FIRQuerySnapshotGetData(localSnap), (@[ @{@"a" : @1} ]));
  222. // Server event with the set reverted.
  223. FIRQuerySnapshot *serverSnap = [accumulator awaitEventWithName:@"server event"];
  224. XCTAssertFalse(serverSnap.metadata.hasPendingWrites);
  225. XCTAssertEqual(serverSnap.count, 0);
  226. }
  227. - (void)testWriteTheSameServerTimestampAcrossWrites {
  228. FIRCollectionReference *collection = [self collectionRef];
  229. FIRDocumentReference *docA = [collection documentWithPath:@"a"];
  230. FIRDocumentReference *docB = [collection documentWithPath:@"b"];
  231. FSTEventAccumulator *accumulator = [FSTEventAccumulator accumulatorForTest:self];
  232. [collection addSnapshotListenerWithIncludeMetadataChanges:YES
  233. listener:accumulator.valueEventHandler];
  234. FIRQuerySnapshot *initialSnap = [accumulator awaitEventWithName:@"initial event"];
  235. XCTAssertEqual(initialSnap.count, 0);
  236. // Atomically write 2 documents with server timestamps.
  237. XCTestExpectation *expectation = [self expectationWithDescription:@"batch written"];
  238. FIRWriteBatch *batch = [collection.firestore batch];
  239. [batch setData:@{@"when" : [FIRFieldValue fieldValueForServerTimestamp]} forDocument:docA];
  240. [batch setData:@{@"when" : [FIRFieldValue fieldValueForServerTimestamp]} forDocument:docB];
  241. [batch commitWithCompletion:^(NSError *_Nullable error) {
  242. XCTAssertNil(error);
  243. [expectation fulfill];
  244. }];
  245. [self awaitExpectations];
  246. FIRQuerySnapshot *localSnap = [accumulator awaitEventWithName:@"local event"];
  247. XCTAssertTrue(localSnap.metadata.hasPendingWrites);
  248. XCTAssertEqualObjects(FIRQuerySnapshotGetData(localSnap),
  249. (@[ @{@"when" : [NSNull null]}, @{@"when" : [NSNull null]} ]));
  250. FIRQuerySnapshot *serverSnap = [accumulator awaitEventWithName:@"server event"];
  251. XCTAssertFalse(serverSnap.metadata.hasPendingWrites);
  252. XCTAssertEqual(serverSnap.count, 2);
  253. NSDate *when = serverSnap.documents[0][@"when"];
  254. XCTAssertEqualObjects(FIRQuerySnapshotGetData(serverSnap),
  255. (@[ @{@"when" : when}, @{@"when" : when} ]));
  256. }
  257. - (void)testCanWriteTheSameDocumentMultipleTimes {
  258. FIRDocumentReference *doc = [self documentRef];
  259. FSTEventAccumulator *accumulator = [FSTEventAccumulator accumulatorForTest:self];
  260. [doc addSnapshotListenerWithIncludeMetadataChanges:YES listener:accumulator.valueEventHandler];
  261. FIRDocumentSnapshot *initialSnap = [accumulator awaitEventWithName:@"initial event"];
  262. XCTAssertFalse(initialSnap.exists);
  263. XCTestExpectation *expectation = [self expectationWithDescription:@"batch written"];
  264. FIRWriteBatch *batch = [doc.firestore batch];
  265. [batch deleteDocument:doc];
  266. [batch setData:@{@"a" : @1, @"b" : @1, @"when" : @"when"} forDocument:doc];
  267. [batch updateData:@{@"b" : @2, @"when" : [FIRFieldValue fieldValueForServerTimestamp]}
  268. forDocument:doc];
  269. [batch commitWithCompletion:^(NSError *_Nullable error) {
  270. XCTAssertNil(error);
  271. [expectation fulfill];
  272. }];
  273. [self awaitExpectations];
  274. FIRDocumentSnapshot *localSnap = [accumulator awaitEventWithName:@"local event"];
  275. XCTAssertTrue(localSnap.metadata.hasPendingWrites);
  276. XCTAssertEqualObjects(localSnap.data, (@{@"a" : @1, @"b" : @2, @"when" : [NSNull null]}));
  277. FIRDocumentSnapshot *serverSnap = [accumulator awaitEventWithName:@"server event"];
  278. XCTAssertFalse(serverSnap.metadata.hasPendingWrites);
  279. NSDate *when = serverSnap[@"when"];
  280. XCTAssertEqualObjects(serverSnap.data, (@{@"a" : @1, @"b" : @2, @"when" : when}));
  281. }
  282. - (void)testCanWriteVeryLargeBatches {
  283. // On Android, SQLite Cursors are limited reading no more than 2 MB per row (despite being able
  284. // to write very large values). This test verifies that the local MutationQueue is not subject
  285. // to this limitation.
  286. // Create a map containing nearly 1 MB of data. Note that if you use 1024 below this will create
  287. // a document larger than 1 MB, which will be rejected by the backend as too large.
  288. NSString *kb = [@"" stringByPaddingToLength:1000 withString:@"a" startingAtIndex:0];
  289. NSMutableDictionary<NSString *, id> *values = [NSMutableDictionary dictionary];
  290. for (int i = 0; i < 1000; i++) {
  291. values[WrapNSString(CreateAutoId())] = kb;
  292. }
  293. FIRDocumentReference *doc = [self documentRef];
  294. FIRWriteBatch *batch = [doc.firestore batch];
  295. // Write a batch containing 3 copies of the data, creating a ~3 MB batch. Writing to the same
  296. // document in a batch is allowed and so long as the net size of the document is under 1 MB the
  297. // batch is allowed.
  298. [batch setData:values forDocument:doc];
  299. for (int i = 0; i < 2; i++) {
  300. [batch updateData:values forDocument:doc];
  301. }
  302. XCTestExpectation *expectation = [self expectationWithDescription:@"batch written"];
  303. [batch commitWithCompletion:^(NSError *_Nullable error) {
  304. XCTAssertNil(error);
  305. [expectation fulfill];
  306. }];
  307. [self awaitExpectations];
  308. FIRDocumentSnapshot *snap = [self readDocumentForRef:doc];
  309. XCTAssertEqualObjects(values, snap.data);
  310. }
  311. // Returns how much memory the test application is currently using, in megabytes (fractional part is
  312. // truncated), or -1 if the OS call fails.
  313. // TODO(varconst): move the helper function and the test into a new test target for performance
  314. // testing.
  315. int64_t GetCurrentMemoryUsedInMb() {
  316. mach_task_basic_info taskInfo;
  317. mach_msg_type_number_t taskInfoSize = MACH_TASK_BASIC_INFO_COUNT;
  318. const auto errorCode =
  319. task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&taskInfo, &taskInfoSize);
  320. if (errorCode == KERN_SUCCESS) {
  321. const int bytesInMegabyte = 1024 * 1024;
  322. return taskInfo.resident_size / bytesInMegabyte;
  323. }
  324. return -1;
  325. }
  326. - (void)testReasonableMemoryUsageForLotsOfMutations {
  327. XCTestExpectation *expectation =
  328. [self expectationWithDescription:@"testReasonableMemoryUsageForLotsOfMutations"];
  329. FIRDocumentReference *mainDoc = [self documentRef];
  330. FIRWriteBatch *batch = [mainDoc.firestore batch];
  331. // > 500 mutations will be rejected.
  332. const int maxMutations = 500;
  333. for (int i = 0; i != maxMutations; ++i) {
  334. FIRDocumentReference *nestedDoc = [[mainDoc collectionWithPath:@"nested"] documentWithAutoID];
  335. // The exact data doesn't matter; what is important is the large number of mutations.
  336. [batch setData:@{
  337. @"a" : @"foo",
  338. @"b" : @"bar",
  339. }
  340. forDocument:nestedDoc];
  341. }
  342. const int64_t memoryUsedBeforeCommitMb = GetCurrentMemoryUsedInMb();
  343. XCTAssertNotEqual(memoryUsedBeforeCommitMb, -1);
  344. [batch commitWithCompletion:^(NSError *_Nullable error) {
  345. XCTAssertNil(error);
  346. const int64_t memoryUsedAfterCommitMb = GetCurrentMemoryUsedInMb();
  347. XCTAssertNotEqual(memoryUsedAfterCommitMb, -1);
  348. const int64_t memoryDeltaMb = memoryUsedAfterCommitMb - memoryUsedBeforeCommitMb;
  349. // This by its nature cannot be a precise value. Runs on simulator seem to give an increase of
  350. // 10MB in debug mode pretty consistently. A regression would be on the scale of 500Mb.
  351. XCTAssertLessThan(memoryDeltaMb, 20);
  352. [expectation fulfill];
  353. }];
  354. [self awaitExpectations];
  355. }
  356. @end
  357. NS_ASSUME_NONNULL_END