FSTIntegrationTestCase.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*
  2. * Copyright 2017 Google LLC
  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 "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  17. #import <FirebaseFirestore/FIRCollectionReference.h>
  18. #import <FirebaseFirestore/FIRDocumentChange.h>
  19. #import <FirebaseFirestore/FIRDocumentReference.h>
  20. #import <FirebaseFirestore/FIRDocumentSnapshot.h>
  21. #import <FirebaseFirestore/FIRFirestore.h>
  22. #import <FirebaseFirestore/FIRFirestoreSettings.h>
  23. #import <FirebaseFirestore/FIRQuerySnapshot.h>
  24. #import <FirebaseFirestore/FIRSnapshotMetadata.h>
  25. #import <FirebaseFirestore/FIRTransaction.h>
  26. #import <FirebaseFirestore/FIRWriteBatch.h>
  27. #include <exception>
  28. #include <memory>
  29. #include <string>
  30. #include <utility>
  31. #import "FirebaseCore/Extension/FIRAppInternal.h"
  32. #import "FirebaseCore/Extension/FIRLogger.h"
  33. #import "FirebaseCore/Extension/FIROptionsInternal.h"
  34. #import "Firestore/Example/Tests/Util/FIRFirestore+Testing.h"
  35. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  36. #import "Firestore/Source/API/FIRAggregateQuery+Internal.h"
  37. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  38. #include "Firestore/core/src/credentials/credentials_provider.h"
  39. #include "Firestore/core/src/credentials/empty_credentials_provider.h"
  40. #include "Firestore/core/src/credentials/user.h"
  41. #include "Firestore/core/src/local/leveldb_opener.h"
  42. #include "Firestore/core/src/model/database_id.h"
  43. #include "Firestore/core/src/remote/firebase_metadata_provider_apple.h"
  44. #include "Firestore/core/src/remote/grpc_connection.h"
  45. #include "Firestore/core/src/util/async_queue.h"
  46. #include "Firestore/core/src/util/autoid.h"
  47. #include "Firestore/core/src/util/filesystem.h"
  48. #include "Firestore/core/src/util/path.h"
  49. #include "Firestore/core/src/util/string_apple.h"
  50. #include "Firestore/core/test/unit/testutil/app_testing.h"
  51. #include "Firestore/core/test/unit/testutil/async_testing.h"
  52. #include "Firestore/core/test/unit/testutil/status_testing.h"
  53. #include "absl/memory/memory.h"
  54. using firebase::firestore::core::DatabaseInfo;
  55. using firebase::firestore::credentials::CredentialChangeListener;
  56. using firebase::firestore::credentials::EmptyAppCheckCredentialsProvider;
  57. using firebase::firestore::credentials::EmptyAuthCredentialsProvider;
  58. using firebase::firestore::credentials::User;
  59. using firebase::firestore::local::LevelDbOpener;
  60. using firebase::firestore::model::DatabaseId;
  61. using firebase::firestore::remote::FirebaseMetadataProviderApple;
  62. using firebase::firestore::testutil::AppForUnitTesting;
  63. using firebase::firestore::testutil::AsyncQueueForTesting;
  64. using firebase::firestore::util::AsyncQueue;
  65. using firebase::firestore::util::CreateAutoId;
  66. using firebase::firestore::util::Filesystem;
  67. using firebase::firestore::util::MakeString;
  68. using firebase::firestore::util::Path;
  69. using firebase::firestore::util::Status;
  70. using firebase::firestore::util::StatusOr;
  71. NS_ASSUME_NONNULL_BEGIN
  72. /**
  73. * Firestore databases can be subject to a ~30s "cold start" delay if they have not been used
  74. * recently, so before any tests run we "prime" the backend.
  75. */
  76. static const double kPrimingTimeout = 45.0;
  77. static NSString *defaultProjectId;
  78. static FIRFirestoreSettings *defaultSettings;
  79. static bool runningAgainstEmulator = false;
  80. // Behaves the same as `EmptyCredentialsProvider` except it can also trigger a user
  81. // change.
  82. class FakeAuthCredentialsProvider : public EmptyAuthCredentialsProvider {
  83. public:
  84. void SetCredentialChangeListener(CredentialChangeListener<User> changeListener) override {
  85. if (changeListener) {
  86. listener_ = std::move(changeListener);
  87. listener_(User::Unauthenticated());
  88. }
  89. }
  90. void ChangeUser(NSString *new_id) {
  91. if (listener_) {
  92. listener_(firebase::firestore::credentials::User::FromUid(new_id));
  93. }
  94. }
  95. private:
  96. CredentialChangeListener<User> listener_;
  97. };
  98. @implementation FSTIntegrationTestCase {
  99. NSMutableArray<FIRFirestore *> *_firestores;
  100. std::shared_ptr<EmptyAppCheckCredentialsProvider> _fakeAppCheckCredentialsProvider;
  101. std::shared_ptr<FakeAuthCredentialsProvider> _fakeAuthCredentialsProvider;
  102. }
  103. - (void)setUp {
  104. [super setUp];
  105. LoadXCTestCaseAwait();
  106. _fakeAppCheckCredentialsProvider = std::make_shared<EmptyAppCheckCredentialsProvider>();
  107. _fakeAuthCredentialsProvider = std::make_shared<FakeAuthCredentialsProvider>();
  108. [self clearPersistenceOnce];
  109. [self primeBackend];
  110. _firestores = [NSMutableArray array];
  111. self.db = [self firestore];
  112. self.eventAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  113. }
  114. - (void)tearDown {
  115. @try {
  116. for (FIRFirestore *firestore in _firestores) {
  117. [self terminateFirestore:firestore];
  118. }
  119. } @finally {
  120. _firestores = nil;
  121. [super tearDown];
  122. }
  123. }
  124. /**
  125. * Clears persistence, but only the first time. This ensures that each test
  126. * run is isolated from the last test run, but doesn't allow tests to interfere
  127. * with each other.
  128. */
  129. - (void)clearPersistenceOnce {
  130. auto *fs = Filesystem::Default();
  131. static bool clearedPersistence = false;
  132. @synchronized([FSTIntegrationTestCase class]) {
  133. if (clearedPersistence) return;
  134. DatabaseInfo dbInfo;
  135. LevelDbOpener opener(dbInfo);
  136. StatusOr<Path> maybeLevelDBDir = opener.FirestoreAppDataDir();
  137. ASSERT_OK(maybeLevelDBDir.status());
  138. Path levelDBDir = std::move(maybeLevelDBDir).ValueOrDie();
  139. Status status = fs->RecursivelyRemove(levelDBDir);
  140. ASSERT_OK(status);
  141. clearedPersistence = true;
  142. }
  143. }
  144. - (FIRFirestore *)firestore {
  145. return [self firestoreWithProjectID:[FSTIntegrationTestCase projectID]];
  146. }
  147. /**
  148. * Figures out what kind of testing environment we're using, and sets up testing defaults to make
  149. * that work.
  150. *
  151. * Several configurations are supported:
  152. * * Mobile Harness, running periocally against prod and nightly, using live SSL certs
  153. * * Firestore emulator, running on localhost, with SSL disabled
  154. *
  155. * See Firestore/README.md for detailed setup instructions or comments below for which specific
  156. * values trigger which configurations.
  157. */
  158. + (void)setUpDefaults {
  159. if (defaultSettings) return;
  160. defaultSettings = [[FIRFirestoreSettings alloc] init];
  161. // Check for a MobileHarness configuration, running against nightly or prod, which have live
  162. // SSL certs.
  163. NSString *project = [[NSProcessInfo processInfo] environment][@"PROJECT_ID"];
  164. NSString *targetBackend = [[NSProcessInfo processInfo] environment][@"TARGET_BACKEND"];
  165. NSString *host;
  166. if (targetBackend) {
  167. if ([targetBackend isEqualToString:@"emulator"]) {
  168. [self setUpEmulatorDefault];
  169. return;
  170. } else if ([targetBackend isEqualToString:@"qa"]) {
  171. host = @"staging-firestore.sandbox.googleapis.com";
  172. } else if ([targetBackend isEqualToString:@"nightly"]) {
  173. host = @"test-firestore.sandbox.googleapis.com";
  174. } else if ([targetBackend isEqualToString:@"prod"]) {
  175. host = @"firestore.googleapis.com";
  176. } else {
  177. @throw [[NSException alloc]
  178. initWithName:@"InvalidArgumentError"
  179. reason:[NSString stringWithFormat:
  180. @"Unexpected TARGET_BACKEND environment variable \"%@\"",
  181. targetBackend]
  182. userInfo:nil];
  183. }
  184. } else {
  185. host = [[NSProcessInfo processInfo] environment][@"DATASTORE_HOST"];
  186. }
  187. if (project && host) {
  188. defaultProjectId = project;
  189. defaultSettings.host = host;
  190. NSLog(@"Integration tests running against %@/%@", defaultSettings.host, defaultProjectId);
  191. return;
  192. }
  193. // Check for configuration of a prod project via GoogleServices-Info.plist.
  194. FIROptions *options = [FIROptions defaultOptions];
  195. if (options && ![options.projectID isEqualToString:@"abc-xyz-123"]) {
  196. defaultProjectId = options.projectID;
  197. if (host) {
  198. // Allow access to nightly or other hosts via this mechanism too.
  199. defaultSettings.host = host;
  200. }
  201. NSLog(@"Integration tests running against %@/%@", defaultSettings.host, defaultProjectId);
  202. return;
  203. }
  204. // Otherwise fall back on assuming the emulator or localhost.
  205. [self setUpEmulatorDefault];
  206. }
  207. + (void)setUpEmulatorDefault {
  208. defaultProjectId = @"test-db";
  209. defaultSettings.host = @"localhost:8080";
  210. defaultSettings.sslEnabled = false;
  211. runningAgainstEmulator = true;
  212. NSLog(@"Integration tests running against the emulator at %@/%@", defaultSettings.host,
  213. defaultProjectId);
  214. }
  215. + (NSString *)projectID {
  216. if (!defaultProjectId) {
  217. [self setUpDefaults];
  218. }
  219. return defaultProjectId;
  220. }
  221. + (bool)isRunningAgainstEmulator {
  222. // The only way to determine whether or not we're running against the emulator is to figure out
  223. // which testing environment we're using. Essentially `setUpDefaults` determines
  224. // `runningAgainstEmulator` as a side effect.
  225. if (!defaultProjectId) {
  226. [self setUpDefaults];
  227. }
  228. return runningAgainstEmulator;
  229. }
  230. + (FIRFirestoreSettings *)settings {
  231. [self setUpDefaults];
  232. return defaultSettings;
  233. }
  234. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  235. FIRApp *app = AppForUnitTesting(MakeString(projectID));
  236. return [self firestoreWithApp:app];
  237. }
  238. - (FIRFirestore *)firestoreWithApp:(FIRApp *)app {
  239. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  240. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  241. std::string projectID = MakeString(app.options.projectID);
  242. FIRFirestore *firestore =
  243. [[FIRFirestore alloc] initWithDatabaseID:DatabaseId(projectID)
  244. persistenceKey:MakeString(persistenceKey)
  245. authCredentialsProvider:_fakeAuthCredentialsProvider
  246. appCheckCredentialsProvider:_fakeAppCheckCredentialsProvider
  247. workerQueue:AsyncQueueForTesting()
  248. firebaseMetadataProvider:absl::make_unique<FirebaseMetadataProviderApple>(app)
  249. firebaseApp:app
  250. instanceRegistry:nil];
  251. firestore.settings = [FSTIntegrationTestCase settings];
  252. [_firestores addObject:firestore];
  253. return firestore;
  254. }
  255. - (void)triggerUserChangeWithUid:(NSString *)uid {
  256. _fakeAuthCredentialsProvider->ChangeUser(uid);
  257. }
  258. - (void)primeBackend {
  259. static dispatch_once_t onceToken;
  260. dispatch_once(&onceToken, ^{
  261. [FSTIntegrationTestCase setUpDefaults];
  262. if (runningAgainstEmulator) {
  263. // Priming not required against the emulator.
  264. return;
  265. }
  266. FIRFirestore *db = [self firestore];
  267. XCTestExpectation *watchInitialized =
  268. [self expectationWithDescription:@"Prime backend: Watch initialized"];
  269. __block XCTestExpectation *watchUpdateReceived;
  270. FIRDocumentReference *docRef = [db documentWithPath:[self documentPath]];
  271. id<FIRListenerRegistration> listenerRegistration =
  272. [docRef addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *) {
  273. if ([snapshot[@"value"] isEqual:@"done"]) {
  274. [watchUpdateReceived fulfill];
  275. } else {
  276. [watchInitialized fulfill];
  277. }
  278. }];
  279. // Wait for watch to initialize and deliver first event.
  280. [self awaitExpectation:watchInitialized];
  281. watchUpdateReceived = [self expectationWithDescription:@"Prime backend: Watch update received"];
  282. // Use a transaction to perform a write without triggering any local events.
  283. [docRef.firestore
  284. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **) {
  285. [transaction setData:@{@"value" : @"done"} forDocument:docRef];
  286. return nil;
  287. }
  288. completion:^(id, NSError *){
  289. }];
  290. // Wait to see the write on the watch stream.
  291. [self waitForExpectationsWithTimeout:kPrimingTimeout
  292. handler:^(NSError *_Nullable expectationError) {
  293. if (expectationError) {
  294. XCTFail(@"Error waiting for prime backend: %@",
  295. expectationError);
  296. }
  297. }];
  298. [listenerRegistration remove];
  299. [self terminateFirestore:db];
  300. });
  301. }
  302. - (void)terminateFirestore:(FIRFirestore *)firestore {
  303. XCTestExpectation *expectation = [self expectationWithDescription:@"shutdown"];
  304. [firestore terminateWithCompletion:[self completionForExpectation:expectation]];
  305. [self awaitExpectation:expectation];
  306. }
  307. - (void)deleteApp:(FIRApp *)app {
  308. XCTestExpectation *expectation = [self expectationWithDescription:@"deleteApp"];
  309. [app deleteApp:^(BOOL completion) {
  310. XCTAssertTrue(completion);
  311. [expectation fulfill];
  312. }];
  313. [self awaitExpectation:expectation];
  314. }
  315. - (NSString *)documentPath {
  316. std::string autoId = CreateAutoId();
  317. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  318. }
  319. - (FIRDocumentReference *)documentRef {
  320. return [self.db documentWithPath:[self documentPath]];
  321. }
  322. - (FIRCollectionReference *)collectionRef {
  323. std::string autoId = CreateAutoId();
  324. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  325. return [self.db collectionWithPath:collectionName];
  326. }
  327. - (FIRCollectionReference *)collectionRefWithDocuments:
  328. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  329. FIRCollectionReference *collection = [self collectionRef];
  330. // Use a different instance to write the documents
  331. [self writeAllDocuments:documents
  332. toCollection:[[self firestore] collectionWithPath:collection.path]];
  333. return collection;
  334. }
  335. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  336. toCollection:(FIRCollectionReference *)collection {
  337. NSMutableArray<XCTestExpectation *> *commits = [[NSMutableArray alloc] init];
  338. __block FIRWriteBatch *writeBatch = nil;
  339. __block int writeBatchSize = 0;
  340. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  341. BOOL *) {
  342. if (writeBatch == nil) {
  343. writeBatch = [collection.firestore batch];
  344. }
  345. [writeBatch setData:value forDocument:[collection documentWithPath:key]];
  346. writeBatchSize++;
  347. // Write batches are capped at 500 writes. Use 400 just to be safe.
  348. if (writeBatchSize == 400) {
  349. XCTestExpectation *commitExpectation = [self expectationWithDescription:@"WriteBatch commit"];
  350. [writeBatch commitWithCompletion:^(NSError *_Nullable error) {
  351. [commitExpectation fulfill];
  352. if (error != nil) {
  353. XCTFail(@"WriteBatch commit failed: %@", error);
  354. }
  355. }];
  356. [commits addObject:commitExpectation];
  357. writeBatch = nil;
  358. writeBatchSize = 0;
  359. }
  360. }];
  361. if (writeBatch != nil) {
  362. XCTestExpectation *commitExpectation = [self expectationWithDescription:@"WriteBatch commit"];
  363. [writeBatch commitWithCompletion:^(NSError *_Nullable error) {
  364. [commitExpectation fulfill];
  365. if (error != nil) {
  366. XCTFail(@"WriteBatch commit failed: %@", error);
  367. }
  368. }];
  369. [commits addObject:commitExpectation];
  370. }
  371. for (XCTestExpectation *commitExpectation in commits) {
  372. [self awaitExpectation:commitExpectation];
  373. }
  374. }
  375. - (void)readerAndWriterOnDocumentRef:(void (^)(FIRDocumentReference *readerRef,
  376. FIRDocumentReference *writerRef))action {
  377. FIRFirestore *reader = self.db; // for clarity
  378. FIRFirestore *writer = [self firestore];
  379. NSString *path = [self documentPath];
  380. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  381. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  382. action(readerRef, writerRef);
  383. }
  384. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  385. return [self readDocumentForRef:ref source:FIRFirestoreSourceDefault];
  386. }
  387. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref
  388. source:(FIRFirestoreSource)source {
  389. __block FIRDocumentSnapshot *result;
  390. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  391. [ref getDocumentWithSource:source
  392. completion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  393. XCTAssertNil(error);
  394. result = doc;
  395. [expectation fulfill];
  396. }];
  397. [self awaitExpectation:expectation];
  398. return result;
  399. }
  400. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  401. return [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  402. }
  403. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query source:(FIRFirestoreSource)source {
  404. if (query == nil) {
  405. XCTFail("Trying to read data from a nil query");
  406. }
  407. __block FIRQuerySnapshot *result;
  408. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  409. [query getDocumentsWithSource:source
  410. completion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  411. XCTAssertNil(error);
  412. result = documentSet;
  413. [expectation fulfill];
  414. }];
  415. [self awaitExpectation:expectation];
  416. return result;
  417. }
  418. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  419. requireOnline:(BOOL)requireOnline {
  420. __block FIRDocumentSnapshot *result;
  421. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  422. id<FIRListenerRegistration> listener = [ref
  423. addSnapshotListenerWithIncludeMetadataChanges:YES
  424. listener:^(FIRDocumentSnapshot *snapshot,
  425. NSError *error) {
  426. XCTAssertNil(error);
  427. if (!requireOnline || !snapshot.metadata.fromCache) {
  428. result = snapshot;
  429. [expectation fulfill];
  430. }
  431. }];
  432. [self awaitExpectation:expectation];
  433. [listener remove];
  434. return result;
  435. }
  436. - (FIRAggregateQuerySnapshot *)readSnapshotForAggregate:(FIRAggregateQuery *)query {
  437. __block FIRAggregateQuerySnapshot *result;
  438. XCTestExpectation *expectation = [self expectationWithDescription:@"aggregate result"];
  439. [query aggregationWithSource:FIRAggregateSourceServer
  440. completion:^(FIRAggregateQuerySnapshot *snapshot, NSError *error) {
  441. XCTAssertNil(error);
  442. result = snapshot;
  443. [expectation fulfill];
  444. }];
  445. [self awaitExpectation:expectation];
  446. return result;
  447. }
  448. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  449. XCTestExpectation *expectation = [self expectationWithDescription:@"setData"];
  450. [ref setData:data completion:[self completionForExpectation:expectation]];
  451. [self awaitExpectation:expectation];
  452. }
  453. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  454. XCTestExpectation *expectation = [self expectationWithDescription:@"updateData"];
  455. [ref updateData:data completion:[self completionForExpectation:expectation]];
  456. [self awaitExpectation:expectation];
  457. }
  458. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  459. XCTestExpectation *expectation = [self expectationWithDescription:@"deleteDocument"];
  460. [ref deleteDocumentWithCompletion:[self completionForExpectation:expectation]];
  461. [self awaitExpectation:expectation];
  462. }
  463. - (FIRDocumentReference *)addDocumentRef:(FIRCollectionReference *)ref
  464. data:(NSDictionary<NSString *, id> *)data {
  465. XCTestExpectation *expectation = [self expectationWithDescription:@"addDocument"];
  466. FIRDocumentReference *doc = [ref addDocumentWithData:data
  467. completion:[self completionForExpectation:expectation]];
  468. [self awaitExpectation:expectation];
  469. return doc;
  470. }
  471. - (void)mergeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  472. XCTestExpectation *expectation = [self expectationWithDescription:@"setDataWithMerge"];
  473. [ref setData:data merge:YES completion:[self completionForExpectation:expectation]];
  474. [self awaitExpectation:expectation];
  475. }
  476. - (void)mergeDocumentRef:(FIRDocumentReference *)ref
  477. data:(NSDictionary<NSString *, id> *)data
  478. fields:(NSArray<id> *)fields {
  479. XCTestExpectation *expectation = [self expectationWithDescription:@"setDataWithMerge"];
  480. [ref setData:data mergeFields:fields completion:[self completionForExpectation:expectation]];
  481. [self awaitExpectation:expectation];
  482. }
  483. - (void)disableNetwork {
  484. XCTestExpectation *expectation = [self expectationWithDescription:@"disableNetwork"];
  485. [self.db disableNetworkWithCompletion:[self completionForExpectation:expectation]];
  486. [self awaitExpectation:expectation];
  487. }
  488. - (void)enableNetwork {
  489. XCTestExpectation *expectation = [self expectationWithDescription:@"enableNetwork"];
  490. [self.db enableNetworkWithCompletion:[self completionForExpectation:expectation]];
  491. [self awaitExpectation:expectation];
  492. }
  493. - (const std::shared_ptr<AsyncQueue> &)queueForFirestore:(FIRFirestore *)firestore {
  494. return [firestore workerQueue];
  495. }
  496. - (void)waitUntil:(BOOL (^)())predicate {
  497. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  498. double waitSeconds = [self defaultExpectationWaitSeconds];
  499. while (!predicate() && ([NSDate timeIntervalSinceReferenceDate] - start < waitSeconds)) {
  500. // This waits for the next event or until the 100ms timeout is reached
  501. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  502. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  503. }
  504. if (!predicate()) {
  505. XCTFail(@"Timeout");
  506. }
  507. }
  508. extern "C" NSArray<NSDictionary<NSString *, id> *> *FIRQuerySnapshotGetData(
  509. FIRQuerySnapshot *docs) {
  510. NSMutableArray<NSDictionary<NSString *, id> *> *result = [NSMutableArray array];
  511. for (FIRDocumentSnapshot *doc in docs.documents) {
  512. [result addObject:doc.data];
  513. }
  514. return result;
  515. }
  516. extern "C" NSArray<NSString *> *FIRQuerySnapshotGetIDs(FIRQuerySnapshot *docs) {
  517. NSMutableArray<NSString *> *result = [NSMutableArray array];
  518. for (FIRDocumentSnapshot *doc in docs.documents) {
  519. [result addObject:doc.documentID];
  520. }
  521. return result;
  522. }
  523. extern "C" NSArray<NSArray<id> *> *FIRQuerySnapshotGetDocChangesData(FIRQuerySnapshot *docs) {
  524. NSMutableArray<NSMutableArray<id> *> *result = [NSMutableArray array];
  525. for (FIRDocumentChange *docChange in docs.documentChanges) {
  526. NSMutableArray<id> *docChangeData = [NSMutableArray array];
  527. [docChangeData addObject:@(docChange.type)];
  528. [docChangeData addObject:docChange.document.documentID];
  529. [docChangeData addObject:docChange.document.data];
  530. [result addObject:docChangeData];
  531. }
  532. return result;
  533. }
  534. extern "C" NSArray<FIRDocumentReference *> *FIRDocumentReferenceArrayFromQuerySnapshot(
  535. FIRQuerySnapshot *docs) {
  536. NSMutableArray<FIRDocumentReference *> *documentReferenceAccumulator =
  537. [[NSMutableArray alloc] init];
  538. for (FIRDocumentSnapshot *documentSnapshot in docs.documents) {
  539. [documentReferenceAccumulator addObject:documentSnapshot.reference];
  540. }
  541. return [documentReferenceAccumulator copy];
  542. }
  543. @end
  544. NS_ASSUME_NONNULL_END