FIRWriteBatchTests.mm 17 KB

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