FSTIntegrationTestCase.mm 18 KB

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