FSTIntegrationTestCase.mm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. 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. _fakeCredentialsProvider = std::make_shared<FakeCredentialsProvider>();
  99. [self clearPersistenceOnce];
  100. [self primeBackend];
  101. _firestores = [NSMutableArray array];
  102. self.db = [self firestore];
  103. self.eventAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  104. }
  105. - (void)tearDown {
  106. @try {
  107. for (FIRFirestore *firestore in _firestores) {
  108. [self terminateFirestore:firestore];
  109. }
  110. } @finally {
  111. _firestores = nil;
  112. [super tearDown];
  113. }
  114. }
  115. /**
  116. * Clears persistence, but only the first time. This ensures that each test
  117. * run is isolated from the last test run, but doesn't allow tests to interfere
  118. * with each other.
  119. */
  120. - (void)clearPersistenceOnce {
  121. static bool clearedPersistence = false;
  122. @synchronized([FSTIntegrationTestCase class]) {
  123. if (clearedPersistence) return;
  124. Path levelDBDir = LevelDbPersistence::AppDataDirectory();
  125. Status status = util::RecursivelyDelete(levelDBDir);
  126. ASSERT_OK(status);
  127. clearedPersistence = true;
  128. }
  129. }
  130. - (FIRFirestore *)firestore {
  131. return [self firestoreWithProjectID:[FSTIntegrationTestCase projectID]];
  132. }
  133. /**
  134. * Figures out what kind of testing environment we're using, and sets up testing defaults to make
  135. * that work.
  136. *
  137. * Several configurations are supported:
  138. * * Mobile Harness, running periocally against prod and nightly, using live SSL certs
  139. * * Hexa built from google3, running on a companion gLinux machine, using self-signed test SSL
  140. * certs
  141. * * Firestore emulator, running on localhost, with SSL disabled
  142. *
  143. * See Firestore/README.md for detailed setup instructions or comments below for which specific
  144. * values trigger which configurations.
  145. */
  146. + (void)setUpDefaults {
  147. if (defaultSettings) return;
  148. defaultSettings = [[FIRFirestoreSettings alloc] init];
  149. defaultSettings.persistenceEnabled = YES;
  150. // Check for a MobileHarness configuration, running against nightly or prod, which have live
  151. // SSL certs.
  152. NSString *project = [[NSProcessInfo processInfo] environment][@"PROJECT_ID"];
  153. NSString *host = [[NSProcessInfo processInfo] environment][@"DATASTORE_HOST"];
  154. if (project && host) {
  155. defaultProjectId = project;
  156. defaultSettings.host = host;
  157. return;
  158. }
  159. // Check for configuration of a prod project via GoogleServices-Info.plist.
  160. FIROptions *options = [FIROptions defaultOptions];
  161. if (options && ![options.projectID isEqualToString:@"abc-xyz-123"]) {
  162. defaultProjectId = options.projectID;
  163. if (host) {
  164. // Allow access to nightly or other hosts via this mechanism too.
  165. defaultSettings.host = host;
  166. }
  167. return;
  168. }
  169. // Otherwise fall back on assuming the emulator or Hexa on localhost.
  170. defaultProjectId = @"test-db";
  171. // Hexa uses a self-signed cert: the first bundle location is used by bazel builds. The second is
  172. // used for github clones.
  173. NSString *certsPath =
  174. [[NSBundle mainBundle] pathForResource:@"PlugIns/IntegrationTests.xctest/CAcert"
  175. ofType:@"pem"];
  176. if (certsPath == nil) {
  177. certsPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"CAcert" ofType:@"pem"];
  178. }
  179. unsigned long long fileSize =
  180. [[[NSFileManager defaultManager] attributesOfItemAtPath:certsPath error:nil] fileSize];
  181. if (fileSize != 0) {
  182. defaultSettings.host = @"localhost:8081";
  183. GrpcConnection::UseTestCertificate(util::MakeString(defaultSettings.host),
  184. Path::FromNSString(certsPath), "test_cert_2");
  185. } else {
  186. // If no cert is set up, configure for the Firestore emulator.
  187. defaultSettings.host = @"localhost:8080";
  188. defaultSettings.sslEnabled = false;
  189. runningAgainstEmulator = true;
  190. // Also issue a warning because the Firestore emulator doesn't completely work yet.
  191. NSLog(@"Please set up a GoogleServices-Info.plist for Firestore in Firestore/Example/App using "
  192. "instructions at <https://github.com/firebase/firebase-ios-sdk#running-sample-apps>. "
  193. "Alternatively, if you're a Googler with a Hexa preproduction environment, run "
  194. "setup_integration_tests.py to properly configure testing SSL certificates.");
  195. }
  196. }
  197. + (NSString *)projectID {
  198. if (!defaultProjectId) {
  199. [self setUpDefaults];
  200. }
  201. return defaultProjectId;
  202. }
  203. + (bool)isRunningAgainstEmulator {
  204. // The only way to determine whether or not we're running against the emulator is to figure out
  205. // which testing environment we're using. Essentially `setUpDefaults` determines
  206. // `runningAgainstEmulator` as a side effect.
  207. if (!defaultProjectId) {
  208. [self setUpDefaults];
  209. }
  210. return runningAgainstEmulator;
  211. }
  212. + (FIRFirestoreSettings *)settings {
  213. [self setUpDefaults];
  214. return defaultSettings;
  215. }
  216. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  217. FIRApp *app = AppForUnitTesting(util::MakeString(projectID));
  218. return [self firestoreWithApp:app];
  219. }
  220. - (FIRFirestore *)firestoreWithApp:(FIRApp *)app {
  221. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  222. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  223. std::string projectID = util::MakeString(app.options.projectID);
  224. FIRFirestore *firestore =
  225. [[FIRFirestore alloc] initWithDatabaseID:DatabaseId(projectID)
  226. persistenceKey:util::MakeString(persistenceKey)
  227. credentialsProvider:_fakeCredentialsProvider
  228. workerQueue:AsyncQueueForTesting()
  229. firebaseApp:app
  230. instanceRegistry:nil];
  231. firestore.settings = [FSTIntegrationTestCase settings];
  232. [_firestores addObject:firestore];
  233. return firestore;
  234. }
  235. - (void)triggerUserChangeWithUid:(NSString *)uid {
  236. _fakeCredentialsProvider->ChangeUser(uid);
  237. }
  238. - (void)primeBackend {
  239. static dispatch_once_t onceToken;
  240. dispatch_once(&onceToken, ^{
  241. [FSTIntegrationTestCase setUpDefaults];
  242. if (runningAgainstEmulator) {
  243. // Priming not required against the emulator.
  244. return;
  245. }
  246. FIRFirestore *db = [self firestore];
  247. XCTestExpectation *watchInitialized =
  248. [self expectationWithDescription:@"Prime backend: Watch initialized"];
  249. __block XCTestExpectation *watchUpdateReceived;
  250. FIRDocumentReference *docRef = [db documentWithPath:[self documentPath]];
  251. id<FIRListenerRegistration> listenerRegistration =
  252. [docRef addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  253. if ([snapshot[@"value"] isEqual:@"done"]) {
  254. [watchUpdateReceived fulfill];
  255. } else {
  256. [watchInitialized fulfill];
  257. }
  258. }];
  259. // Wait for watch to initialize and deliver first event.
  260. [self awaitExpectations];
  261. watchUpdateReceived = [self expectationWithDescription:@"Prime backend: Watch update received"];
  262. // Use a transaction to perform a write without triggering any local events.
  263. [docRef.firestore
  264. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  265. [transaction setData:@{@"value" : @"done"} forDocument:docRef];
  266. return nil;
  267. }
  268. completion:^(id result, NSError *error){
  269. }];
  270. // Wait to see the write on the watch stream.
  271. [self waitForExpectationsWithTimeout:kPrimingTimeout
  272. handler:^(NSError *_Nullable expectationError) {
  273. if (expectationError) {
  274. XCTFail(@"Error waiting for prime backend: %@",
  275. expectationError);
  276. }
  277. }];
  278. [listenerRegistration remove];
  279. [self terminateFirestore:db];
  280. });
  281. }
  282. - (void)terminateFirestore:(FIRFirestore *)firestore {
  283. [firestore terminateWithCompletion:[self completionForExpectationWithName:@"shutdown"]];
  284. [self awaitExpectations];
  285. }
  286. - (void)deleteApp:(FIRApp *)app {
  287. XCTestExpectation *expectation = [self expectationWithDescription:@"Delete app"];
  288. [app deleteApp:^(BOOL completion) {
  289. XCTAssertTrue(completion);
  290. [expectation fulfill];
  291. }];
  292. [self awaitExpectations];
  293. }
  294. - (NSString *)documentPath {
  295. std::string autoId = CreateAutoId();
  296. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  297. }
  298. - (FIRDocumentReference *)documentRef {
  299. return [self.db documentWithPath:[self documentPath]];
  300. }
  301. - (FIRCollectionReference *)collectionRef {
  302. std::string autoId = CreateAutoId();
  303. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  304. return [self.db collectionWithPath:collectionName];
  305. }
  306. - (FIRCollectionReference *)collectionRefWithDocuments:
  307. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  308. FIRCollectionReference *collection = [self collectionRef];
  309. // Use a different instance to write the documents
  310. [self writeAllDocuments:documents
  311. toCollection:[[self firestore] collectionWithPath:collection.path]];
  312. return collection;
  313. }
  314. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  315. toCollection:(FIRCollectionReference *)collection {
  316. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  317. BOOL *stop) {
  318. FIRDocumentReference *ref = [collection documentWithPath:key];
  319. [self writeDocumentRef:ref data:value];
  320. }];
  321. }
  322. - (void)readerAndWriterOnDocumentRef:(void (^)(NSString *path,
  323. FIRDocumentReference *readerRef,
  324. FIRDocumentReference *writerRef))action {
  325. FIRFirestore *reader = self.db; // for clarity
  326. FIRFirestore *writer = [self firestore];
  327. NSString *path = [self documentPath];
  328. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  329. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  330. action(path, readerRef, writerRef);
  331. }
  332. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  333. return [self readDocumentForRef:ref source:FIRFirestoreSourceDefault];
  334. }
  335. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref
  336. source:(FIRFirestoreSource)source {
  337. __block FIRDocumentSnapshot *result;
  338. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  339. [ref getDocumentWithSource:source
  340. completion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  341. XCTAssertNil(error);
  342. result = doc;
  343. [expectation fulfill];
  344. }];
  345. [self awaitExpectations];
  346. return result;
  347. }
  348. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  349. return [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  350. }
  351. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query source:(FIRFirestoreSource)source {
  352. __block FIRQuerySnapshot *result;
  353. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  354. [query getDocumentsWithSource:source
  355. completion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  356. XCTAssertNil(error);
  357. result = documentSet;
  358. [expectation fulfill];
  359. }];
  360. [self awaitExpectations];
  361. return result;
  362. }
  363. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  364. requireOnline:(BOOL)requireOnline {
  365. __block FIRDocumentSnapshot *result;
  366. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  367. id<FIRListenerRegistration> listener = [ref
  368. addSnapshotListenerWithIncludeMetadataChanges:YES
  369. listener:^(FIRDocumentSnapshot *snapshot,
  370. NSError *error) {
  371. XCTAssertNil(error);
  372. if (!requireOnline || !snapshot.metadata.fromCache) {
  373. result = snapshot;
  374. [expectation fulfill];
  375. }
  376. }];
  377. [self awaitExpectations];
  378. [listener remove];
  379. return result;
  380. }
  381. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  382. [ref setData:data completion:[self completionForExpectationWithName:@"setData"]];
  383. [self awaitExpectations];
  384. }
  385. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  386. [ref updateData:data completion:[self completionForExpectationWithName:@"updateData"]];
  387. [self awaitExpectations];
  388. }
  389. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  390. [ref deleteDocumentWithCompletion:[self completionForExpectationWithName:@"deleteDocument"]];
  391. [self awaitExpectations];
  392. }
  393. - (void)mergeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  394. [ref setData:data
  395. merge:YES
  396. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  397. [self awaitExpectations];
  398. }
  399. - (void)mergeDocumentRef:(FIRDocumentReference *)ref
  400. data:(NSDictionary<NSString *, id> *)data
  401. fields:(NSArray<id> *)fields {
  402. [ref setData:data
  403. mergeFields:fields
  404. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  405. [self awaitExpectations];
  406. }
  407. - (void)disableNetwork {
  408. [self.db
  409. disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable Network."]];
  410. [self awaitExpectations];
  411. }
  412. - (void)enableNetwork {
  413. [self.db enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable Network."]];
  414. [self awaitExpectations];
  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