FSTTransactionTests.mm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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 <atomic>
  19. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  20. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  21. using firebase::firestore::util::TimerId;
  22. @interface FSTTransactionTests : FSTIntegrationTestCase
  23. @end
  24. /**
  25. * This category is to handle the use of assertions in `FSTTransactionTester`, since XCTest
  26. * assertions do not work in classes that don't extend XCTestCase.
  27. */
  28. @interface FSTTransactionTests (Assertions)
  29. - (void)assertExistsWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error;
  30. - (void)assertDoesNotExistWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error;
  31. - (void)assertNilError:(NSError *)error message:(NSString *)message;
  32. - (void)assertError:(NSError *)error message:(NSString *)message code:(NSInteger)code;
  33. - (void)assertSnapshot:(FIRDocumentSnapshot *)snapshot
  34. equalsObject:(NSObject *)expected
  35. error:(NSError *)error;
  36. @end
  37. @implementation FSTTransactionTests (Assertions)
  38. - (void)assertExistsWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error {
  39. XCTAssertNil(error);
  40. XCTAssertTrue(snapshot.exists);
  41. }
  42. - (void)assertDoesNotExistWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error {
  43. XCTAssertNil(error);
  44. XCTAssertFalse(snapshot.exists);
  45. }
  46. - (void)assertNilError:(NSError *)error message:(NSString *)message {
  47. XCTAssertNil(error, @"%@", message);
  48. }
  49. - (void)assertError:(NSError *)error message:(NSString *)message code:(NSInteger)code {
  50. XCTAssertNotNil(error, @"%@", message);
  51. XCTAssertEqual(error.code, code, @"%@", message);
  52. }
  53. - (void)assertSnapshot:(FIRDocumentSnapshot *)snapshot
  54. equalsObject:(NSObject *)expected
  55. error:(NSError *)error {
  56. XCTAssertNil(error);
  57. XCTAssertTrue(snapshot.exists);
  58. XCTAssertEqualObjects(expected, snapshot.data);
  59. }
  60. @end
  61. typedef void (^TransactionStage)(FIRTransaction *, FIRDocumentReference *);
  62. /**
  63. * The transaction stages that follow are postfixed by numbers to indicate the calling order. For
  64. * example, calling `set1` followed by `set2` should result in the document being set to the value
  65. * specified by `set2`.
  66. */
  67. TransactionStage delete1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  68. [transaction deleteDocument:doc];
  69. };
  70. TransactionStage update1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  71. [transaction updateData:@{@"foo" : @"bar1"} forDocument:doc];
  72. };
  73. TransactionStage update2 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  74. [transaction updateData:@{@"foo" : @"bar2"} forDocument:doc];
  75. };
  76. TransactionStage set1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  77. [transaction setData:@{@"foo" : @"bar1"} forDocument:doc];
  78. };
  79. TransactionStage set2 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  80. [transaction setData:@{@"foo" : @"bar2"} forDocument:doc];
  81. };
  82. TransactionStage get = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  83. NSError *error = nil;
  84. [transaction getDocument:doc error:&error];
  85. };
  86. /**
  87. * Used for testing that all possible combinations of executing transactions result in the desired
  88. * document value or error.
  89. *
  90. * `runWithStages`, `withExistingDoc`, and `withNonexistentDoc` don't actually do anything except
  91. * assign variables into `FSTTransactionTester`.
  92. *
  93. * `expectDoc`, `expectNoDoc`, and `expectError` will trigger the transaction to run and assert
  94. * that the end result matches the input.
  95. */
  96. @interface FSTTransactionTester : NSObject
  97. - (FSTTransactionTester *)withExistingDoc;
  98. - (FSTTransactionTester *)withNonexistentDoc;
  99. - (FSTTransactionTester *)runWithStages:(NSArray<TransactionStage> *)stages;
  100. - (void)expectDoc:(NSObject *)expected;
  101. - (void)expectNoDoc;
  102. - (void)expectError:(FIRFirestoreErrorCode)expected;
  103. @end
  104. @implementation FSTTransactionTester {
  105. FIRFirestore *_db;
  106. FIRDocumentReference *_docRef;
  107. BOOL _fromExistingDoc;
  108. NSArray<TransactionStage> *_stages;
  109. FSTTransactionTests *_testCase;
  110. NSMutableArray<XCTestExpectation *> *_testExpectations;
  111. }
  112. - (instancetype)initWithDb:(FIRFirestore *)db testCase:(FSTTransactionTests *)testCase {
  113. self = [super init];
  114. if (self) {
  115. _db = db;
  116. _stages = [NSArray array];
  117. _testCase = testCase;
  118. _testExpectations = [NSMutableArray array];
  119. }
  120. return self;
  121. }
  122. - (FSTTransactionTester *)withExistingDoc {
  123. _fromExistingDoc = YES;
  124. return self;
  125. }
  126. - (FSTTransactionTester *)withNonexistentDoc {
  127. _fromExistingDoc = NO;
  128. return self;
  129. }
  130. - (FSTTransactionTester *)runWithStages:(NSArray<TransactionStage> *)stages {
  131. _stages = stages;
  132. return self;
  133. }
  134. - (void)expectDoc:(NSObject *)expected {
  135. [self prepareDoc];
  136. [self runSuccessfulTransaction];
  137. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"expectDoc"];
  138. [_docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  139. [self->_testCase assertSnapshot:snapshot equalsObject:expected error:error];
  140. [expectation fulfill];
  141. }];
  142. [_testCase awaitExpectations];
  143. [self cleanupTester];
  144. }
  145. - (void)expectNoDoc {
  146. [self prepareDoc];
  147. [self runSuccessfulTransaction];
  148. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"expectNoDoc"];
  149. [_docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  150. [self->_testCase assertDoesNotExistWithSnapshot:snapshot error:error];
  151. [expectation fulfill];
  152. }];
  153. [_testCase awaitExpectations];
  154. [self cleanupTester];
  155. }
  156. - (void)expectError:(FIRFirestoreErrorCode)expected {
  157. [self prepareDoc];
  158. [self runFailingTransactionWithError:expected];
  159. [self cleanupTester];
  160. }
  161. - (void)prepareDoc {
  162. _docRef = [[_db collectionWithPath:@"nonexistent"] documentWithAutoID];
  163. if (_fromExistingDoc) {
  164. NSError *setError = [self writeDocumentRef:_docRef data:@{@"foo" : @"bar"}];
  165. NSString *message = [NSString stringWithFormat:@"Failed set at %@", [self stageNames]];
  166. [_testCase assertNilError:setError message:message];
  167. }
  168. }
  169. - (NSError *)writeDocumentRef:(FIRDocumentReference *)ref
  170. data:(NSDictionary<NSString *, id> *)data {
  171. __block NSError *errorResult;
  172. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"prepareDoc:set"];
  173. [ref setData:data
  174. completion:^(NSError *error) {
  175. errorResult = error;
  176. [expectation fulfill];
  177. }];
  178. [_testCase awaitExpectations];
  179. return errorResult;
  180. }
  181. - (void)runSuccessfulTransaction {
  182. XCTestExpectation *expectation =
  183. [_testCase expectationWithDescription:@"runSuccessfulTransaction"];
  184. [_db
  185. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  186. for (TransactionStage stage in self->_stages) {
  187. stage(transaction, self->_docRef);
  188. }
  189. return @YES;
  190. }
  191. completion:^(id, NSError *error) {
  192. [expectation fulfill];
  193. NSString *message =
  194. [NSString stringWithFormat:@"Expected the sequence %@, to succeed, but got %d.",
  195. [self stageNames], (int)[error code]];
  196. [self->_testCase assertNilError:error message:message];
  197. }];
  198. [_testCase awaitExpectations];
  199. }
  200. - (void)runFailingTransactionWithError:(FIRFirestoreErrorCode)expected {
  201. (void)expected;
  202. XCTestExpectation *expectation =
  203. [_testCase expectationWithDescription:@"runFailingTransactionWithError"];
  204. [_db
  205. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  206. for (TransactionStage stage in self->_stages) {
  207. stage(transaction, self->_docRef);
  208. }
  209. return @YES;
  210. }
  211. completion:^(id, NSError *_Nullable error) {
  212. [expectation fulfill];
  213. NSString *message =
  214. [NSString stringWithFormat:@"Expected the sequence (%@), to fail, but it didn't.",
  215. [self stageNames]];
  216. [self->_testCase assertError:error message:message code:expected];
  217. }];
  218. [_testCase awaitExpectations];
  219. }
  220. - (void)cleanupTester {
  221. _stages = [NSArray array];
  222. // Set the docRef to something else to lose the original reference.
  223. _docRef = [[self->_db collectionWithPath:@"reset"] documentWithAutoID];
  224. }
  225. - (NSString *)stageNames {
  226. NSMutableArray<NSString *> *seqList = [NSMutableArray array];
  227. for (TransactionStage stage in _stages) {
  228. if (stage == delete1) {
  229. [seqList addObject:@"delete"];
  230. } else if (stage == update1 || stage == update2) {
  231. [seqList addObject:@"update"];
  232. } else if (stage == set1 || stage == set2) {
  233. [seqList addObject:@"set"];
  234. } else if (stage == get) {
  235. [seqList addObject:@"get"];
  236. }
  237. }
  238. return [seqList description];
  239. }
  240. @end
  241. @implementation FSTTransactionTests
  242. - (void)testRunsTransactionsAfterGettingExistingDoc {
  243. FIRFirestore *firestore = [self firestore];
  244. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  245. [[[tt withExistingDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  246. [[[tt withExistingDoc] runWithStages:@[ get, delete1, update2 ]]
  247. expectError:FIRFirestoreErrorCodeInvalidArgument];
  248. [[[tt withExistingDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  249. [[[tt withExistingDoc] runWithStages:@[ get, update1, delete1 ]] expectNoDoc];
  250. [[[tt withExistingDoc] runWithStages:@[ get, update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  251. [[[tt withExistingDoc] runWithStages:@[ get, update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  252. [[[tt withExistingDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  253. [[[tt withExistingDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  254. [[[tt withExistingDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  255. }
  256. - (void)testRunsTransactionsAfterGettingNonexistentDoc {
  257. FIRFirestore *firestore = [self firestore];
  258. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  259. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  260. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, update2 ]]
  261. expectError:FIRFirestoreErrorCodeInvalidArgument];
  262. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  263. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, delete1 ]]
  264. expectError:FIRFirestoreErrorCodeInvalidArgument];
  265. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, update2 ]]
  266. expectError:FIRFirestoreErrorCodeInvalidArgument];
  267. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, set2 ]]
  268. expectError:FIRFirestoreErrorCodeInvalidArgument];
  269. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  270. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  271. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  272. }
  273. - (void)testRunsTransactionOnExistingDoc {
  274. FIRFirestore *firestore = [self firestore];
  275. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  276. [[[tt withExistingDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  277. [[[tt withExistingDoc] runWithStages:@[ delete1, update2 ]]
  278. expectError:FIRFirestoreErrorCodeInvalidArgument];
  279. [[[tt withExistingDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  280. [[[tt withExistingDoc] runWithStages:@[ update1, delete1 ]] expectNoDoc];
  281. [[[tt withExistingDoc] runWithStages:@[ update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  282. [[[tt withExistingDoc] runWithStages:@[ update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  283. [[[tt withExistingDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  284. [[[tt withExistingDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  285. [[[tt withExistingDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  286. }
  287. - (void)testRunsTransactionsOnNonexistentDoc {
  288. FIRFirestore *firestore = [self firestore];
  289. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  290. [[[tt withNonexistentDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  291. [[[tt withNonexistentDoc] runWithStages:@[ delete1, update2 ]]
  292. expectError:FIRFirestoreErrorCodeInvalidArgument];
  293. [[[tt withNonexistentDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  294. [[[tt withNonexistentDoc] runWithStages:@[ update1, delete1 ]]
  295. expectError:FIRFirestoreErrorCodeNotFound];
  296. [[[tt withNonexistentDoc] runWithStages:@[ update1, update2 ]]
  297. expectError:FIRFirestoreErrorCodeNotFound];
  298. [[[tt withNonexistentDoc] runWithStages:@[ update1, set2 ]]
  299. expectError:FIRFirestoreErrorCodeNotFound];
  300. [[[tt withNonexistentDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  301. [[[tt withNonexistentDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  302. [[[tt withNonexistentDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  303. }
  304. - (void)testSetDocumentWithMerge {
  305. FIRFirestore *firestore = [self firestore];
  306. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  307. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  308. [firestore
  309. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  310. [transaction setData:@{@"a" : @"b", @"nested" : @{@"a" : @"b"}} forDocument:doc];
  311. [transaction setData:@{@"c" : @"d", @"nested" : @{@"c" : @"d"}} forDocument:doc merge:YES];
  312. return @YES;
  313. }
  314. completion:^(id _Nullable result, NSError *_Nullable error) {
  315. XCTAssertEqualObjects(result, @YES);
  316. XCTAssertNil(error);
  317. [expectation fulfill];
  318. }];
  319. [self awaitExpectations];
  320. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  321. XCTAssertEqualObjects(snapshot.data,
  322. (@{@"a" : @"b", @"c" : @"d", @"nested" : @{@"a" : @"b", @"c" : @"d"}}));
  323. }
  324. - (void)testIncrementTransactionally {
  325. // A barrier to make sure every transaction reaches the same spot.
  326. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  327. auto counter = std::make_shared<std::atomic_int>(0);
  328. FIRFirestore *firestore = [self firestore];
  329. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  330. [self writeDocumentRef:doc data:@{@"count" : @(5.0)}];
  331. // Skip backoff delays.
  332. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  333. // Make 3 transactions that will all increment.
  334. int total = 3;
  335. for (int i = 0; i < total; i++) {
  336. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  337. [firestore
  338. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  339. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  340. XCTAssertNil(*error);
  341. (*counter)++;
  342. // Once all of the transactions have read, allow the first write.
  343. if (*counter == total) {
  344. dispatch_semaphore_signal(writeBarrier);
  345. }
  346. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  347. // Refill the barrier so that the other transactions and retries succeed.
  348. dispatch_semaphore_signal(writeBarrier);
  349. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  350. [transaction setData:@{@"count" : @(newCount)} forDocument:doc];
  351. return @YES;
  352. }
  353. completion:^(id, NSError *) {
  354. [expectation fulfill];
  355. }];
  356. }
  357. [self awaitExpectations];
  358. // Now all transaction should be completed, so check the result.
  359. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  360. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  361. }
  362. - (void)testUpdateTransactionally {
  363. // A barrier to make sure every transaction reaches the same spot.
  364. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  365. auto counter = std::make_shared<std::atomic_int>(0);
  366. FIRFirestore *firestore = [self firestore];
  367. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  368. [self writeDocumentRef:doc data:@{@"count" : @(5.0), @"other" : @"yes"}];
  369. // Skip backoff delays.
  370. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  371. // Make 3 transactions that will all increment.
  372. int total = 3;
  373. for (int i = 0; i < total; i++) {
  374. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  375. [firestore
  376. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  377. int32_t nowStarted = ++(*counter);
  378. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  379. XCTAssertNil(*error);
  380. // Once all of the transactions have read, allow the first write. There should be 3
  381. // initial transaction runs.
  382. if (nowStarted == total) {
  383. XCTAssertEqual(counter->load(), 3);
  384. dispatch_semaphore_signal(writeBarrier);
  385. }
  386. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  387. // Refill the barrier so that the other transactions and retries succeed.
  388. dispatch_semaphore_signal(writeBarrier);
  389. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  390. [transaction updateData:@{@"count" : @(newCount)} forDocument:doc];
  391. return @YES;
  392. }
  393. completion:^(id, NSError *) {
  394. [expectation fulfill];
  395. }];
  396. }
  397. [self awaitExpectations];
  398. // There should be a maximum of 3 retries: once for the 2nd update, and twice for the 3rd update.
  399. XCTAssertLessThanOrEqual(counter->load(), 6);
  400. // Now all transaction should be completed, so check the result.
  401. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  402. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  403. XCTAssertEqualObjects(@"yes", snapshot[@"other"]);
  404. }
  405. - (void)testRetriesWhenDocumentThatWasReadWithoutBeingWrittenChanges {
  406. FIRFirestore *firestore = [self firestore];
  407. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  408. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  409. auto counter = std::make_shared<std::atomic_int>(0);
  410. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  411. // Skip backoff delays.
  412. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  413. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  414. [firestore
  415. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  416. ++(*counter);
  417. // Get the first doc.
  418. [transaction getDocument:doc1 error:error];
  419. XCTAssertNil(*error);
  420. // Do a write outside of the transaction. The first time the
  421. // transaction is tried, this will bump the version, which
  422. // will cause the write to doc2 to fail. The second time, it
  423. // will be a no-op and not bump the version.
  424. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  425. [doc1 setData:@{
  426. @"count" : @(1234)
  427. }
  428. completion:^(NSError *) {
  429. dispatch_semaphore_signal(writeSemaphore);
  430. }];
  431. // We can block on it, because transactions run on a background queue.
  432. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  433. // Now try to update the other doc from within the transaction.
  434. // This should fail once, because we read 15 earlier.
  435. [transaction setData:@{@"count" : @(16)} forDocument:doc2];
  436. return nil;
  437. }
  438. completion:^(id, NSError *_Nullable error) {
  439. XCTAssertNil(error);
  440. XCTAssertEqual(counter->load(), 2);
  441. [expectation fulfill];
  442. }];
  443. [self awaitExpectations];
  444. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc1];
  445. XCTAssertEqualObjects(snapshot[@"count"], @(1234));
  446. }
  447. - (void)testReadingADocTwiceWithDifferentVersions {
  448. FIRFirestore *firestore = [self firestore];
  449. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  450. auto counter = std::make_shared<std::atomic_int>(0);
  451. [self writeDocumentRef:doc data:@{@"count" : @(15.0)}];
  452. // Skip backoff delays.
  453. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  454. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  455. [firestore
  456. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  457. ++(*counter);
  458. // Get the doc once.
  459. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  460. XCTAssertNil(*error);
  461. // Do a write outside of the transaction. Because the transaction will retry, set the
  462. // document to a different value each time.
  463. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  464. [doc setData:@{
  465. @"count" : @(1234 + (int)(*counter))
  466. }
  467. completion:^(NSError *) {
  468. dispatch_semaphore_signal(writeSemaphore);
  469. }];
  470. // We can block on it, because transactions run on a background queue.
  471. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  472. // Get the doc again in the transaction with the new version.
  473. snapshot = [transaction getDocument:doc error:error];
  474. // The get itself will fail, because we already read an earlier version of this document.
  475. // TODO(klimt): Perhaps we shouldn't fail reads for this, but should wait and fail the
  476. // whole transaction? It's an edge-case anyway, as developers shouldn't be reading the same
  477. // doc multiple times. But they need to handle read errors anyway.
  478. XCTAssertNotNil(*error);
  479. return nil;
  480. }
  481. completion:^(id, NSError *_Nullable error) {
  482. [expectation fulfill];
  483. XCTAssertNotNil(error);
  484. XCTAssertEqual(error.code, FIRFirestoreErrorCodeAborted);
  485. }];
  486. [self awaitExpectations];
  487. }
  488. - (void)testReadAndUpdateNonExistentDocumentWithExternalWrite {
  489. FIRFirestore *firestore = [self firestore];
  490. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  491. [firestore
  492. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  493. // Get and update a document that doesn't exist so that the transaction fails.
  494. FIRDocumentReference *doc =
  495. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  496. [transaction getDocument:doc error:error];
  497. XCTAssertNil(*error);
  498. // Do a write outside of the transaction.
  499. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  500. [doc setData:@{
  501. @"count" : @(1234)
  502. }
  503. completion:^(NSError *) {
  504. dispatch_semaphore_signal(writeSemaphore);
  505. }];
  506. // We can block on it, because transactions run on a background queue.
  507. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  508. // Now try to update the other doc from within the transaction.
  509. // This should fail, because the document didn't exist at the
  510. // start of the transaction.
  511. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  512. return nil;
  513. }
  514. completion:^(id, NSError *_Nullable error) {
  515. [expectation fulfill];
  516. XCTAssertNotNil(error);
  517. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  518. }];
  519. [self awaitExpectations];
  520. }
  521. - (void)testCanHaveGetsWithoutMutations {
  522. FIRFirestore *firestore = [self firestore];
  523. FIRDocumentReference *doc = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  524. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  525. [self writeDocumentRef:doc data:@{@"foo" : @"bar"}];
  526. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  527. [firestore
  528. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  529. [transaction getDocument:doc2 error:error];
  530. [transaction getDocument:doc error:error];
  531. return nil;
  532. }
  533. completion:^(id, NSError *_Nullable error) {
  534. XCTAssertNil(error);
  535. [expectation fulfill];
  536. }];
  537. [self awaitExpectations];
  538. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  539. XCTAssertEqualObjects(snapshot[@"foo"], @"bar");
  540. }
  541. - (void)testDoesNotRetryOnPermanentError {
  542. FIRFirestore *firestore = [self firestore];
  543. auto counter = std::make_shared<std::atomic_int>(0);
  544. // Make a transaction that should fail with a permanent error
  545. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  546. [firestore
  547. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  548. ++(*counter);
  549. // Get and update a document that doesn't exist so that the transaction fails.
  550. FIRDocumentReference *doc =
  551. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  552. [transaction getDocument:doc error:error];
  553. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  554. return nil;
  555. }
  556. completion:^(id, NSError *_Nullable error) {
  557. [expectation fulfill];
  558. XCTAssertNotNil(error);
  559. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  560. XCTAssertEqual(counter->load(), 1);
  561. }];
  562. [self awaitExpectations];
  563. }
  564. - (void)testSuccessWithNoTransactionOperations {
  565. FIRFirestore *firestore = [self firestore];
  566. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  567. [firestore
  568. runTransactionWithBlock:^id _Nullable(FIRTransaction *, NSError **) {
  569. return @"yes";
  570. }
  571. completion:^(id _Nullable result, NSError *_Nullable error) {
  572. XCTAssertEqualObjects(result, @"yes");
  573. XCTAssertNil(error);
  574. [expectation fulfill];
  575. }];
  576. [self awaitExpectations];
  577. }
  578. - (void)testCancellationOnError {
  579. FIRFirestore *firestore = [self firestore];
  580. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  581. auto counter = std::make_shared<std::atomic_int>(0);
  582. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  583. [firestore
  584. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  585. ++(*counter);
  586. [transaction setData:@{@"foo" : @"bar"} forDocument:doc];
  587. if (error) {
  588. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:35 userInfo:@{}];
  589. }
  590. return nil;
  591. }
  592. completion:^(id _Nullable result, NSError *_Nullable error) {
  593. XCTAssertNil(result);
  594. XCTAssertNotNil(error);
  595. XCTAssertEqual(error.code, 35);
  596. [expectation fulfill];
  597. }];
  598. [self awaitExpectations];
  599. XCTAssertEqual(counter->load(), 1);
  600. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  601. XCTAssertFalse(snapshot.exists);
  602. }
  603. - (void)testUpdateFieldsWithDotsTransactionally {
  604. FIRDocumentReference *doc = [self documentRef];
  605. XCTestExpectation *expectation =
  606. [self expectationWithDescription:@"testUpdateFieldsWithDotsTransactionally"];
  607. [doc.firestore
  608. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  609. XCTAssertNil(*error);
  610. [transaction setData:@{@"a.b" : @"old", @"c.d" : @"old"} forDocument:doc];
  611. [transaction updateData:@{
  612. [[FIRFieldPath alloc] initWithFields:@[ @"a.b" ]] : @"new"
  613. }
  614. forDocument:doc];
  615. return nil;
  616. }
  617. completion:^(id, NSError *error) {
  618. XCTAssertNil(error);
  619. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  620. XCTAssertNil(error);
  621. XCTAssertEqualObjects(snapshot.data, (@{@"a.b" : @"new", @"c.d" : @"old"}));
  622. }];
  623. [expectation fulfill];
  624. }];
  625. [self awaitExpectations];
  626. }
  627. - (void)testUpdateNestedFieldsTransactionally {
  628. FIRDocumentReference *doc = [self documentRef];
  629. XCTestExpectation *expectation =
  630. [self expectationWithDescription:@"testUpdateNestedFieldsTransactionally"];
  631. [doc.firestore
  632. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  633. XCTAssertNil(*error);
  634. [transaction setData:@{
  635. @"a" : @{@"b" : @"old"},
  636. @"c" : @{@"d" : @"old"},
  637. @"e" : @{@"f" : @"old"}
  638. }
  639. forDocument:doc];
  640. [transaction updateData:@{
  641. @"a.b" : @"new",
  642. [[FIRFieldPath alloc] initWithFields:@[ @"c", @"d" ]] : @"new"
  643. }
  644. forDocument:doc];
  645. return nil;
  646. }
  647. completion:^(id, NSError *error) {
  648. XCTAssertNil(error);
  649. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  650. XCTAssertNil(error);
  651. XCTAssertEqualObjects(snapshot.data, (@{
  652. @"a" : @{@"b" : @"new"},
  653. @"c" : @{@"d" : @"new"},
  654. @"e" : @{@"f" : @"old"}
  655. }));
  656. }];
  657. [expectation fulfill];
  658. }];
  659. [self awaitExpectations];
  660. }
  661. @end