FIRWriteBatchTests.mm 17 KB

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