FSTIntegrationTestCase.mm 15 KB

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