FSTIntegrationTestCase.mm 20 KB

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