FSTTransactionTests.mm 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 <libkern/OSAtomic.h>
  19. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  20. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  21. #import "Firestore/Source/Util/FSTClasses.h"
  22. using firebase::firestore::util::TimerId;
  23. @interface FSTTransactionTests : FSTIntegrationTestCase
  24. @end
  25. /**
  26. * This category is to handle the use of assertions in `FSTTransactionTester`, since XCTest
  27. * assertions do not work in classes that don't extend XCTestCase.
  28. */
  29. @interface FSTTransactionTests (Assertions)
  30. - (void)assertExistsWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error;
  31. - (void)assertDoesNotExistWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error;
  32. - (void)assertNilError:(NSError *)error message:(NSString *)message;
  33. - (void)assertError:(NSError *)error message:(NSString *)message;
  34. - (void)assertSnapshot:(FIRDocumentSnapshot *)snapshot
  35. equalsObject:(NSObject *)expected
  36. error:(NSError *)error;
  37. @end
  38. @implementation FSTTransactionTests (Assertions)
  39. - (void)assertExistsWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error {
  40. XCTAssertNil(error);
  41. XCTAssertTrue(snapshot.exists);
  42. }
  43. - (void)assertDoesNotExistWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error {
  44. XCTAssertNil(error);
  45. XCTAssertFalse(snapshot.exists);
  46. }
  47. - (void)assertNilError:(NSError *)error message:(NSString *)message {
  48. XCTAssertNil(error, @"%@", message);
  49. }
  50. - (void)assertError:(NSError *)error message:(NSString *)message {
  51. XCTAssertNotNil(error, @"%@", 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. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"prepareDoc:get"];
  168. [_docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  169. [self->_testCase assertExistsWithSnapshot:snapshot error:error];
  170. [expectation fulfill];
  171. }];
  172. [_testCase awaitExpectations];
  173. }
  174. }
  175. - (NSError *)writeDocumentRef:(FIRDocumentReference *)ref
  176. data:(NSDictionary<NSString *, id> *)data {
  177. __block NSError *errorResult;
  178. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"prepareDoc:set"];
  179. [_docRef setData:data
  180. completion:^(NSError *error) {
  181. errorResult = error;
  182. [expectation fulfill];
  183. }];
  184. [_testCase awaitExpectations];
  185. return errorResult;
  186. }
  187. - (void)runSuccessfulTransaction {
  188. XCTestExpectation *expectation =
  189. [_testCase expectationWithDescription:@"runSuccessfulTransaction"];
  190. [_db
  191. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  192. for (TransactionStage stage in self->_stages) {
  193. stage(transaction, self->_docRef);
  194. }
  195. return @YES;
  196. }
  197. completion:^(id _Nullable result, NSError *_Nullable error) {
  198. [expectation fulfill];
  199. NSString *message =
  200. [NSString stringWithFormat:@"Expected the sequence %@, to succeed, but got %ld.",
  201. [self stageNames], [error code]];
  202. [self->_testCase assertNilError:error message:message];
  203. }];
  204. [_testCase awaitExpectations];
  205. }
  206. - (void)runFailingTransactionWithError:(FIRFirestoreErrorCode)expected {
  207. XCTestExpectation *expectation =
  208. [_testCase expectationWithDescription:@"runFailingTransactionWithError"];
  209. [_db
  210. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  211. for (TransactionStage stage in self->_stages) {
  212. stage(transaction, self->_docRef);
  213. }
  214. return @YES;
  215. }
  216. completion:^(id _Nullable result, NSError *_Nullable error) {
  217. [expectation fulfill];
  218. NSString *message =
  219. [NSString stringWithFormat:@"Expected the sequence (%@), to fail, but it didn't.",
  220. [self stageNames]];
  221. [self->_testCase assertError:error message:message];
  222. }];
  223. [_testCase awaitExpectations];
  224. }
  225. - (void)cleanupTester {
  226. _stages = [NSArray array];
  227. // Set the docRef to something else to lose the original reference.
  228. _docRef = [[self->_db collectionWithPath:@"reset"] documentWithAutoID];
  229. }
  230. - (NSString *)stageNames {
  231. NSMutableArray<NSString *> *seqList = [NSMutableArray array];
  232. for (TransactionStage stage in _stages) {
  233. if (stage == delete1) {
  234. [seqList addObject:@"delete"];
  235. } else if (stage == update1 || stage == update2) {
  236. [seqList addObject:@"update"];
  237. } else if (stage == set1 || stage == set2) {
  238. [seqList addObject:@"set"];
  239. } else if (stage == get) {
  240. [seqList addObject:@"get"];
  241. }
  242. }
  243. return [seqList description];
  244. }
  245. @end
  246. @implementation FSTTransactionTests
  247. - (void)testRunsTransactionsAfterGettingExistingDoc {
  248. FIRFirestore *firestore = [self firestore];
  249. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  250. [[[tt withExistingDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  251. [[[tt withExistingDoc] runWithStages:@[ get, delete1, update2 ]]
  252. expectError:FIRFirestoreErrorCodeInvalidArgument];
  253. [[[tt withExistingDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  254. [[[tt withExistingDoc] runWithStages:@[ get, update1, delete1 ]] expectNoDoc];
  255. [[[tt withExistingDoc] runWithStages:@[ get, update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  256. [[[tt withExistingDoc] runWithStages:@[ get, update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  257. [[[tt withExistingDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  258. [[[tt withExistingDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  259. [[[tt withExistingDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  260. }
  261. - (void)testRunsTransactionsAfterGettingNonexistentDoc {
  262. FIRFirestore *firestore = [self firestore];
  263. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  264. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  265. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, update2 ]]
  266. expectError:FIRFirestoreErrorCodeInvalidArgument];
  267. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  268. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, delete1 ]]
  269. expectError:FIRFirestoreErrorCodeInvalidArgument];
  270. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, update2 ]]
  271. expectError:FIRFirestoreErrorCodeInvalidArgument];
  272. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, set2 ]]
  273. expectError:FIRFirestoreErrorCodeInvalidArgument];
  274. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  275. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  276. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  277. }
  278. - (void)testRunsTransactionOnExistingDoc {
  279. FIRFirestore *firestore = [self firestore];
  280. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  281. [[[tt withExistingDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  282. [[[tt withExistingDoc] runWithStages:@[ delete1, update2 ]]
  283. expectError:FIRFirestoreErrorCodeInvalidArgument];
  284. [[[tt withExistingDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  285. [[[tt withExistingDoc] runWithStages:@[ update1, delete1 ]] expectNoDoc];
  286. [[[tt withExistingDoc] runWithStages:@[ update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  287. [[[tt withExistingDoc] runWithStages:@[ update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  288. [[[tt withExistingDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  289. [[[tt withExistingDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  290. [[[tt withExistingDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  291. }
  292. - (void)testRunsTransactionsOnNonexistentDoc {
  293. FIRFirestore *firestore = [self firestore];
  294. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  295. [[[tt withNonexistentDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  296. [[[tt withNonexistentDoc] runWithStages:@[ delete1, update2 ]]
  297. expectError:FIRFirestoreErrorCodeInvalidArgument];
  298. [[[tt withNonexistentDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  299. [[[tt withNonexistentDoc] runWithStages:@[ update1, delete1 ]]
  300. expectError:FIRFirestoreErrorCodeNotFound];
  301. [[[tt withNonexistentDoc] runWithStages:@[ update1, update2 ]]
  302. expectError:FIRFirestoreErrorCodeNotFound];
  303. [[[tt withNonexistentDoc] runWithStages:@[ update1, set2 ]]
  304. expectError:FIRFirestoreErrorCodeNotFound];
  305. [[[tt withNonexistentDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  306. [[[tt withNonexistentDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  307. [[[tt withNonexistentDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  308. }
  309. - (void)testGetDocuments {
  310. FIRFirestore *firestore = [self firestore];
  311. FIRDocumentReference *doc = [[firestore collectionWithPath:@"spaces"] documentWithAutoID];
  312. [self writeDocumentRef:doc data:@{@"foo" : @1, @"desc" : @"Stuff", @"owner" : @"Jonny"}];
  313. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  314. [firestore
  315. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  316. [transaction getDocument:doc error:error];
  317. XCTAssertNil(*error);
  318. return @YES;
  319. }
  320. completion:^(id _Nullable result, NSError *_Nullable error) {
  321. XCTAssertNil(result);
  322. // We currently require every document read to also be written.
  323. // TODO(b/34879758): Fix this check once we drop that requirement.
  324. XCTAssertNotNil(error);
  325. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  326. [expectation fulfill];
  327. }];
  328. [self awaitExpectations];
  329. }
  330. - (void)testSetDocumentWithMerge {
  331. FIRFirestore *firestore = [self firestore];
  332. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  333. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  334. [firestore
  335. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  336. [transaction setData:@{@"a" : @"b", @"nested" : @{@"a" : @"b"}} forDocument:doc];
  337. [transaction setData:@{@"c" : @"d", @"nested" : @{@"c" : @"d"}} forDocument:doc merge:YES];
  338. return @YES;
  339. }
  340. completion:^(id _Nullable result, NSError *_Nullable error) {
  341. XCTAssertEqualObjects(@YES, result);
  342. XCTAssertNil(error);
  343. [expectation fulfill];
  344. }];
  345. [self awaitExpectations];
  346. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  347. XCTAssertEqualObjects(snapshot.data,
  348. (@{@"a" : @"b", @"c" : @"d", @"nested" : @{@"a" : @"b", @"c" : @"d"}}));
  349. }
  350. - (void)testIncrementTransactionally {
  351. // A barrier to make sure every transaction reaches the same spot.
  352. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  353. __block volatile int32_t counter = 0;
  354. FIRFirestore *firestore = [self firestore];
  355. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  356. [self writeDocumentRef:doc data:@{@"count" : @(5.0)}];
  357. // Skip backoff delays.
  358. [firestore workerQueue] -> SkipDelaysForTimerId(TimerId::RetryTransaction);
  359. // Make 3 transactions that will all increment.
  360. int total = 3;
  361. for (int i = 0; i < total; i++) {
  362. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  363. [firestore
  364. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  365. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  366. XCTAssertNil(*error);
  367. int32_t nowStarted = OSAtomicIncrement32(&counter);
  368. // Once all of the transactions have read, allow the first write.
  369. if (nowStarted == total) {
  370. dispatch_semaphore_signal(writeBarrier);
  371. }
  372. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  373. // Refill the barrier so that the other transactions and retries succeed.
  374. dispatch_semaphore_signal(writeBarrier);
  375. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  376. [transaction setData:@{@"count" : @(newCount)} forDocument:doc];
  377. return @YES;
  378. }
  379. completion:^(id _Nullable result, NSError *_Nullable error) {
  380. [expectation fulfill];
  381. }];
  382. }
  383. [self awaitExpectations];
  384. // Now all transaction should be completed, so check the result.
  385. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  386. XCTAssertEqualObjects(@(5.0 + total), snapshot[@"count"]);
  387. }
  388. - (void)testUpdateTransactionally {
  389. // A barrier to make sure every transaction reaches the same spot.
  390. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  391. __block volatile int32_t counter = 0;
  392. FIRFirestore *firestore = [self firestore];
  393. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  394. [self writeDocumentRef:doc data:@{@"count" : @(5.0), @"other" : @"yes"}];
  395. // Skip backoff delays.
  396. [firestore workerQueue] -> SkipDelaysForTimerId(TimerId::RetryTransaction);
  397. // Make 3 transactions that will all increment.
  398. int total = 3;
  399. for (int i = 0; i < total; i++) {
  400. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  401. [firestore
  402. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  403. int32_t nowStarted = OSAtomicIncrement32(&counter);
  404. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  405. XCTAssertNil(*error);
  406. // Once all of the transactions have read, allow the first write. There should be 3
  407. // initial transaction runs.
  408. if (nowStarted == total) {
  409. XCTAssertEqual(3, (int)counter);
  410. dispatch_semaphore_signal(writeBarrier);
  411. }
  412. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  413. // Refill the barrier so that the other transactions and retries succeed.
  414. dispatch_semaphore_signal(writeBarrier);
  415. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  416. [transaction updateData:@{@"count" : @(newCount)} forDocument:doc];
  417. return @YES;
  418. }
  419. completion:^(id _Nullable result, NSError *_Nullable error) {
  420. [expectation fulfill];
  421. }];
  422. }
  423. [self awaitExpectations];
  424. // There should be a maximum of 3 retries: once for the 2nd update, and twice for the 3rd update.
  425. XCTAssertLessThanOrEqual((int)counter, 6);
  426. // Now all transaction should be completed, so check the result.
  427. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  428. XCTAssertEqualObjects(@(5.0 + total), snapshot[@"count"]);
  429. XCTAssertEqualObjects(@"yes", snapshot[@"other"]);
  430. }
  431. - (void)testHandleReadingOneDocAndWritingAnother {
  432. FIRFirestore *firestore = [self firestore];
  433. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  434. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  435. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  436. // Skip backoff delays.
  437. [firestore workerQueue] -> SkipDelaysForTimerId(TimerId::RetryTransaction);
  438. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  439. [firestore
  440. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  441. // Get the first doc.
  442. [transaction getDocument:doc1 error:error];
  443. XCTAssertNil(*error);
  444. // Do a write outside of the transaction. The first time the
  445. // transaction is tried, this will bump the version, which
  446. // will cause the write to doc2 to fail. The second time, it
  447. // will be a no-op and not bump the version.
  448. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  449. [doc1 setData:@{
  450. @"count" : @(1234)
  451. }
  452. completion:^(NSError *_Nullable error) {
  453. dispatch_semaphore_signal(writeSemaphore);
  454. }];
  455. // We can block on it, because transactions run on a background queue.
  456. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  457. // Now try to update the other doc from within the transaction.
  458. // This should fail once, because we read 15 earlier.
  459. [transaction setData:@{@"count" : @(16)} forDocument:doc2];
  460. return nil;
  461. }
  462. completion:^(id _Nullable result, NSError *_Nullable error) {
  463. // We currently require every document read to also be written.
  464. // TODO(b/34879758): Add this check back once we drop that.
  465. // NSError *error = nil;
  466. // FIRDocument *snapshot = [transaction getDocument:doc1 error:&error];
  467. // XCTAssertNil(error);
  468. // XCTAssertEquals(0, tries);
  469. // XCTAssertEqualObjects(@(1234), snapshot[@"count"]);
  470. // snapshot = [transaction getDocument:doc2 error:&error];
  471. // XCTAssertNil(error);
  472. // XCTAssertEqualObjects(@(16), snapshot[@"count"]);
  473. XCTAssertNotNil(error);
  474. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  475. [expectation fulfill];
  476. }];
  477. [self awaitExpectations];
  478. }
  479. - (void)testReadingADocTwiceWithDifferentVersions {
  480. FIRFirestore *firestore = [self firestore];
  481. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  482. __block volatile int32_t counter = 0;
  483. [self writeDocumentRef:doc data:@{@"count" : @(15.0)}];
  484. // Skip backoff delays.
  485. [firestore workerQueue] -> SkipDelaysForTimerId(TimerId::RetryTransaction);
  486. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  487. [firestore
  488. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  489. OSAtomicIncrement32(&counter);
  490. // Get the doc once.
  491. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  492. XCTAssertNil(*error);
  493. // Do a write outside of the transaction. Because the transaction will retry, set the
  494. // document to a different value each time.
  495. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  496. [doc setData:@{
  497. @"count" : @(1234 + (int)counter)
  498. }
  499. completion:^(NSError *_Nullable error) {
  500. dispatch_semaphore_signal(writeSemaphore);
  501. }];
  502. // We can block on it, because transactions run on a background queue.
  503. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  504. // Get the doc again in the transaction with the new version.
  505. snapshot = [transaction getDocument:doc error:error];
  506. // The get itself will fail, because we already read an earlier version of this document.
  507. // TODO(klimt): Perhaps we shouldn't fail reads for this, but should wait and fail the
  508. // whole transaction? It's an edge-case anyway, as developers shouldn't be reading the same
  509. // doc multiple times. But they need to handle read errors anyway.
  510. XCTAssertNotNil(*error);
  511. return nil;
  512. }
  513. completion:^(id _Nullable result, NSError *_Nullable error) {
  514. [expectation fulfill];
  515. XCTAssertNotNil(error);
  516. XCTAssertEqual(error.code, FIRFirestoreErrorCodeAborted);
  517. }];
  518. [self awaitExpectations];
  519. }
  520. - (void)testReadAndUpdateNonExistentDocumentWithExternalWrite {
  521. FIRFirestore *firestore = [self firestore];
  522. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  523. [firestore
  524. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  525. // Get and update a document that doesn't exist so that the transaction fails.
  526. FIRDocumentReference *doc =
  527. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  528. [transaction getDocument:doc error:error];
  529. XCTAssertNil(*error);
  530. // Do a write outside of the transaction.
  531. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  532. [doc setData:@{
  533. @"count" : @(1234)
  534. }
  535. completion:^(NSError *_Nullable error) {
  536. dispatch_semaphore_signal(writeSemaphore);
  537. }];
  538. // We can block on it, because transactions run on a background queue.
  539. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  540. // Now try to update the other doc from within the transaction.
  541. // This should fail, because the document didn't exist at the
  542. // start of the transaction.
  543. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  544. return nil;
  545. }
  546. completion:^(id _Nullable result, NSError *_Nullable error) {
  547. [expectation fulfill];
  548. XCTAssertNotNil(error);
  549. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  550. }];
  551. [self awaitExpectations];
  552. }
  553. - (void)testCannotHaveAGetWithoutMutations {
  554. FIRFirestore *firestore = [self firestore];
  555. FIRDocumentReference *doc = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  556. [self writeDocumentRef:doc data:@{@"foo" : @"bar"}];
  557. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  558. [firestore
  559. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  560. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  561. XCTAssertTrue(snapshot.exists);
  562. XCTAssertNil(*error);
  563. return nil;
  564. }
  565. completion:^(id _Nullable result, NSError *_Nullable error) {
  566. // We currently require every document read to also be written.
  567. // TODO(b/34879758): Fix this check once we drop that requirement.
  568. XCTAssertNotNil(error);
  569. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  570. [expectation fulfill];
  571. }];
  572. [self awaitExpectations];
  573. }
  574. - (void)testDoesNotRetryOnPermanentError {
  575. FIRFirestore *firestore = [self firestore];
  576. __block volatile int32_t counter = 0;
  577. // Make a transaction that should fail with a permanent error
  578. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  579. [firestore
  580. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  581. OSAtomicIncrement32(&counter);
  582. // Get and update a document that doesn't exist so that the transaction fails.
  583. FIRDocumentReference *doc =
  584. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  585. [transaction getDocument:doc error:error];
  586. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  587. return nil;
  588. }
  589. completion:^(id _Nullable result, NSError *_Nullable error) {
  590. [expectation fulfill];
  591. XCTAssertNotNil(error);
  592. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  593. XCTAssertEqual(1, (int)counter);
  594. }];
  595. [self awaitExpectations];
  596. }
  597. - (void)testSuccessWithNoTransactionOperations {
  598. FIRFirestore *firestore = [self firestore];
  599. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  600. [firestore
  601. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  602. return @"yes";
  603. }
  604. completion:^(id _Nullable result, NSError *_Nullable error) {
  605. XCTAssertEqualObjects(@"yes", result);
  606. XCTAssertNil(error);
  607. [expectation fulfill];
  608. }];
  609. [self awaitExpectations];
  610. }
  611. - (void)testCancellationOnError {
  612. FIRFirestore *firestore = [self firestore];
  613. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  614. __block volatile int32_t counter = 0;
  615. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  616. [firestore
  617. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  618. OSAtomicIncrement32(&counter);
  619. [transaction setData:@{@"foo" : @"bar"} forDocument:doc];
  620. if (error) {
  621. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:35 userInfo:@{}];
  622. }
  623. return nil;
  624. }
  625. completion:^(id _Nullable result, NSError *_Nullable error) {
  626. XCTAssertNil(result);
  627. XCTAssertNotNil(error);
  628. XCTAssertEqual(35, error.code);
  629. [expectation fulfill];
  630. }];
  631. [self awaitExpectations];
  632. XCTAssertEqual(1, (int)counter);
  633. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  634. XCTAssertFalse(snapshot.exists);
  635. }
  636. - (void)testUpdateFieldsWithDotsTransactionally {
  637. FIRDocumentReference *doc = [self documentRef];
  638. XCTestExpectation *expectation =
  639. [self expectationWithDescription:@"testUpdateFieldsWithDotsTransactionally"];
  640. [doc.firestore
  641. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  642. XCTAssertNil(*error);
  643. [transaction setData:@{@"a.b" : @"old", @"c.d" : @"old"} forDocument:doc];
  644. [transaction updateData:@{
  645. [[FIRFieldPath alloc] initWithFields:@[ @"a.b" ]] : @"new"
  646. }
  647. forDocument:doc];
  648. return nil;
  649. }
  650. completion:^(id result, NSError *error) {
  651. XCTAssertNil(error);
  652. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  653. XCTAssertNil(error);
  654. XCTAssertEqualObjects(snapshot.data, (@{@"a.b" : @"new", @"c.d" : @"old"}));
  655. }];
  656. [expectation fulfill];
  657. }];
  658. [self awaitExpectations];
  659. }
  660. - (void)testUpdateNestedFieldsTransactionally {
  661. FIRDocumentReference *doc = [self documentRef];
  662. XCTestExpectation *expectation =
  663. [self expectationWithDescription:@"testUpdateNestedFieldsTransactionally"];
  664. [doc.firestore
  665. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  666. XCTAssertNil(*error);
  667. [transaction setData:@{
  668. @"a" : @{@"b" : @"old"},
  669. @"c" : @{@"d" : @"old"},
  670. @"e" : @{@"f" : @"old"}
  671. }
  672. forDocument:doc];
  673. [transaction updateData:@{
  674. @"a.b" : @"new",
  675. [[FIRFieldPath alloc] initWithFields:@[ @"c", @"d" ]] : @"new"
  676. }
  677. forDocument:doc];
  678. return nil;
  679. }
  680. completion:^(id result, NSError *error) {
  681. XCTAssertNil(error);
  682. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  683. XCTAssertNil(error);
  684. XCTAssertEqualObjects(snapshot.data, (@{
  685. @"a" : @{@"b" : @"new"},
  686. @"c" : @{@"d" : @"new"},
  687. @"e" : @{@"f" : @"old"}
  688. }));
  689. }];
  690. [expectation fulfill];
  691. }];
  692. [self awaitExpectations];
  693. }
  694. @end