FSTIntegrationTestCase.mm 20 KB

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