FSTDatastoreTests.mm 11 KB

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