FSTIntegrationTestCase.mm 13 KB

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