FSTIntegrationTestCase.mm 13 KB

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