FSTIntegrationTestCase.mm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 <FirebaseCore/FIROptions.h>
  19. #import <FirebaseFirestore/FIRCollectionReference.h>
  20. #import <FirebaseFirestore/FIRDocumentChange.h>
  21. #import <FirebaseFirestore/FIRDocumentReference.h>
  22. #import <FirebaseFirestore/FIRDocumentSnapshot.h>
  23. #import <FirebaseFirestore/FIRFirestore.h>
  24. #import <FirebaseFirestore/FIRFirestoreSettings.h>
  25. #import <FirebaseFirestore/FIRQuerySnapshot.h>
  26. #import <FirebaseFirestore/FIRSnapshotMetadata.h>
  27. #import <FirebaseFirestore/FIRTransaction.h>
  28. #include <memory>
  29. #include <string>
  30. #include <utility>
  31. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  32. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  33. #include "Firestore/core/src/firebase/firestore/remote/grpc_connection.h"
  34. #include "Firestore/core/src/firebase/firestore/util/autoid.h"
  35. #include "Firestore/core/src/firebase/firestore/util/filesystem.h"
  36. #include "Firestore/core/src/firebase/firestore/util/path.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. #include "Firestore/core/test/firebase/firestore/testutil/app_testing.h"
  39. #include "Firestore/core/test/firebase/firestore/util/status_test_util.h"
  40. #include "absl/memory/memory.h"
  41. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  42. #import "Firestore/Source/Core/FSTFirestoreClient.h"
  43. #import "Firestore/Source/Local/FSTLevelDB.h"
  44. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  45. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  46. namespace util = firebase::firestore::util;
  47. using firebase::firestore::auth::CredentialsProvider;
  48. using firebase::firestore::auth::EmptyCredentialsProvider;
  49. using firebase::firestore::model::DatabaseId;
  50. using firebase::firestore::testutil::AppForUnitTesting;
  51. using firebase::firestore::remote::GrpcConnection;
  52. using firebase::firestore::util::CreateAutoId;
  53. using firebase::firestore::util::Path;
  54. using firebase::firestore::util::Status;
  55. NS_ASSUME_NONNULL_BEGIN
  56. /**
  57. * Firestore databases can be subject to a ~30s "cold start" delay if they have not been used
  58. * recently, so before any tests run we "prime" the backend.
  59. */
  60. static const double kPrimingTimeout = 45.0;
  61. @interface FIRFirestore (Testing)
  62. @property(nonatomic, strong) FSTDispatchQueue *workerDispatchQueue;
  63. @end
  64. static NSString *defaultProjectId;
  65. static FIRFirestoreSettings *defaultSettings;
  66. @implementation FSTIntegrationTestCase {
  67. NSMutableArray<FIRFirestore *> *_firestores;
  68. }
  69. - (void)setUp {
  70. [super setUp];
  71. [self clearPersistence];
  72. _firestores = [NSMutableArray array];
  73. self.db = [self firestore];
  74. self.eventAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  75. }
  76. - (void)tearDown {
  77. @try {
  78. for (FIRFirestore *firestore in _firestores) {
  79. [self shutdownFirestore:firestore];
  80. }
  81. } @finally {
  82. _firestores = nil;
  83. [super tearDown];
  84. }
  85. }
  86. - (void)clearPersistence {
  87. Path levelDBDir = [FSTLevelDB documentsDirectory];
  88. Status status = util::RecursivelyDelete(levelDBDir);
  89. ASSERT_OK(status);
  90. }
  91. - (FIRFirestore *)firestore {
  92. return [self firestoreWithProjectID:[FSTIntegrationTestCase projectID]];
  93. }
  94. + (void)setUpDefaults {
  95. defaultSettings = [[FIRFirestoreSettings alloc] init];
  96. defaultSettings.persistenceEnabled = YES;
  97. defaultSettings.timestampsInSnapshotsEnabled = YES;
  98. // Check for a MobileHarness configuration, running against nightly or prod, which have live
  99. // SSL certs.
  100. NSString *project = [[NSProcessInfo processInfo] environment][@"PROJECT_ID"];
  101. NSString *host = [[NSProcessInfo processInfo] environment][@"DATASTORE_HOST"];
  102. if (project && host) {
  103. defaultProjectId = project;
  104. defaultSettings.host = host;
  105. return;
  106. }
  107. // Check for configuration of a prod project via GoogleServices-Info.plist.
  108. FIROptions *options = [FIROptions defaultOptions];
  109. if (options && ![options.projectID isEqualToString:@"abc-xyz-123"]) {
  110. defaultProjectId = options.projectID;
  111. if (host) {
  112. // Allow access to nightly or other hosts via this mechanism too.
  113. defaultSettings.host = host;
  114. }
  115. return;
  116. }
  117. // Otherwise fall back on assuming Hexa on localhost.
  118. defaultProjectId = @"test-db";
  119. defaultSettings.host = @"localhost:8081";
  120. // Hexa uses a self-signed cert: the first bundle location is used by bazel builds. The second is
  121. // used for github clones.
  122. NSString *certsPath =
  123. [[NSBundle mainBundle] pathForResource:@"PlugIns/IntegrationTests.xctest/CAcert"
  124. ofType:@"pem"];
  125. if (certsPath == nil) {
  126. certsPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"CAcert" ofType:@"pem"];
  127. }
  128. unsigned long long fileSize =
  129. [[[NSFileManager defaultManager] attributesOfItemAtPath:certsPath error:nil] fileSize];
  130. if (fileSize == 0) {
  131. NSLog(
  132. @"Please set up a GoogleServices-Info.plist for Firestore in Firestore/Example/App using "
  133. "instructions at <https://github.com/firebase/firebase-ios-sdk#running-sample-apps>. "
  134. "Alternatively, if you're a Googler with a Hexa preproduction environment, run "
  135. "setup_integration_tests.py to properly configure testing SSL certificates.");
  136. }
  137. GrpcConnection::UseTestCertificate(util::MakeString(defaultSettings.host),
  138. Path::FromNSString(certsPath), "test_cert_2");
  139. }
  140. + (NSString *)projectID {
  141. if (!defaultProjectId) {
  142. [self setUpDefaults];
  143. }
  144. return defaultProjectId;
  145. }
  146. + (FIRFirestoreSettings *)settings {
  147. if (!defaultSettings) {
  148. [self setUpDefaults];
  149. }
  150. return defaultSettings;
  151. }
  152. - (FIRFirestore *)firestoreWithProjectID:(NSString *)projectID {
  153. NSString *persistenceKey = [NSString stringWithFormat:@"db%lu", (unsigned long)_firestores.count];
  154. FSTDispatchQueue *workerDispatchQueue = [FSTDispatchQueue
  155. queueWith:dispatch_queue_create("com.google.firebase.firestore", DISPATCH_QUEUE_SERIAL)];
  156. FIRSetLoggerLevel(FIRLoggerLevelDebug);
  157. FIRApp *app = AppForUnitTesting();
  158. std::unique_ptr<CredentialsProvider> credentials_provider =
  159. absl::make_unique<firebase::firestore::auth::EmptyCredentialsProvider>();
  160. FIRFirestore *firestore = [[FIRFirestore alloc] initWithProjectID:util::MakeString(projectID)
  161. database:DatabaseId::kDefault
  162. persistenceKey:persistenceKey
  163. credentialsProvider:std::move(credentials_provider)
  164. workerDispatchQueue:workerDispatchQueue
  165. firebaseApp:app];
  166. firestore.settings = [FSTIntegrationTestCase settings];
  167. [_firestores addObject:firestore];
  168. [self primeBackend:firestore];
  169. return firestore;
  170. }
  171. - (void)primeBackend:(FIRFirestore *)db {
  172. static dispatch_once_t onceToken;
  173. dispatch_once(&onceToken, ^{
  174. XCTestExpectation *watchInitialized =
  175. [self expectationWithDescription:@"Prime backend: Watch initialized"];
  176. __block XCTestExpectation *watchUpdateReceived;
  177. FIRDocumentReference *docRef = [db documentWithPath:[self documentPath]];
  178. id<FIRListenerRegistration> listenerRegistration =
  179. [docRef addSnapshotListener:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  180. if ([snapshot[@"value"] isEqual:@"done"]) {
  181. [watchUpdateReceived fulfill];
  182. } else {
  183. [watchInitialized fulfill];
  184. }
  185. }];
  186. // Wait for watch to initialize and deliver first event.
  187. [self awaitExpectations];
  188. watchUpdateReceived = [self expectationWithDescription:@"Prime backend: Watch update received"];
  189. // Use a transaction to perform a write without triggering any local events.
  190. [docRef.firestore
  191. runTransactionWithBlock:^id(FIRTransaction *transaction, NSError **pError) {
  192. [transaction setData:@{@"value" : @"done"} forDocument:docRef];
  193. return nil;
  194. }
  195. completion:^(id result, NSError *error){
  196. }];
  197. // Wait to see the write on the watch stream.
  198. [self waitForExpectationsWithTimeout:kPrimingTimeout
  199. handler:^(NSError *_Nullable expectationError) {
  200. if (expectationError) {
  201. XCTFail(@"Error waiting for prime backend: %@",
  202. expectationError);
  203. }
  204. }];
  205. [listenerRegistration remove];
  206. });
  207. }
  208. - (void)shutdownFirestore:(FIRFirestore *)firestore {
  209. [firestore shutdownWithCompletion:[self completionForExpectationWithName:@"shutdown"]];
  210. [self awaitExpectations];
  211. }
  212. - (NSString *)documentPath {
  213. std::string autoId = CreateAutoId();
  214. return [NSString stringWithFormat:@"test-collection/%s", autoId.c_str()];
  215. }
  216. - (FIRDocumentReference *)documentRef {
  217. return [self.db documentWithPath:[self documentPath]];
  218. }
  219. - (FIRCollectionReference *)collectionRef {
  220. std::string autoId = CreateAutoId();
  221. NSString *collectionName = [NSString stringWithFormat:@"test-collection-%s", autoId.c_str()];
  222. return [self.db collectionWithPath:collectionName];
  223. }
  224. - (FIRCollectionReference *)collectionRefWithDocuments:
  225. (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents {
  226. FIRCollectionReference *collection = [self collectionRef];
  227. // Use a different instance to write the documents
  228. [self writeAllDocuments:documents
  229. toCollection:[[self firestore] collectionWithPath:collection.path]];
  230. return collection;
  231. }
  232. - (void)writeAllDocuments:(NSDictionary<NSString *, NSDictionary<NSString *, id> *> *)documents
  233. toCollection:(FIRCollectionReference *)collection {
  234. [documents enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary<NSString *, id> *value,
  235. BOOL *stop) {
  236. FIRDocumentReference *ref = [collection documentWithPath:key];
  237. [self writeDocumentRef:ref data:value];
  238. }];
  239. }
  240. - (void)readerAndWriterOnDocumentRef:(void (^)(NSString *path,
  241. FIRDocumentReference *readerRef,
  242. FIRDocumentReference *writerRef))action {
  243. FIRFirestore *reader = self.db; // for clarity
  244. FIRFirestore *writer = [self firestore];
  245. NSString *path = [self documentPath];
  246. FIRDocumentReference *readerRef = [reader documentWithPath:path];
  247. FIRDocumentReference *writerRef = [writer documentWithPath:path];
  248. action(path, readerRef, writerRef);
  249. }
  250. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref {
  251. return [self readDocumentForRef:ref source:FIRFirestoreSourceDefault];
  252. }
  253. - (FIRDocumentSnapshot *)readDocumentForRef:(FIRDocumentReference *)ref
  254. source:(FIRFirestoreSource)source {
  255. __block FIRDocumentSnapshot *result;
  256. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  257. [ref getDocumentWithSource:source
  258. completion:^(FIRDocumentSnapshot *doc, NSError *_Nullable error) {
  259. XCTAssertNil(error);
  260. result = doc;
  261. [expectation fulfill];
  262. }];
  263. [self awaitExpectations];
  264. return result;
  265. }
  266. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query {
  267. return [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  268. }
  269. - (FIRQuerySnapshot *)readDocumentSetForRef:(FIRQuery *)query source:(FIRFirestoreSource)source {
  270. __block FIRQuerySnapshot *result;
  271. XCTestExpectation *expectation = [self expectationWithDescription:@"getData"];
  272. [query getDocumentsWithSource:source
  273. completion:^(FIRQuerySnapshot *documentSet, NSError *error) {
  274. XCTAssertNil(error);
  275. result = documentSet;
  276. [expectation fulfill];
  277. }];
  278. [self awaitExpectations];
  279. return result;
  280. }
  281. - (FIRDocumentSnapshot *)readSnapshotForRef:(FIRDocumentReference *)ref
  282. requireOnline:(BOOL)requireOnline {
  283. __block FIRDocumentSnapshot *result;
  284. XCTestExpectation *expectation = [self expectationWithDescription:@"listener"];
  285. id<FIRListenerRegistration> listener = [ref
  286. addSnapshotListenerWithIncludeMetadataChanges:YES
  287. listener:^(FIRDocumentSnapshot *snapshot,
  288. NSError *error) {
  289. XCTAssertNil(error);
  290. if (!requireOnline || !snapshot.metadata.fromCache) {
  291. result = snapshot;
  292. [expectation fulfill];
  293. }
  294. }];
  295. [self awaitExpectations];
  296. [listener remove];
  297. return result;
  298. }
  299. - (void)writeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  300. [ref setData:data completion:[self completionForExpectationWithName:@"setData"]];
  301. [self awaitExpectations];
  302. }
  303. - (void)updateDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<id, id> *)data {
  304. [ref updateData:data completion:[self completionForExpectationWithName:@"updateData"]];
  305. [self awaitExpectations];
  306. }
  307. - (void)deleteDocumentRef:(FIRDocumentReference *)ref {
  308. [ref deleteDocumentWithCompletion:[self completionForExpectationWithName:@"deleteDocument"]];
  309. [self awaitExpectations];
  310. }
  311. - (void)mergeDocumentRef:(FIRDocumentReference *)ref data:(NSDictionary<NSString *, id> *)data {
  312. [ref setData:data
  313. merge:YES
  314. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  315. [self awaitExpectations];
  316. }
  317. - (void)mergeDocumentRef:(FIRDocumentReference *)ref
  318. data:(NSDictionary<NSString *, id> *)data
  319. fields:(NSArray<id> *)fields {
  320. [ref setData:data
  321. mergeFields:fields
  322. completion:[self completionForExpectationWithName:@"setDataWithMerge"]];
  323. [self awaitExpectations];
  324. }
  325. - (void)disableNetwork {
  326. [self.db.client
  327. disableNetworkWithCompletion:[self completionForExpectationWithName:@"Disable Network."]];
  328. [self awaitExpectations];
  329. }
  330. - (void)enableNetwork {
  331. [self.db.client
  332. enableNetworkWithCompletion:[self completionForExpectationWithName:@"Enable Network."]];
  333. [self awaitExpectations];
  334. }
  335. - (FSTDispatchQueue *)queueForFirestore:(FIRFirestore *)firestore {
  336. return firestore.workerDispatchQueue;
  337. }
  338. - (void)waitUntil:(BOOL (^)())predicate {
  339. NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
  340. double waitSeconds = [self defaultExpectationWaitSeconds];
  341. while (!predicate() && ([NSDate timeIntervalSinceReferenceDate] - start < waitSeconds)) {
  342. // This waits for the next event or until the 100ms timeout is reached
  343. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  344. beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  345. }
  346. if (!predicate()) {
  347. XCTFail(@"Timeout");
  348. }
  349. }
  350. extern "C" NSArray<NSDictionary<NSString *, id> *> *FIRQuerySnapshotGetData(
  351. FIRQuerySnapshot *docs) {
  352. NSMutableArray<NSDictionary<NSString *, id> *> *result = [NSMutableArray array];
  353. for (FIRDocumentSnapshot *doc in docs.documents) {
  354. [result addObject:doc.data];
  355. }
  356. return result;
  357. }
  358. extern "C" NSArray<NSString *> *FIRQuerySnapshotGetIDs(FIRQuerySnapshot *docs) {
  359. NSMutableArray<NSString *> *result = [NSMutableArray array];
  360. for (FIRDocumentSnapshot *doc in docs.documents) {
  361. [result addObject:doc.documentID];
  362. }
  363. return result;
  364. }
  365. extern "C" NSArray<NSArray<id> *> *FIRQuerySnapshotGetDocChangesData(FIRQuerySnapshot *docs) {
  366. NSMutableArray<NSMutableArray<id> *> *result = [NSMutableArray array];
  367. for (FIRDocumentChange *docChange in docs.documentChanges) {
  368. NSMutableArray<id> *docChangeData = [NSMutableArray array];
  369. [docChangeData addObject:@(docChange.type)];
  370. [docChangeData addObject:docChange.document.documentID];
  371. [docChangeData addObject:docChange.document.data];
  372. [result addObject:docChangeData];
  373. }
  374. return result;
  375. }
  376. @end
  377. NS_ASSUME_NONNULL_END