FSTDatastoreTests.mm 11 KB

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