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