FSTIntegrationTestCase.mm 11 KB

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