FSTDatastoreTests.mm 11 KB

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