FSTIntegrationTestCase.mm 17 KB

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