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