FSTIntegrationTestCase.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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/FIRLogger.h>
  18. #import <FirebaseCore/FIROptions.h>
  19. #import <FirebaseFirestore/FIRCollectionReference.h>
  20. #import <FirebaseFirestore/FIRDocumentChange.h>
  21. #import <FirebaseFirestore/FIRDocumentReference.h>
  22. #import <FirebaseFirestore/FIRDocumentSnapshot.h>
  23. #import <FirebaseFirestore/FIRFirestore.h>
  24. #import <FirebaseFirestore/FIRFirestoreSettings.h>
  25. #import <FirebaseFirestore/FIRQuerySnapshot.h>
  26. #import <FirebaseFirestore/FIRSnapshotMetadata.h>
  27. #import <FirebaseFirestore/FIRTransaction.h>
  28. #include <memory>
  29. #include <string>
  30. #include <utility>
  31. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  32. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  33. #include "Firestore/core/src/firebase/firestore/remote/grpc_connection.h"
  34. #include "Firestore/core/src/firebase/firestore/util/autoid.h"
  35. #include "Firestore/core/src/firebase/firestore/util/filesystem.h"
  36. #include "Firestore/core/src/firebase/firestore/util/path.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. #include "Firestore/core/test/firebase/firestore/testutil/app_testing.h"
  39. #include "Firestore/core/test/firebase/firestore/util/status_test_util.h"
  40. #include "absl/memory/memory.h"
  41. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  42. #import "Firestore/Source/Core/FSTFirestoreClient.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. @implementation FSTIntegrationTestCase {
  68. NSMutableArray<FIRFirestore *> *_firestores;
  69. }
  70. - (void)setUp {
  71. [super setUp];
  72. [self clearPersistence];
  73. _firestores = [NSMutableArray array];
  74. self.db = [self firestore];
  75. self.eventAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  76. }
  77. - (void)tearDown {
  78. @try {
  79. for (FIRFirestore *firestore in _firestores) {
  80. [self shutdownFirestore:firestore];
  81. }
  82. } @finally {
  83. _firestores = nil;
  84. [super tearDown];
  85. }
  86. }
  87. - (void)clearPersistence {
  88. Path levelDBDir = [FSTLevelDB documentsDirectory];
  89. Status status = util::RecursivelyDelete(levelDBDir);
  90. ASSERT_OK(status);
  91. }
  92. - (FIRFirestore *)firestore {
  93. return [self firestoreWithProjectID:[FSTIntegrationTestCase projectID]];
  94. }
  95. + (void)setUpDefaults {
  96. defaultSettings = [[FIRFirestoreSettings alloc] init];
  97. defaultSettings.persistenceEnabled = YES;
  98. defaultSettings.timestampsInSnapshotsEnabled = YES;
  99. // Check for a MobileHarness configuration, running against nightly or prod, which have live
  100. // SSL certs.
  101. NSString *project = [[NSProcessInfo processInfo] environment][@"PROJECT_ID"];
  102. NSString *host = [[NSProcessInfo processInfo] environment][@"DATASTORE_HOST"];
  103. if (project && host) {
  104. defaultProjectId = project;
  105. defaultSettings.host = host;
  106. return;
  107. }
  108. // Check for configuration of a prod project via GoogleServices-Info.plist.
  109. FIROptions *options = [FIROptions defaultOptions];
  110. if (options && ![options.projectID isEqualToString:@"abc-xyz-123"]) {
  111. defaultProjectId = options.projectID;
  112. if (host) {
  113. // Allow access to nightly or other hosts via this mechanism too.
  114. defaultSettings.host = host;
  115. }
  116. return;
  117. }
  118. // Otherwise fall back on assuming Hexa on localhost.
  119. defaultProjectId = @"test-db";
  120. defaultSettings.host = @"localhost:8081";
  121. // Hexa uses a self-signed cert: the first bundle location is used by bazel builds. The second is
  122. // used for github clones.
  123. NSString *certsPath =
  124. [[NSBundle mainBundle] pathForResource:@"PlugIns/IntegrationTests.xctest/CAcert"
  125. ofType:@"pem"];
  126. if (certsPath == nil) {
  127. certsPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"CAcert" ofType:@"pem"];
  128. }
  129. unsigned long long fileSize =
  130. [[[NSFileManager defaultManager] attributesOfItemAtPath:certsPath error:nil] fileSize];
  131. if (fileSize == 0) {
  132. NSLog(
  133. @"Please set up a GoogleServices-Info.plist for Firestore in Firestore/Example/App using "
  134. "instructions at <https://github.com/firebase/firebase-ios-sdk#running-sample-apps>. "
  135. "Alternatively, if you're a Googler with a Hexa preproduction environment, run "
  136. "setup_integration_tests.py to properly configure testing SSL certificates.");
  137. }
  138. GrpcConnection::UseTestCertificate(util::MakeString(defaultSettings.host),
  139. Path::FromNSString(certsPath), "test_cert_2");
  140. }
  141. + (NSString *)projectID {
  142. if (!defaultProjectId) {
  143. [self setUpDefaults];
  144. }
  145. return defaultProjectId;
  146. }
  147. + (FIRFirestoreSettings *)settings {
  148. if (!defaultSettings) {
  149. [self setUpDefaults];
  150. }
  151. return defaultSettings;
  152. }
  153. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  154. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  155. dispatch_queue_t queue =
  156. dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL);
  157. std::unique_ptr<AsyncQueue> workerQueue =
  158. absl::make_unique<AsyncQueue>(absl::make_unique<ExecutorLibdispatch>(queue));
  159. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  160. FIRApp *app = AppForUnitTesting();
  161. std::unique_ptr<CredentialsProvider> credentials_provider =
  162. absl::make_unique<firebase::firestore::auth::EmptyCredentialsProvider>();
  163. FIRFirestore *firestore = [[FIRFirestore alloc] initWithProjectID:util::MakeString(projectID)
  164. database:DatabaseId::kDefault
  165. persistenceKey:persistenceKey
  166. credentialsProvider:std::move(credentials_provider)
  167. workerQueue:std::move(workerQueue)
  168. firebaseApp:app];
  169. firestore.settings = [FSTIntegrationTestCase settings];
  170. [_firestores addObject:firestore];
  171. [self primeBackend:firestore];
  172. return firestore;
  173. }
  174. - (void)primeBackend:(FIRFirestore *)db {
  175. static dispatch_once_t onceToken;
  176. dispatch_once(&onceToken, ^{
  177. XCTestExpectation *watchInitialized =
  178. [self expectationWithDescription:@"Prime backend: Watch initialized"];
  179. __block XCTestExpectation *watchUpdateReceived;
  180. FIRDocumentReference *docRef = [db documentWithPath:[self documentPath]];
  181. id<FIRListenerRegistration> listenerRegistration =
  182. [docRef addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  183. if ([snapshot[@"value"] isEqual:@"done"]) {
  184. [watchUpdateReceived fulfill];
  185. } else {
  186. [watchInitialized fulfill];
  187. }
  188. }];
  189. // Wait for watch to initialize and deliver first event.
  190. [self awaitExpectations];
  191. watchUpdateReceived = [self expectationWithDescription:@"Prime backend: Watch update received"];
  192. // Use a transaction to perform a write without triggering any local events.
  193. [docRef.firestore
  194. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  195. [transaction setData:@{@"value" : @"done"} forDocument:docRef];
  196. return nil;
  197. }
  198. completion:^(id result, NSError *error){
  199. }];
  200. // Wait to see the write on the watch stream.
  201. [self waitForExpectationsWithTimeout:kPrimingTimeout
  202. handler:^(NSError *_Nullable expectationError) {
  203. if (expectationError) {
  204. XCTFail(@"Error waiting for prime backend: %@",
  205. expectationError);
  206. }
  207. }];
  208. [listenerRegistration remove];
  209. });
  210. }
  211. - (void)shutdownFirestore:(FIRFirestore *)firestore {
  212. [firestore shutdownWithCompletion:[self completionForExpectationWithName:@"shutdown"]];
  213. [self awaitExpectations];
  214. }
  215. - (NSString *)documentPath {
  216. std::string autoId = CreateAutoId();
  217. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  218. }
  219. - (FIRDocumentReference *)documentRef {
  220. return [self.db documentWithPath:[self documentPath]];
  221. }
  222. - (FIRCollectionReference *)collectionRef {
  223. std::string autoId = CreateAutoId();
  224. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  225. return [self.db collectionWithPath:collectionName];
  226. }
  227. - (FIRCollectionReference *)collectionRefWithDocuments:
  228. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  229. FIRCollectionReference *collection = [self collectionRef];
  230. // Use a different instance to write the documents
  231. [self writeAllDocuments:documents
  232. toCollection:[[self firestore] collectionWithPath:collection.path]];
  233. return collection;
  234. }
  235. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  236. toCollection:(FIRCollectionReference *)collection {
  237. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  238. BOOL *stop) {
  239. FIRDocumentReference *ref = [collection documentWithPath:key];
  240. [self writeDocumentRef:ref data:value];
  241. }];
  242. }
  243. - (void)readerAndWriterOnDocumentRef:(void (^)(NSString *path,
  244. FIRDocumentReference *readerRef,
  245. FIRDocumentReference *writerRef))action {
  246. FIRFirestore *reader = self.db; // for clarity
  247. FIRFirestore *writer = [self firestore];
  248. NSString *path = [self documentPath];
  249. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  250. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  251. action(path, readerRef, writerRef);
  252. }
  253. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  254. return [self readDocumentForRef:ref source:FIRFirestoreSourceDefault];
  255. }
  256. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref
  257. source:(FIRFirestoreSource)source {
  258. __block FIRDocumentSnapshot *result;
  259. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  260. [ref getDocumentWithSource:source
  261. completion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  262. XCTAssertNil(error);
  263. result = doc;
  264. [expectation fulfill];
  265. }];
  266. [self awaitExpectations];
  267. return result;
  268. }
  269. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  270. return [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  271. }
  272. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query source:(FIRFirestoreSource)source {
  273. __block FIRQuerySnapshot *result;
  274. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  275. [query getDocumentsWithSource:source
  276. completion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  277. XCTAssertNil(error);
  278. result = documentSet;
  279. [expectation fulfill];
  280. }];
  281. [self awaitExpectations];
  282. return result;
  283. }
  284. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  285. requireOnline:(BOOL)requireOnline {
  286. __block FIRDocumentSnapshot *result;
  287. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  288. id<FIRListenerRegistration> listener = [ref
  289. addSnapshotListenerWithIncludeMetadataChanges:YES
  290. listener:^(FIRDocumentSnapshot *snapshot,
  291. NSError *error) {
  292. XCTAssertNil(error);
  293. if (!requireOnline || !snapshot.metadata.fromCache) {
  294. result = snapshot;
  295. [expectation fulfill];
  296. }
  297. }];
  298. [self awaitExpectations];
  299. [listener remove];
  300. return result;
  301. }
  302. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  303. [ref setData:data completion:[self completionForExpectationWithName:@"setData"]];
  304. [self awaitExpectations];
  305. }
  306. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  307. [ref updateData:data completion:[self completionForExpectationWithName:@"updateData"]];
  308. [self awaitExpectations];
  309. }
  310. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  311. [ref deleteDocumentWithCompletion:[self completionForExpectationWithName:@"deleteDocument"]];
  312. [self awaitExpectations];
  313. }
  314. - (void)mergeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  315. [ref setData:data
  316. merge:YES
  317. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  318. [self awaitExpectations];
  319. }
  320. - (void)mergeDocumentRef:(FIRDocumentReference *)ref
  321. data:(NSDictionary<NSString *, id> *)data
  322. fields:(NSArray<id> *)fields {
  323. [ref setData:data
  324. mergeFields:fields
  325. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  326. [self awaitExpectations];
  327. }
  328. - (void)disableNetwork {
  329. [self.db.client
  330. disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable Network."]];
  331. [self awaitExpectations];
  332. }
  333. - (void)enableNetwork {
  334. [self.db.client
  335. enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable Network."]];
  336. [self awaitExpectations];
  337. }
  338. - (AsyncQueue *)queueForFirestore:(FIRFirestore *)firestore {
  339. return [firestore workerQueue];
  340. }
  341. - (void)waitUntil:(BOOL (^)())predicate {
  342. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  343. double waitSeconds = [self defaultExpectationWaitSeconds];
  344. while (!predicate() && ([NSDate timeIntervalSinceReferenceDate] - start < waitSeconds)) {
  345. // This waits for the next event or until the 100ms timeout is reached
  346. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  347. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  348. }
  349. if (!predicate()) {
  350. XCTFail(@"Timeout");
  351. }
  352. }
  353. extern "C" NSArray<NSDictionary<NSString *, id> *> *FIRQuerySnapshotGetData(
  354. FIRQuerySnapshot *docs) {
  355. NSMutableArray<NSDictionary<NSString *, id> *> *result = [NSMutableArray array];
  356. for (FIRDocumentSnapshot *doc in docs.documents) {
  357. [result addObject:doc.data];
  358. }
  359. return result;
  360. }
  361. extern "C" NSArray<NSString *> *FIRQuerySnapshotGetIDs(FIRQuerySnapshot *docs) {
  362. NSMutableArray<NSString *> *result = [NSMutableArray array];
  363. for (FIRDocumentSnapshot *doc in docs.documents) {
  364. [result addObject:doc.documentID];
  365. }
  366. return result;
  367. }
  368. extern "C" NSArray<NSArray<id> *> *FIRQuerySnapshotGetDocChangesData(FIRQuerySnapshot *docs) {
  369. NSMutableArray<NSMutableArray<id> *> *result = [NSMutableArray array];
  370. for (FIRDocumentChange *docChange in docs.documentChanges) {
  371. NSMutableArray<id> *docChangeData = [NSMutableArray array];
  372. [docChangeData addObject:@(docChange.type)];
  373. [docChangeData addObject:docChange.document.documentID];
  374. [docChangeData addObject:docChange.document.data];
  375. [result addObject:docChangeData];
  376. }
  377. return result;
  378. }
  379. @end
  380. NS_ASSUME_NONNULL_END