FSTDatastoreTests.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 <FirebaseFirestore/FirebaseFirestore.h>
  17. #import <FirebaseFirestore/FIRTimestamp.h>
  18. #import <XCTest/XCTest.h>
  19. #include <memory>
  20. #include <vector>
  21. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  22. #import "Firestore/Source/API/FSTUserDataReader.h"
  23. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  24. #include "Firestore/core/src/core/database_info.h"
  25. #include "Firestore/core/src/credentials/empty_credentials_provider.h"
  26. #include "Firestore/core/src/local/local_documents_view.h"
  27. #include "Firestore/core/src/local/local_store.h"
  28. #include "Firestore/core/src/local/memory_persistence.h"
  29. #include "Firestore/core/src/local/query_engine.h"
  30. #include "Firestore/core/src/local/target_data.h"
  31. #include "Firestore/core/src/model/database_id.h"
  32. #include "Firestore/core/src/model/document_key.h"
  33. #include "Firestore/core/src/model/mutation_batch_result.h"
  34. #include "Firestore/core/src/model/precondition.h"
  35. #include "Firestore/core/src/model/set_mutation.h"
  36. #include "Firestore/core/src/remote/connectivity_monitor.h"
  37. #include "Firestore/core/src/remote/datastore.h"
  38. #include "Firestore/core/src/remote/firebase_metadata_provider.h"
  39. #include "Firestore/core/src/remote/firebase_metadata_provider_noop.h"
  40. #include "Firestore/core/src/remote/remote_event.h"
  41. #include "Firestore/core/src/remote/remote_store.h"
  42. #include "Firestore/core/src/util/async_queue.h"
  43. #include "Firestore/core/src/util/hard_assert.h"
  44. #include "Firestore/core/src/util/status.h"
  45. #include "Firestore/core/src/util/string_apple.h"
  46. #include "Firestore/core/test/unit/remote/create_noop_connectivity_monitor.h"
  47. #include "Firestore/core/test/unit/testutil/async_testing.h"
  48. #include "Firestore/core/test/unit/testutil/testutil.h"
  49. #include "absl/memory/memory.h"
  50. namespace util = firebase::firestore::util;
  51. namespace testutil = firebase::firestore::testutil;
  52. using firebase::Timestamp;
  53. using firebase::firestore::core::DatabaseInfo;
  54. using firebase::firestore::credentials::EmptyAppCheckCredentialsProvider;
  55. using firebase::firestore::credentials::EmptyAuthCredentialsProvider;
  56. using firebase::firestore::credentials::User;
  57. using firebase::firestore::google_firestore_v1_Value;
  58. using firebase::firestore::local::LocalStore;
  59. using firebase::firestore::local::MemoryPersistence;
  60. using firebase::firestore::local::Persistence;
  61. using firebase::firestore::local::QueryEngine;
  62. using firebase::firestore::model::BatchId;
  63. using firebase::firestore::model::DatabaseId;
  64. using firebase::firestore::model::DocumentKeySet;
  65. using firebase::firestore::model::MutationBatch;
  66. using firebase::firestore::model::MutationBatchResult;
  67. using firebase::firestore::model::OnlineState;
  68. using firebase::firestore::model::TargetId;
  69. using firebase::firestore::remote::ConnectivityMonitor;
  70. using firebase::firestore::remote::CreateFirebaseMetadataProviderNoOp;
  71. using firebase::firestore::remote::CreateNoOpConnectivityMonitor;
  72. using firebase::firestore::remote::Datastore;
  73. using firebase::firestore::remote::FirebaseMetadataProvider;
  74. using firebase::firestore::remote::GrpcConnection;
  75. using firebase::firestore::remote::RemoteEvent;
  76. using firebase::firestore::remote::RemoteStore;
  77. using firebase::firestore::remote::RemoteStoreCallback;
  78. using firebase::firestore::testutil::Map;
  79. using firebase::firestore::util::AsyncQueue;
  80. using firebase::firestore::util::Status;
  81. NS_ASSUME_NONNULL_BEGIN
  82. #pragma mark - FSTRemoteStoreEventCapture
  83. @interface FSTRemoteStoreEventCapture : NSObject
  84. - (instancetype)init __attribute__((unavailable("Use initWithTestCase:")));
  85. - (instancetype)initWithTestCase:(XCTestCase *_Nullable)testCase NS_DESIGNATED_INITIALIZER;
  86. - (void)expectWriteEventWithDescription:(NSString *)description;
  87. - (void)expectListenEventWithDescription:(NSString *)description;
  88. @property(nonatomic, weak, nullable) XCTestCase *testCase;
  89. @property(nonatomic, strong) NSMutableArray<XCTestExpectation *> *writeEventExpectations;
  90. @property(nonatomic, strong) NSMutableArray<XCTestExpectation *> *listenEventExpectations;
  91. @end
  92. @implementation FSTRemoteStoreEventCapture {
  93. std::vector<RemoteEvent> _listenEvents;
  94. std::vector<MutationBatchResult> _writeEvents;
  95. }
  96. - (instancetype)initWithTestCase:(XCTestCase *_Nullable)testCase {
  97. if (self = [super init]) {
  98. _testCase = testCase;
  99. _writeEventExpectations = [NSMutableArray array];
  100. _listenEventExpectations = [NSMutableArray array];
  101. }
  102. return self;
  103. }
  104. - (void)expectWriteEventWithDescription:(NSString *)description {
  105. [self.writeEventExpectations
  106. addObject:[self.testCase
  107. expectationWithDescription:[NSString
  108. stringWithFormat:@"write event %lu: %@",
  109. (unsigned long)
  110. self.writeEventExpectations
  111. .count,
  112. description]]];
  113. }
  114. - (void)expectListenEventWithDescription:(NSString *)description {
  115. [self.listenEventExpectations
  116. addObject:[self.testCase
  117. expectationWithDescription:[NSString
  118. stringWithFormat:@"listen event %lu: %@",
  119. (unsigned long)
  120. self.listenEventExpectations
  121. .count,
  122. description]]];
  123. }
  124. - (void)applySuccessfulWriteWithResult:(MutationBatchResult)batchResult {
  125. _writeEvents.push_back(std::move(batchResult));
  126. XCTestExpectation *expectation = [self.writeEventExpectations objectAtIndex:0];
  127. [self.writeEventExpectations removeObjectAtIndex:0];
  128. [expectation fulfill];
  129. }
  130. - (void)rejectFailedWriteWithBatchID:(__unused BatchId)batchID error:(__unused NSError *)error {
  131. HARD_FAIL("Not implemented");
  132. }
  133. - (DocumentKeySet)remoteKeysForTarget:(__unused TargetId)targetId {
  134. return DocumentKeySet{};
  135. }
  136. - (void)applyRemoteEvent:(const RemoteEvent &)remoteEvent {
  137. _listenEvents.push_back(remoteEvent);
  138. XCTestExpectation *expectation = [self.listenEventExpectations objectAtIndex:0];
  139. [self.listenEventExpectations removeObjectAtIndex:0];
  140. [expectation fulfill];
  141. }
  142. - (void)rejectListenWithTargetID:(__unused const TargetId)targetID error:(__unused NSError *)error {
  143. HARD_FAIL("Not implemented");
  144. }
  145. @end
  146. class RemoteStoreEventCapture : public RemoteStoreCallback {
  147. public:
  148. explicit RemoteStoreEventCapture(XCTestCase *test_case)
  149. : underlying_capture_([[FSTRemoteStoreEventCapture alloc] initWithTestCase:test_case]) {
  150. }
  151. void ExpectWriteEvent(NSString *description) {
  152. [underlying_capture_ expectWriteEventWithDescription:description];
  153. }
  154. void ExpectListenEvent(NSString *description) {
  155. [underlying_capture_ expectListenEventWithDescription:description];
  156. }
  157. void ApplyRemoteEvent(const RemoteEvent &remote_event) override {
  158. [underlying_capture_ applyRemoteEvent:remote_event];
  159. }
  160. void HandleRejectedListen(TargetId target_id, Status error) override {
  161. [underlying_capture_ rejectListenWithTargetID:target_id error:error.ToNSError()];
  162. }
  163. void HandleSuccessfulWrite(MutationBatchResult batch_result) override {
  164. [underlying_capture_ applySuccessfulWriteWithResult:std::move(batch_result)];
  165. }
  166. void HandleRejectedWrite(BatchId batch_id, Status error) override {
  167. [underlying_capture_ rejectFailedWriteWithBatchID:batch_id error:error.ToNSError()];
  168. }
  169. void HandleOnlineStateChange(OnlineState) override {
  170. HARD_FAIL("Not implemented");
  171. }
  172. model::DocumentKeySet GetRemoteKeys(TargetId target_id) const override {
  173. return [underlying_capture_ remoteKeysForTarget:target_id];
  174. }
  175. private:
  176. FSTRemoteStoreEventCapture *underlying_capture_;
  177. };
  178. #pragma mark - FSTDatastoreTests
  179. @interface FSTDatastoreTests : XCTestCase
  180. @end
  181. @implementation FSTDatastoreTests {
  182. std::shared_ptr<AsyncQueue> _testWorkerQueue;
  183. std::unique_ptr<LocalStore> _localStore;
  184. std::unique_ptr<Persistence> _persistence;
  185. DatabaseInfo _databaseInfo;
  186. QueryEngine _queryEngine;
  187. std::unique_ptr<ConnectivityMonitor> _connectivityMonitor;
  188. std::unique_ptr<FirebaseMetadataProvider> _firebaseMetadataProvider;
  189. std::shared_ptr<Datastore> _datastore;
  190. std::unique_ptr<RemoteStore> _remoteStore;
  191. }
  192. - (void)setUp {
  193. [super setUp];
  194. NSString *projectID = [FSTIntegrationTestCase projectID];
  195. FIRFirestoreSettings *settings = [FSTIntegrationTestCase settings];
  196. if (!settings.sslEnabled) {
  197. GrpcConnection::UseInsecureChannel(util::MakeString(settings.host));
  198. }
  199. DatabaseId database_id(util::MakeString(projectID));
  200. _databaseInfo =
  201. DatabaseInfo(database_id, "test-key", util::MakeString(settings.host), settings.sslEnabled);
  202. _testWorkerQueue = testutil::AsyncQueueForTesting();
  203. _connectivityMonitor = CreateNoOpConnectivityMonitor();
  204. _firebaseMetadataProvider = CreateFirebaseMetadataProviderNoOp();
  205. _datastore = std::make_shared<Datastore>(
  206. _databaseInfo, _testWorkerQueue, std::make_shared<EmptyAuthCredentialsProvider>(),
  207. std::make_shared<EmptyAppCheckCredentialsProvider>(), _connectivityMonitor.get(),
  208. _firebaseMetadataProvider.get());
  209. _persistence = MemoryPersistence::WithEagerGarbageCollector();
  210. _localStore =
  211. absl::make_unique<LocalStore>(_persistence.get(), &_queryEngine, User::Unauthenticated());
  212. _remoteStore = absl::make_unique<RemoteStore>(_localStore.get(), _datastore, _testWorkerQueue,
  213. _connectivityMonitor.get(), [](OnlineState) {});
  214. _testWorkerQueue->Enqueue([=] { _remoteStore->Start(); });
  215. }
  216. - (void)tearDown {
  217. XCTestExpectation *completion = [self expectationWithDescription:@"shutdown"];
  218. _testWorkerQueue->Enqueue([=] {
  219. _remoteStore->Shutdown();
  220. [completion fulfill];
  221. });
  222. [self awaitExpectations];
  223. [super tearDown];
  224. }
  225. - (void)testCommit {
  226. XCTestExpectation *expectation = [self expectationWithDescription:@"commitWithCompletion"];
  227. _datastore->CommitMutations({}, [self, expectation](const Status &status) {
  228. (void)self; // Avoid unused lambda capture error in Xcode 12.
  229. XCTAssertTrue(status.ok(), @"Failed to commit");
  230. [expectation fulfill];
  231. });
  232. [self awaitExpectations];
  233. }
  234. - (void)testStreamingWrite {
  235. RemoteStoreEventCapture capture(self);
  236. capture.ExpectWriteEvent(@"write mutations");
  237. _remoteStore->set_sync_engine(&capture);
  238. auto mutation = testutil::SetMutation("rooms/eros", Map("name", "Eros"));
  239. MutationBatch batch = MutationBatch(23, Timestamp::Now(), {}, {mutation});
  240. _testWorkerQueue->Enqueue([=] {
  241. _remoteStore->AddToWritePipeline(batch);
  242. // The added batch won't be written immediately because write stream wasn't yet open --
  243. // trigger its opening.
  244. _remoteStore->FillWritePipeline();
  245. });
  246. [self awaitExpectations];
  247. }
  248. - (void)awaitExpectations {
  249. [self waitForExpectationsWithTimeout:4.0
  250. handler:^(NSError *_Nullable expectationError) {
  251. if (expectationError) {
  252. XCTFail(@"Error waiting for timeout: %@", expectationError);
  253. }
  254. }];
  255. }
  256. @end
  257. NS_ASSUME_NONNULL_END