FSTDatastoreTests.mm 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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/Source/Core/FSTFirestoreClient.h"
  24. #import "Firestore/Source/Core/FSTQuery.h"
  25. #import "Firestore/Source/Local/FSTQueryData.h"
  26. #import "Firestore/Source/Model/FSTFieldValue.h"
  27. #import "Firestore/Source/Model/FSTMutation.h"
  28. #import "Firestore/Source/Model/FSTMutationBatch.h"
  29. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  30. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  31. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  32. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  33. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  34. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  35. #include "Firestore/core/src/firebase/firestore/remote/datastore.h"
  36. #include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
  37. #include "Firestore/core/src/firebase/firestore/remote/remote_store.h"
  38. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  39. #include "Firestore/core/src/firebase/firestore/util/executor_libdispatch.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 "absl/memory/memory.h"
  44. namespace util = firebase::firestore::util;
  45. using firebase::firestore::auth::EmptyCredentialsProvider;
  46. using firebase::firestore::core::DatabaseInfo;
  47. using firebase::firestore::model::BatchId;
  48. using firebase::firestore::model::DatabaseId;
  49. using firebase::firestore::model::DocumentKey;
  50. using firebase::firestore::model::DocumentKeySet;
  51. using firebase::firestore::model::FieldValue;
  52. using firebase::firestore::model::Precondition;
  53. using firebase::firestore::model::OnlineState;
  54. using firebase::firestore::model::TargetId;
  55. using firebase::firestore::remote::Datastore;
  56. using firebase::firestore::remote::GrpcConnection;
  57. using firebase::firestore::remote::RemoteEvent;
  58. using firebase::firestore::remote::RemoteStore;
  59. using firebase::firestore::util::AsyncQueue;
  60. using firebase::firestore::util::ExecutorLibdispatch;
  61. using firebase::firestore::util::Status;
  62. NS_ASSUME_NONNULL_BEGIN
  63. #pragma mark - FSTRemoteStoreEventCapture
  64. @interface FSTRemoteStoreEventCapture : NSObject <FSTRemoteSyncer>
  65. - (instancetype)init __attribute__((unavailable("Use initWithTestCase:")));
  66. - (instancetype)initWithTestCase:(XCTestCase *_Nullable)testCase NS_DESIGNATED_INITIALIZER;
  67. - (void)expectWriteEventWithDescription:(NSString *)description;
  68. - (void)expectListenEventWithDescription:(NSString *)description;
  69. @property(nonatomic, weak, nullable) XCTestCase *testCase;
  70. @property(nonatomic, strong) NSMutableArray<NSObject *> *writeEvents;
  71. @property(nonatomic, strong) NSMutableArray<XCTestExpectation *> *writeEventExpectations;
  72. @property(nonatomic, strong) NSMutableArray<XCTestExpectation *> *listenEventExpectations;
  73. @end
  74. @implementation FSTRemoteStoreEventCapture {
  75. std::vector<RemoteEvent> _listenEvents;
  76. }
  77. - (instancetype)initWithTestCase:(XCTestCase *_Nullable)testCase {
  78. if (self = [super init]) {
  79. _writeEvents = [NSMutableArray array];
  80. _testCase = testCase;
  81. _writeEventExpectations = [NSMutableArray array];
  82. _listenEventExpectations = [NSMutableArray array];
  83. }
  84. return self;
  85. }
  86. - (void)expectWriteEventWithDescription:(NSString *)description {
  87. [self.writeEventExpectations
  88. addObject:[self.testCase
  89. expectationWithDescription:[NSString
  90. stringWithFormat:@"write event %lu: %@",
  91. (unsigned long)
  92. self.writeEventExpectations
  93. .count,
  94. description]]];
  95. }
  96. - (void)expectListenEventWithDescription:(NSString *)description {
  97. [self.listenEventExpectations
  98. addObject:[self.testCase
  99. expectationWithDescription:[NSString
  100. stringWithFormat:@"listen event %lu: %@",
  101. (unsigned long)
  102. self.listenEventExpectations
  103. .count,
  104. description]]];
  105. }
  106. - (void)applySuccessfulWriteWithResult:(FSTMutationBatchResult *)batchResult {
  107. [self.writeEvents addObject:batchResult];
  108. XCTestExpectation *expectation = [self.writeEventExpectations objectAtIndex:0];
  109. [self.writeEventExpectations removeObjectAtIndex:0];
  110. [expectation fulfill];
  111. }
  112. - (void)rejectFailedWriteWithBatchID:(BatchId)batchID error:(NSError *)error {
  113. HARD_FAIL("Not implemented");
  114. }
  115. - (DocumentKeySet)remoteKeysForTarget:(TargetId)targetId {
  116. return DocumentKeySet{};
  117. }
  118. - (void)applyRemoteEvent:(const RemoteEvent &)remoteEvent {
  119. _listenEvents.push_back(remoteEvent);
  120. XCTestExpectation *expectation = [self.listenEventExpectations objectAtIndex:0];
  121. [self.listenEventExpectations removeObjectAtIndex:0];
  122. [expectation fulfill];
  123. }
  124. - (void)rejectListenWithTargetID:(const TargetId)targetID error:(NSError *)error {
  125. HARD_FAIL("Not implemented");
  126. }
  127. @end
  128. #pragma mark - FSTDatastoreTests
  129. @interface FSTDatastoreTests : XCTestCase
  130. @end
  131. @implementation FSTDatastoreTests {
  132. std::unique_ptr<AsyncQueue> _testWorkerQueue;
  133. FSTLocalStore *_localStore;
  134. EmptyCredentialsProvider _credentials;
  135. DatabaseInfo _databaseInfo;
  136. std::shared_ptr<Datastore> _datastore;
  137. std::unique_ptr<RemoteStore> _remoteStore;
  138. }
  139. - (void)setUp {
  140. [super setUp];
  141. NSString *projectID = [FSTIntegrationTestCase projectID];
  142. FIRFirestoreSettings *settings = [FSTIntegrationTestCase settings];
  143. if (!settings.sslEnabled) {
  144. GrpcConnection::UseInsecureChannel(util::MakeString(settings.host));
  145. }
  146. DatabaseId database_id(util::MakeString(projectID), DatabaseId::kDefault);
  147. _databaseInfo =
  148. DatabaseInfo(database_id, "test-key", util::MakeString(settings.host), settings.sslEnabled);
  149. dispatch_queue_t queue = dispatch_queue_create(
  150. "com.google.firestore.FSTDatastoreTestsWorkerQueue", DISPATCH_QUEUE_SERIAL);
  151. _testWorkerQueue = absl::make_unique<AsyncQueue>(absl::make_unique<ExecutorLibdispatch>(queue));
  152. _datastore = std::make_shared<Datastore>(_databaseInfo, _testWorkerQueue.get(), &_credentials);
  153. _remoteStore = absl::make_unique<RemoteStore>(_localStore, _datastore, _testWorkerQueue.get(),
  154. [](OnlineState) {});
  155. _testWorkerQueue->Enqueue([=] { _remoteStore->Start(); });
  156. }
  157. - (void)tearDown {
  158. XCTestExpectation *completion = [self expectationWithDescription:@"shutdown"];
  159. _testWorkerQueue->Enqueue([=] {
  160. _remoteStore->Shutdown();
  161. [completion fulfill];
  162. });
  163. [self awaitExpectations];
  164. [super tearDown];
  165. }
  166. - (void)testCommit {
  167. XCTestExpectation *expectation = [self expectationWithDescription:@"commitWithCompletion"];
  168. _datastore->CommitMutations({}, [self, expectation](const Status &status) {
  169. XCTAssertTrue(status.ok(), @"Failed to commit");
  170. [expectation fulfill];
  171. });
  172. [self awaitExpectations];
  173. }
  174. - (void)testStreamingWrite {
  175. FSTRemoteStoreEventCapture *capture = [[FSTRemoteStoreEventCapture alloc] initWithTestCase:self];
  176. [capture expectWriteEventWithDescription:@"write mutations"];
  177. _remoteStore->set_sync_engine(capture);
  178. FSTSetMutation *mutation = [self setMutation];
  179. FSTMutationBatch *batch = [[FSTMutationBatch alloc] initWithBatchID:23
  180. localWriteTime:[FIRTimestamp timestamp]
  181. baseMutations:{}
  182. mutations:{mutation}];
  183. _testWorkerQueue->Enqueue([=] {
  184. _remoteStore->AddToWritePipeline(batch);
  185. // The added batch won't be written immediately because write stream wasn't yet open --
  186. // trigger its opening.
  187. _remoteStore->FillWritePipeline();
  188. });
  189. [self awaitExpectations];
  190. }
  191. - (void)awaitExpectations {
  192. [self waitForExpectationsWithTimeout:4.0
  193. handler:^(NSError *_Nullable expectationError) {
  194. if (expectationError) {
  195. XCTFail(@"Error waiting for timeout: %@", expectationError);
  196. }
  197. }];
  198. }
  199. - (FSTSetMutation *)setMutation {
  200. return [[FSTSetMutation alloc]
  201. initWithKey:DocumentKey::FromPathString("rooms/eros")
  202. value:[[FSTObjectValue alloc]
  203. initWithDictionary:@{@"name" : FieldValue::FromString("Eros").Wrap()}]
  204. precondition:Precondition::None()];
  205. }
  206. @end
  207. NS_ASSUME_NONNULL_END