FSTIntegrationTestCase.mm 27 KB

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