FSTIntegrationTestCase.mm 26 KB

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