FSTIntegrationTestCase.mm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Copyright 2017 Google
  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 <FirebaseCore/FIRAppInternal.h>
  18. #import <FirebaseCore/FIRLogger.h>
  19. #import <FirebaseCore/FIROptions.h>
  20. #import <FirebaseFirestore/FIRCollectionReference.h>
  21. #import <FirebaseFirestore/FIRDocumentChange.h>
  22. #import <FirebaseFirestore/FIRDocumentReference.h>
  23. #import <FirebaseFirestore/FIRDocumentSnapshot.h>
  24. #import <FirebaseFirestore/FIRFirestore.h>
  25. #import <FirebaseFirestore/FIRFirestoreSettings.h>
  26. #import <FirebaseFirestore/FIRQuerySnapshot.h>
  27. #import <FirebaseFirestore/FIRSnapshotMetadata.h>
  28. #import <FirebaseFirestore/FIRTransaction.h>
  29. #include <memory>
  30. #include <string>
  31. #include <utility>
  32. #import "Firestore/Example/Tests/Util/FIRFirestore+Testing.h"
  33. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  34. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  35. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  36. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  37. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  38. #include "Firestore/core/src/firebase/firestore/local/leveldb_persistence.h"
  39. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  40. #include "Firestore/core/src/firebase/firestore/remote/grpc_connection.h"
  41. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  42. #include "Firestore/core/src/firebase/firestore/util/autoid.h"
  43. #include "Firestore/core/src/firebase/firestore/util/filesystem.h"
  44. #include "Firestore/core/src/firebase/firestore/util/path.h"
  45. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  46. #include "Firestore/core/test/firebase/firestore/testutil/app_testing.h"
  47. #include "Firestore/core/test/firebase/firestore/testutil/async_testing.h"
  48. #include "Firestore/core/test/firebase/firestore/util/status_testing.h"
  49. #include "absl/memory/memory.h"
  50. namespace testutil = firebase::firestore::testutil;
  51. namespace util = firebase::firestore::util;
  52. using firebase::firestore::auth::CredentialChangeListener;
  53. using firebase::firestore::auth::CredentialsProvider;
  54. using firebase::firestore::auth::EmptyCredentialsProvider;
  55. using firebase::firestore::auth::User;
  56. using firebase::firestore::local::LevelDbPersistence;
  57. using firebase::firestore::model::DatabaseId;
  58. using firebase::firestore::testutil::AppForUnitTesting;
  59. using firebase::firestore::testutil::AsyncQueueForTesting;
  60. using firebase::firestore::remote::GrpcConnection;
  61. using firebase::firestore::util::AsyncQueue;
  62. using firebase::firestore::util::CreateAutoId;
  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 FakeCredentialsProvider : public EmptyCredentialsProvider {
  78. public:
  79. void SetCredentialChangeListener(CredentialChangeListener 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::auth::User::FromUid(new_id));
  88. }
  89. }
  90. private:
  91. CredentialChangeListener listener_;
  92. };
  93. @implementation FSTIntegrationTestCase {
  94. NSMutableArray<FIRFirestore *> *_firestores;
  95. std::shared_ptr<FakeCredentialsProvider> _fakeCredentialsProvider;
  96. }
  97. - (void)setUp {
  98. [super setUp];
  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. static bool clearedPersistence = false;
  123. @synchronized([FSTIntegrationTestCase class]) {
  124. if (clearedPersistence) return;
  125. StatusOr<Path> maybe_dir = LevelDbPersistence::AppDataDirectory();
  126. ASSERT_OK(maybe_dir);
  127. Path levelDBDir = maybe_dir.ValueOrDie();
  128. Status status = util::RecursivelyDelete(levelDBDir);
  129. ASSERT_OK(status);
  130. clearedPersistence = true;
  131. }
  132. }
  133. - (FIRFirestore *)firestore {
  134. return [self firestoreWithProjectID:[FSTIntegrationTestCase projectID]];
  135. }
  136. /**
  137. * Figures out what kind of testing environment we're using, and sets up testing defaults to make
  138. * that work.
  139. *
  140. * Several configurations are supported:
  141. * * Mobile Harness, running periocally against prod and nightly, using live SSL certs
  142. * * Hexa built from google3, running on a companion gLinux machine, using self-signed test SSL
  143. * certs
  144. * * Firestore emulator, running on localhost, with SSL disabled
  145. *
  146. * See Firestore/README.md for detailed setup instructions or comments below for which specific
  147. * values trigger which configurations.
  148. */
  149. + (void)setUpDefaults {
  150. if (defaultSettings) return;
  151. defaultSettings = [[FIRFirestoreSettings alloc] init];
  152. defaultSettings.persistenceEnabled = YES;
  153. // Check for a MobileHarness configuration, running against nightly or prod, which have live
  154. // SSL certs.
  155. NSString *project = [[NSProcessInfo processInfo] environment][@"PROJECT_ID"];
  156. NSString *host = [[NSProcessInfo processInfo] environment][@"DATASTORE_HOST"];
  157. if (project && host) {
  158. defaultProjectId = project;
  159. defaultSettings.host = host;
  160. return;
  161. }
  162. // Check for configuration of a prod project via GoogleServices-Info.plist.
  163. FIROptions *options = [FIROptions defaultOptions];
  164. if (options && ![options.projectID isEqualToString:@"abc-xyz-123"]) {
  165. defaultProjectId = options.projectID;
  166. if (host) {
  167. // Allow access to nightly or other hosts via this mechanism too.
  168. defaultSettings.host = host;
  169. }
  170. return;
  171. }
  172. // Otherwise fall back on assuming the emulator or Hexa on localhost.
  173. defaultProjectId = @"test-db";
  174. // Hexa uses a self-signed cert: the first bundle location is used by bazel builds. The second is
  175. // used for github clones.
  176. NSString *certsPath =
  177. [[NSBundle mainBundle] pathForResource:@"PlugIns/IntegrationTests.xctest/CAcert"
  178. ofType:@"pem"];
  179. if (certsPath == nil) {
  180. certsPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"CAcert" ofType:@"pem"];
  181. }
  182. unsigned long long fileSize =
  183. [[[NSFileManager defaultManager] attributesOfItemAtPath:certsPath error:nil] fileSize];
  184. if (fileSize != 0) {
  185. defaultSettings.host = @"localhost:8081";
  186. GrpcConnection::UseTestCertificate(util::MakeString(defaultSettings.host),
  187. Path::FromNSString(certsPath), "test_cert_2");
  188. } else {
  189. // If no cert is set up, configure for the Firestore emulator.
  190. defaultSettings.host = @"localhost:8080";
  191. defaultSettings.sslEnabled = false;
  192. runningAgainstEmulator = true;
  193. // Also issue a warning because the Firestore emulator doesn't completely work yet.
  194. NSLog(@"Please set up a GoogleServices-Info.plist for Firestore in Firestore/Example/App using "
  195. "instructions at <https://github.com/firebase/firebase-ios-sdk#running-sample-apps>. "
  196. "Alternatively, if you're a Googler with a Hexa preproduction environment, run "
  197. "setup_integration_tests.py to properly configure testing SSL certificates.");
  198. }
  199. }
  200. + (NSString *)projectID {
  201. if (!defaultProjectId) {
  202. [self setUpDefaults];
  203. }
  204. return defaultProjectId;
  205. }
  206. + (bool)isRunningAgainstEmulator {
  207. // The only way to determine whether or not we're running against the emulator is to figure out
  208. // which testing environment we're using. Essentially `setUpDefaults` determines
  209. // `runningAgainstEmulator` as a side effect.
  210. if (!defaultProjectId) {
  211. [self setUpDefaults];
  212. }
  213. return runningAgainstEmulator;
  214. }
  215. + (FIRFirestoreSettings *)settings {
  216. [self setUpDefaults];
  217. return defaultSettings;
  218. }
  219. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  220. FIRApp *app = AppForUnitTesting(util::MakeString(projectID));
  221. return [self firestoreWithApp:app];
  222. }
  223. - (FIRFirestore *)firestoreWithApp:(FIRApp *)app {
  224. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  225. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  226. std::string projectID = util::MakeString(app.options.projectID);
  227. FIRFirestore *firestore =
  228. [[FIRFirestore alloc] initWithDatabaseID:DatabaseId(projectID)
  229. persistenceKey:util::MakeString(persistenceKey)
  230. credentialsProvider:_fakeCredentialsProvider
  231. workerQueue:AsyncQueueForTesting()
  232. firebaseApp:app
  233. instanceRegistry:nil];
  234. firestore.settings = [FSTIntegrationTestCase settings];
  235. [_firestores addObject:firestore];
  236. return firestore;
  237. }
  238. - (void)triggerUserChangeWithUid:(NSString *)uid {
  239. _fakeCredentialsProvider->ChangeUser(uid);
  240. }
  241. - (void)primeBackend {
  242. static dispatch_once_t onceToken;
  243. dispatch_once(&onceToken, ^{
  244. [FSTIntegrationTestCase setUpDefaults];
  245. if (runningAgainstEmulator) {
  246. // Priming not required against the emulator.
  247. return;
  248. }
  249. FIRFirestore *db = [self firestore];
  250. XCTestExpectation *watchInitialized =
  251. [self expectationWithDescription:@"Prime backend: Watch initialized"];
  252. __block XCTestExpectation *watchUpdateReceived;
  253. FIRDocumentReference *docRef = [db documentWithPath:[self documentPath]];
  254. id<FIRListenerRegistration> listenerRegistration =
  255. [docRef addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  256. if ([snapshot[@"value"] isEqual:@"done"]) {
  257. [watchUpdateReceived fulfill];
  258. } else {
  259. [watchInitialized fulfill];
  260. }
  261. }];
  262. // Wait for watch to initialize and deliver first event.
  263. [self awaitExpectations];
  264. watchUpdateReceived = [self expectationWithDescription:@"Prime backend: Watch update received"];
  265. // Use a transaction to perform a write without triggering any local events.
  266. [docRef.firestore
  267. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  268. [transaction setData:@{@"value" : @"done"} forDocument:docRef];
  269. return nil;
  270. }
  271. completion:^(id result, NSError *error){
  272. }];
  273. // Wait to see the write on the watch stream.
  274. [self waitForExpectationsWithTimeout:kPrimingTimeout
  275. handler:^(NSError *_Nullable expectationError) {
  276. if (expectationError) {
  277. XCTFail(@"Error waiting for prime backend: %@",
  278. expectationError);
  279. }
  280. }];
  281. [listenerRegistration remove];
  282. [self terminateFirestore:db];
  283. });
  284. }
  285. - (void)terminateFirestore:(FIRFirestore *)firestore {
  286. [firestore terminateWithCompletion:[self completionForExpectationWithName:@"shutdown"]];
  287. [self awaitExpectations];
  288. }
  289. - (void)deleteApp:(FIRApp *)app {
  290. XCTestExpectation *expectation = [self expectationWithDescription:@"Delete app"];
  291. [app deleteApp:^(BOOL completion) {
  292. XCTAssertTrue(completion);
  293. [expectation fulfill];
  294. }];
  295. [self awaitExpectations];
  296. }
  297. - (NSString *)documentPath {
  298. std::string autoId = CreateAutoId();
  299. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  300. }
  301. - (FIRDocumentReference *)documentRef {
  302. return [self.db documentWithPath:[self documentPath]];
  303. }
  304. - (FIRCollectionReference *)collectionRef {
  305. std::string autoId = CreateAutoId();
  306. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  307. return [self.db collectionWithPath:collectionName];
  308. }
  309. - (FIRCollectionReference *)collectionRefWithDocuments:
  310. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  311. FIRCollectionReference *collection = [self collectionRef];
  312. // Use a different instance to write the documents
  313. [self writeAllDocuments:documents
  314. toCollection:[[self firestore] collectionWithPath:collection.path]];
  315. return collection;
  316. }
  317. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  318. toCollection:(FIRCollectionReference *)collection {
  319. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  320. BOOL *stop) {
  321. FIRDocumentReference *ref = [collection documentWithPath:key];
  322. [self writeDocumentRef:ref data:value];
  323. }];
  324. }
  325. - (void)readerAndWriterOnDocumentRef:(void (^)(NSString *path,
  326. FIRDocumentReference *readerRef,
  327. FIRDocumentReference *writerRef))action {
  328. FIRFirestore *reader = self.db; // for clarity
  329. FIRFirestore *writer = [self firestore];
  330. NSString *path = [self documentPath];
  331. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  332. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  333. action(path, readerRef, writerRef);
  334. }
  335. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  336. return [self readDocumentForRef:ref source:FIRFirestoreSourceDefault];
  337. }
  338. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref
  339. source:(FIRFirestoreSource)source {
  340. __block FIRDocumentSnapshot *result;
  341. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  342. [ref getDocumentWithSource:source
  343. completion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  344. XCTAssertNil(error);
  345. result = doc;
  346. [expectation fulfill];
  347. }];
  348. [self awaitExpectations];
  349. return result;
  350. }
  351. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  352. return [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  353. }
  354. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query source:(FIRFirestoreSource)source {
  355. __block FIRQuerySnapshot *result;
  356. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  357. [query getDocumentsWithSource:source
  358. completion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  359. XCTAssertNil(error);
  360. result = documentSet;
  361. [expectation fulfill];
  362. }];
  363. [self awaitExpectations];
  364. return result;
  365. }
  366. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  367. requireOnline:(BOOL)requireOnline {
  368. __block FIRDocumentSnapshot *result;
  369. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  370. id<FIRListenerRegistration> listener = [ref
  371. addSnapshotListenerWithIncludeMetadataChanges:YES
  372. listener:^(FIRDocumentSnapshot *snapshot,
  373. NSError *error) {
  374. XCTAssertNil(error);
  375. if (!requireOnline || !snapshot.metadata.fromCache) {
  376. result = snapshot;
  377. [expectation fulfill];
  378. }
  379. }];
  380. [self awaitExpectations];
  381. [listener remove];
  382. return result;
  383. }
  384. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  385. [ref setData:data completion:[self completionForExpectationWithName:@"setData"]];
  386. [self awaitExpectations];
  387. }
  388. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  389. [ref updateData:data completion:[self completionForExpectationWithName:@"updateData"]];
  390. [self awaitExpectations];
  391. }
  392. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  393. [ref deleteDocumentWithCompletion:[self completionForExpectationWithName:@"deleteDocument"]];
  394. [self awaitExpectations];
  395. }
  396. - (void)mergeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  397. [ref setData:data
  398. merge:YES
  399. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  400. [self awaitExpectations];
  401. }
  402. - (void)mergeDocumentRef:(FIRDocumentReference *)ref
  403. data:(NSDictionary<NSString *, id> *)data
  404. fields:(NSArray<id> *)fields {
  405. [ref setData:data
  406. mergeFields:fields
  407. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  408. [self awaitExpectations];
  409. }
  410. - (void)disableNetwork {
  411. [self.db
  412. disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable Network."]];
  413. [self awaitExpectations];
  414. }
  415. - (void)enableNetwork {
  416. [self.db enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable Network."]];
  417. [self awaitExpectations];
  418. }
  419. - (const std::shared_ptr<util::AsyncQueue> &)queueForFirestore:(FIRFirestore *)firestore {
  420. return [firestore workerQueue];
  421. }
  422. - (void)waitUntil:(BOOL (^)())predicate {
  423. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  424. double waitSeconds = [self defaultExpectationWaitSeconds];
  425. while (!predicate() && ([NSDate timeIntervalSinceReferenceDate] - start < waitSeconds)) {
  426. // This waits for the next event or until the 100ms timeout is reached
  427. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  428. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  429. }
  430. if (!predicate()) {
  431. XCTFail(@"Timeout");
  432. }
  433. }
  434. extern "C" NSArray<NSDictionary<NSString *, id> *> *FIRQuerySnapshotGetData(
  435. FIRQuerySnapshot *docs) {
  436. NSMutableArray<NSDictionary<NSString *, id> *> *result = [NSMutableArray array];
  437. for (FIRDocumentSnapshot *doc in docs.documents) {
  438. [result addObject:doc.data];
  439. }
  440. return result;
  441. }
  442. extern "C" NSArray<NSString *> *FIRQuerySnapshotGetIDs(FIRQuerySnapshot *docs) {
  443. NSMutableArray<NSString *> *result = [NSMutableArray array];
  444. for (FIRDocumentSnapshot *doc in docs.documents) {
  445. [result addObject:doc.documentID];
  446. }
  447. return result;
  448. }
  449. extern "C" NSArray<NSArray<id> *> *FIRQuerySnapshotGetDocChangesData(FIRQuerySnapshot *docs) {
  450. NSMutableArray<NSMutableArray<id> *> *result = [NSMutableArray array];
  451. for (FIRDocumentChange *docChange in docs.documentChanges) {
  452. NSMutableArray<id> *docChangeData = [NSMutableArray array];
  453. [docChangeData addObject:@(docChange.type)];
  454. [docChangeData addObject:docChange.document.documentID];
  455. [docChangeData addObject:docChange.document.data];
  456. [result addObject:docChangeData];
  457. }
  458. return result;
  459. }
  460. @end
  461. NS_ASSUME_NONNULL_END