FSTIntegrationTestCase.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 <FirebaseFirestore/FirebaseFirestore-umbrella.h>
  19. #import <GRPCClient/GRPCCall+ChannelArg.h>
  20. #import <GRPCClient/GRPCCall+Tests.h>
  21. #include "Firestore/src/core/util/autoid.h"
  22. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  23. #import "Firestore/Source/Auth/FSTEmptyCredentialsProvider.h"
  24. #import "Firestore/Source/Local/FSTLevelDB.h"
  25. #import "Firestore/Source/Model/FSTDatabaseID.h"
  26. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  27. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  28. #import "Firestore/Example/Tests/Util/FSTTestDispatchQueue.h"
  29. NS_ASSUME_NONNULL_BEGIN
  30. @interface FIRFirestore (Testing)
  31. @property(nonatomic, strong) FSTDispatchQueue *workerDispatchQueue;
  32. @end
  33. @implementation FSTIntegrationTestCase {
  34. NSMutableArray<FIRFirestore *> *_firestores;
  35. }
  36. - (void)setUp {
  37. [super setUp];
  38. [self clearPersistence];
  39. _firestores = [NSMutableArray array];
  40. self.db = [self firestore];
  41. self.eventAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  42. }
  43. - (void)tearDown {
  44. @try {
  45. for (FIRFirestore *firestore in _firestores) {
  46. [self shutdownFirestore:firestore];
  47. }
  48. } @finally {
  49. #pragma clang diagnostic push
  50. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  51. [GRPCCall closeOpenConnections];
  52. #pragma clang diagnostic pop
  53. _firestores = nil;
  54. [super tearDown];
  55. }
  56. }
  57. - (void)clearPersistence {
  58. NSString *levelDBDir = [FSTLevelDB documentsDirectory];
  59. NSError *error;
  60. if (![[NSFileManager defaultManager] removeItemAtPath:levelDBDir error:&error]) {
  61. // file not found is okay.
  62. XCTAssertTrue(
  63. [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == NSFileNoSuchFileError,
  64. @"Failed to clear LevelDB Persistence: %@", error);
  65. }
  66. }
  67. - (FIRFirestore *)firestore {
  68. return [self firestoreWithProjectID:[FSTIntegrationTestCase projectID]];
  69. }
  70. + (NSString *)projectID {
  71. NSString *project = [[NSProcessInfo processInfo] environment][@"PROJECT_ID"];
  72. if (!project) {
  73. project = @"test-db";
  74. }
  75. return project;
  76. }
  77. + (FIRFirestoreSettings *)settings {
  78. FIRFirestoreSettings *settings = [[FIRFirestoreSettings alloc] init];
  79. NSString *host = [[NSProcessInfo processInfo] environment][@"DATASTORE_HOST"];
  80. settings.sslEnabled = YES;
  81. if (!host) {
  82. // If host is nil, there is no GoogleService-Info.plist. Check if a hexa integration test
  83. // configuration is configured. The first bundle location is used by bazel builds. The
  84. // second is used for github clones.
  85. host = @"localhost:8081";
  86. settings.sslEnabled = YES;
  87. NSString *certsPath =
  88. [[NSBundle mainBundle] pathForResource:@"PlugIns/IntegrationTests.xctest/CAcert"
  89. ofType:@"pem"];
  90. if (certsPath == nil) {
  91. certsPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"CAcert" ofType:@"pem"];
  92. }
  93. unsigned long long fileSize =
  94. [[[NSFileManager defaultManager] attributesOfItemAtPath:certsPath error:nil] fileSize];
  95. if (fileSize == 0) {
  96. NSLog(
  97. @"The cert is not properly configured. Make sure setup_integration_tests.py "
  98. "has been run.");
  99. }
  100. [GRPCCall useTestCertsPath:certsPath testName:@"test_cert_2" forHost:host];
  101. }
  102. settings.host = host;
  103. settings.persistenceEnabled = YES;
  104. NSLog(@"Configured integration test for %@ with SSL: %@", settings.host,
  105. settings.sslEnabled ? @"YES" : @"NO");
  106. return settings;
  107. }
  108. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  109. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  110. FSTTestDispatchQueue *workerDispatchQueue = [FSTTestDispatchQueue
  111. queueWith:dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL)];
  112. FSTEmptyCredentialsProvider *credentialsProvider = [[FSTEmptyCredentialsProvider alloc] init];
  113. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  114. // HACK: FIRFirestore expects a non-nil app, but for tests we cheat.
  115. FIRApp *app = nil;
  116. FIRFirestore *firestore = [[FIRFirestore alloc] initWithProjectID:projectID
  117. database:kDefaultDatabaseID
  118. persistenceKey:persistenceKey
  119. credentialsProvider:credentialsProvider
  120. workerDispatchQueue:workerDispatchQueue
  121. firebaseApp:app];
  122. firestore.settings = [FSTIntegrationTestCase settings];
  123. [_firestores addObject:firestore];
  124. return firestore;
  125. }
  126. - (void)waitForIdleFirestore:(FIRFirestore *)firestore {
  127. XCTestExpectation *expectation = [self expectationWithDescription:@"idle"];
  128. // Note that we wait on any task that is scheduled with a delay of 60s. Currently, the idle
  129. // timeout is the only task that uses this delay.
  130. [((FSTTestDispatchQueue *)firestore.workerDispatchQueue) fulfillOnExecution:expectation];
  131. [self awaitExpectations];
  132. }
  133. - (void)shutdownFirestore:(FIRFirestore *)firestore {
  134. XCTestExpectation *shutdownCompletion = [self expectationWithDescription:@"shutdown"];
  135. [firestore shutdownWithCompletion:^(NSError *_Nullable error) {
  136. XCTAssertNil(error);
  137. [shutdownCompletion fulfill];
  138. }];
  139. [self awaitExpectations];
  140. }
  141. - (NSString *)documentPath {
  142. std::string autoId = firestore::CreateAutoId();
  143. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  144. }
  145. - (FIRDocumentReference *)documentRef {
  146. return [self.db documentWithPath:[self documentPath]];
  147. }
  148. - (FIRCollectionReference *)collectionRef {
  149. std::string autoId = firestore::CreateAutoId();
  150. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  151. return [self.db collectionWithPath:collectionName];
  152. }
  153. - (FIRCollectionReference *)collectionRefWithDocuments:
  154. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  155. FIRCollectionReference *collection = [self collectionRef];
  156. // Use a different instance to write the documents
  157. [self writeAllDocuments:documents
  158. toCollection:[[self firestore] collectionWithPath:collection.path]];
  159. return collection;
  160. }
  161. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  162. toCollection:(FIRCollectionReference *)collection {
  163. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  164. BOOL *stop) {
  165. FIRDocumentReference *ref = [collection documentWithPath:key];
  166. [self writeDocumentRef:ref data:value];
  167. }];
  168. }
  169. - (void)readerAndWriterOnDocumentRef:(void (^)(NSString *path,
  170. FIRDocumentReference *readerRef,
  171. FIRDocumentReference *writerRef))action {
  172. FIRFirestore *reader = self.db; // for clarity
  173. FIRFirestore *writer = [self firestore];
  174. NSString *path = [self documentPath];
  175. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  176. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  177. action(path, readerRef, writerRef);
  178. }
  179. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  180. __block FIRDocumentSnapshot *result;
  181. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  182. [ref getDocumentWithCompletion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  183. XCTAssertNil(error);
  184. result = doc;
  185. [expectation fulfill];
  186. }];
  187. [self awaitExpectations];
  188. return result;
  189. }
  190. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  191. __block FIRQuerySnapshot *result;
  192. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  193. [query getDocumentsWithCompletion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  194. XCTAssertNil(error);
  195. result = documentSet;
  196. [expectation fulfill];
  197. }];
  198. [self awaitExpectations];
  199. return result;
  200. }
  201. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  202. requireOnline:(BOOL)requireOnline {
  203. __block FIRDocumentSnapshot *result;
  204. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  205. id<FIRListenerRegistration> listener = [ref
  206. addSnapshotListenerWithOptions:[[FIRDocumentListenOptions options] includeMetadataChanges:YES]
  207. listener:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  208. XCTAssertNil(error);
  209. if (!requireOnline || !snapshot.metadata.fromCache) {
  210. result = snapshot;
  211. [expectation fulfill];
  212. }
  213. }];
  214. [self awaitExpectations];
  215. [listener remove];
  216. return result;
  217. }
  218. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  219. XCTestExpectation *expectation = [self expectationWithDescription:@"setData"];
  220. [ref setData:data
  221. completion:^(NSError *_Nullable error) {
  222. XCTAssertNil(error);
  223. [expectation fulfill];
  224. }];
  225. [self awaitExpectations];
  226. }
  227. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  228. XCTestExpectation *expectation = [self expectationWithDescription:@"updateData"];
  229. [ref updateData:data
  230. completion:^(NSError *_Nullable error) {
  231. XCTAssertNil(error);
  232. [expectation fulfill];
  233. }];
  234. [self awaitExpectations];
  235. }
  236. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  237. XCTestExpectation *expectation = [self expectationWithDescription:@"deleteDocument"];
  238. [ref deleteDocumentWithCompletion:^(NSError *_Nullable error) {
  239. XCTAssertNil(error);
  240. [expectation fulfill];
  241. }];
  242. [self awaitExpectations];
  243. }
  244. - (void)waitUntil:(BOOL (^)())predicate {
  245. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  246. double waitSeconds = [self defaultExpectationWaitSeconds];
  247. while (!predicate() && ([NSDate timeIntervalSinceReferenceDate] - start < waitSeconds)) {
  248. // This waits for the next event or until the 100ms timeout is reached
  249. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  250. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  251. }
  252. if (!predicate()) {
  253. XCTFail(@"Timeout");
  254. }
  255. }
  256. extern "C" NSArray<NSDictionary<NSString *, id> *> *FIRQuerySnapshotGetData(
  257. FIRQuerySnapshot *docs) {
  258. NSMutableArray<NSDictionary<NSString *, id> *> *result = [NSMutableArray array];
  259. for (FIRDocumentSnapshot *doc in docs.documents) {
  260. [result addObject:doc.data];
  261. }
  262. return result;
  263. }
  264. extern "C" NSArray<NSString *> *FIRQuerySnapshotGetIDs(FIRQuerySnapshot *docs) {
  265. NSMutableArray<NSString *> *result = [NSMutableArray array];
  266. for (FIRDocumentSnapshot *doc in docs.documents) {
  267. [result addObject:doc.documentID];
  268. }
  269. return result;
  270. }
  271. @end
  272. NS_ASSUME_NONNULL_END