FSTDatastoreTests.mm 11 KB

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