FSTIntegrationTestCase.m 9.7 KB

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