FSTIntegrationTestCase.mm 17 KB

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