FSTIntegrationTestCase.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. settings.timestampsInSnapshotsEnabled = YES;
  114. NSLog(@"Configured integration test for %@ with SSL: %@", settings.host,
  115. settings.sslEnabled ? @"YES" : @"NO");
  116. return settings;
  117. }
  118. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  119. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  120. FSTDispatchQueue *workerDispatchQueue = [FSTDispatchQueue
  121. queueWith:dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL)];
  122. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  123. // HACK: FIRFirestore expects a non-nil app, but for tests we cheat.
  124. FIRApp *app = nil;
  125. std::unique_ptr<CredentialsProvider> credentials_provider =
  126. absl::make_unique<firebase::firestore::auth::EmptyCredentialsProvider>();
  127. FIRFirestore *firestore = [[FIRFirestore alloc] initWithProjectID:util::MakeStringView(projectID)
  128. database:DatabaseId::kDefault
  129. persistenceKey:persistenceKey
  130. credentialsProvider:std::move(credentials_provider)
  131. workerDispatchQueue:workerDispatchQueue
  132. firebaseApp:app];
  133. firestore.settings = [FSTIntegrationTestCase settings];
  134. [_firestores addObject:firestore];
  135. return firestore;
  136. }
  137. - (void)shutdownFirestore:(FIRFirestore *)firestore {
  138. [firestore shutdownWithCompletion:[self completionForExpectationWithName:@"shutdown"]];
  139. [self awaitExpectations];
  140. }
  141. - (NSString *)documentPath {
  142. std::string autoId = CreateAutoId();
  143. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  144. }
  145. - (FIRDocumentReference *)documentRef {
  146. return [self.db documentWithPath:[self documentPath]];
  147. }
  148. - (FIRCollectionReference *)collectionRef {
  149. std::string autoId = CreateAutoId();
  150. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  151. return [self.db collectionWithPath:collectionName];
  152. }
  153. - (FIRCollectionReference *)collectionRefWithDocuments:
  154. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  155. FIRCollectionReference *collection = [self collectionRef];
  156. // Use a different instance to write the documents
  157. [self writeAllDocuments:documents
  158. toCollection:[[self firestore] collectionWithPath:collection.path]];
  159. return collection;
  160. }
  161. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  162. toCollection:(FIRCollectionReference *)collection {
  163. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  164. BOOL *stop) {
  165. FIRDocumentReference *ref = [collection documentWithPath:key];
  166. [self writeDocumentRef:ref data:value];
  167. }];
  168. }
  169. - (void)readerAndWriterOnDocumentRef:(void (^)(NSString *path,
  170. FIRDocumentReference *readerRef,
  171. FIRDocumentReference *writerRef))action {
  172. FIRFirestore *reader = self.db; // for clarity
  173. FIRFirestore *writer = [self firestore];
  174. NSString *path = [self documentPath];
  175. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  176. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  177. action(path, readerRef, writerRef);
  178. }
  179. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  180. __block FIRDocumentSnapshot *result;
  181. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  182. [ref getDocumentWithCompletion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  183. XCTAssertNil(error);
  184. result = doc;
  185. [expectation fulfill];
  186. }];
  187. [self awaitExpectations];
  188. return result;
  189. }
  190. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  191. __block FIRQuerySnapshot *result;
  192. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  193. [query getDocumentsWithCompletion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  194. XCTAssertNil(error);
  195. result = documentSet;
  196. [expectation fulfill];
  197. }];
  198. [self awaitExpectations];
  199. return result;
  200. }
  201. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  202. requireOnline:(BOOL)requireOnline {
  203. __block FIRDocumentSnapshot *result;
  204. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  205. id<FIRListenerRegistration> listener = [ref
  206. addSnapshotListenerWithOptions:[[FIRDocumentListenOptions options] includeMetadataChanges:YES]
  207. listener:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  208. XCTAssertNil(error);
  209. if (!requireOnline || !snapshot.metadata.fromCache) {
  210. result = snapshot;
  211. [expectation fulfill];
  212. }
  213. }];
  214. [self awaitExpectations];
  215. [listener remove];
  216. return result;
  217. }
  218. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  219. [ref setData:data completion:[self completionForExpectationWithName:@"setData"]];
  220. [self awaitExpectations];
  221. }
  222. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  223. [ref updateData:data completion:[self completionForExpectationWithName:@"updateData"]];
  224. [self awaitExpectations];
  225. }
  226. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  227. [ref deleteDocumentWithCompletion:[self completionForExpectationWithName:@"deleteDocument"]];
  228. [self awaitExpectations];
  229. }
  230. - (void)disableNetwork {
  231. [self.db.client
  232. disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable Network."]];
  233. [self awaitExpectations];
  234. }
  235. - (void)enableNetwork {
  236. [self.db.client
  237. enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable Network."]];
  238. [self awaitExpectations];
  239. }
  240. - (FSTDispatchQueue *)queueForFirestore:(FIRFirestore *)firestore {
  241. return firestore.workerDispatchQueue;
  242. }
  243. - (void)waitUntil:(BOOL (^)())predicate {
  244. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  245. double waitSeconds = [self defaultExpectationWaitSeconds];
  246. while (!predicate() && ([NSDate timeIntervalSinceReferenceDate] - start < waitSeconds)) {
  247. // This waits for the next event or until the 100ms timeout is reached
  248. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  249. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  250. }
  251. if (!predicate()) {
  252. XCTFail(@"Timeout");
  253. }
  254. }
  255. extern "C" NSArray<NSDictionary<NSString *, id> *> *FIRQuerySnapshotGetData(
  256. FIRQuerySnapshot *docs) {
  257. NSMutableArray<NSDictionary<NSString *, id> *> *result = [NSMutableArray array];
  258. for (FIRDocumentSnapshot *doc in docs.documents) {
  259. [result addObject:doc.data];
  260. }
  261. return result;
  262. }
  263. extern "C" NSArray<NSString *> *FIRQuerySnapshotGetIDs(FIRQuerySnapshot *docs) {
  264. NSMutableArray<NSString *> *result = [NSMutableArray array];
  265. for (FIRDocumentSnapshot *doc in docs.documents) {
  266. [result addObject:doc.documentID];
  267. }
  268. return result;
  269. }
  270. @end
  271. NS_ASSUME_NONNULL_END