FSTDatastoreTests.mm 12 KB

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