FSTIntegrationTestCase.mm 11 KB

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