FSTDatastoreTests.mm 11 KB

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