FSTIntegrationTestCase.mm 27 KB

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