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