FIRWriteBatchTests.mm 18 KB

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