FSTDatastoreTests.mm 12 KB

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