FSTDatastoreTests.mm 9.6 KB

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