FSTIntegrationTestCase.mm 11 KB

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