FSTSpecTests.mm 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 "Firestore/Example/Tests/SpecTests/FSTSpecTests.h"
  17. #import <FirebaseFirestore/FIRFirestoreErrors.h>
  18. #include <map>
  19. #include <memory>
  20. #include <string>
  21. #include <unordered_map>
  22. #include <utility>
  23. #include <vector>
  24. #import "Firestore/Source/API/FSTUserDataConverter.h"
  25. #import "Firestore/Example/Tests/SpecTests/FSTSyncEngineTestDriver.h"
  26. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  27. #include "Firestore/core/include/firebase/firestore/firestore_errors.h"
  28. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  29. #include "Firestore/core/src/firebase/firestore/local/persistence.h"
  30. #include "Firestore/core/src/firebase/firestore/local/query_data.h"
  31. #include "Firestore/core/src/firebase/firestore/model/document.h"
  32. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  33. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  34. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  35. #include "Firestore/core/src/firebase/firestore/model/maybe_document.h"
  36. #include "Firestore/core/src/firebase/firestore/model/no_document.h"
  37. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  38. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  39. #include "Firestore/core/src/firebase/firestore/model/types.h"
  40. #include "Firestore/core/src/firebase/firestore/nanopb/nanopb_util.h"
  41. #include "Firestore/core/src/firebase/firestore/objc/objc_compatibility.h"
  42. #include "Firestore/core/src/firebase/firestore/remote/existence_filter.h"
  43. #include "Firestore/core/src/firebase/firestore/remote/serializer.h"
  44. #include "Firestore/core/src/firebase/firestore/remote/watch_change.h"
  45. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  46. #include "Firestore/core/src/firebase/firestore/util/comparison.h"
  47. #include "Firestore/core/src/firebase/firestore/util/filesystem.h"
  48. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  49. #include "Firestore/core/src/firebase/firestore/util/log.h"
  50. #include "Firestore/core/src/firebase/firestore/util/path.h"
  51. #include "Firestore/core/src/firebase/firestore/util/status.h"
  52. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  53. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  54. #include "absl/types/optional.h"
  55. namespace objc = firebase::firestore::objc;
  56. namespace testutil = firebase::firestore::testutil;
  57. namespace util = firebase::firestore::util;
  58. using firebase::firestore::Error;
  59. using firebase::firestore::auth::User;
  60. using firebase::firestore::core::DocumentViewChange;
  61. using firebase::firestore::core::Query;
  62. using firebase::firestore::local::Persistence;
  63. using firebase::firestore::local::QueryData;
  64. using firebase::firestore::local::QueryPurpose;
  65. using firebase::firestore::model::Document;
  66. using firebase::firestore::model::DocumentKey;
  67. using firebase::firestore::model::DocumentKeySet;
  68. using firebase::firestore::model::DocumentState;
  69. using firebase::firestore::model::FieldValue;
  70. using firebase::firestore::model::MaybeDocument;
  71. using firebase::firestore::model::MutationResult;
  72. using firebase::firestore::model::NoDocument;
  73. using firebase::firestore::model::ObjectValue;
  74. using firebase::firestore::model::ResourcePath;
  75. using firebase::firestore::model::SnapshotVersion;
  76. using firebase::firestore::model::TargetId;
  77. using firebase::firestore::nanopb::ByteString;
  78. using firebase::firestore::nanopb::MakeByteString;
  79. using firebase::firestore::remote::ExistenceFilter;
  80. using firebase::firestore::remote::DocumentWatchChange;
  81. using firebase::firestore::remote::ExistenceFilterWatchChange;
  82. using firebase::firestore::remote::InvalidQuery;
  83. using firebase::firestore::remote::WatchTargetChange;
  84. using firebase::firestore::remote::WatchTargetChangeState;
  85. using firebase::firestore::util::MakeString;
  86. using firebase::firestore::util::Path;
  87. using firebase::firestore::util::Status;
  88. using firebase::firestore::util::TimerId;
  89. using testutil::Doc;
  90. using testutil::Filter;
  91. using testutil::OrderBy;
  92. NS_ASSUME_NONNULL_BEGIN
  93. // Whether to run the benchmark spec tests.
  94. // TODO(mrschmidt): Make this configurable via the tests schema.
  95. static BOOL kRunBenchmarkTests = NO;
  96. // Disables all other tests; useful for debugging. Multiple tests can have this tag and they'll all
  97. // be run (but all others won't).
  98. static NSString *const kExclusiveTag = @"exclusive";
  99. // A tag for tests that should be excluded from execution (on iOS), useful to allow the platforms
  100. // to temporarily diverge.
  101. static NSString *const kNoIOSTag = @"no-ios";
  102. // A tag for tests that exercise the multi-client behavior of the Web client. These tests are
  103. // ignored on iOS.
  104. static NSString *const kMultiClientTag = @"multi-client";
  105. // A tag for tests that is assigned to the perf tests in "perf_spec.json". These tests are only run
  106. // if `kRunBenchmarkTests` is set to 'YES'.
  107. static NSString *const kBenchmarkTag = @"benchmark";
  108. NSString *const kEagerGC = @"eager-gc";
  109. NSString *const kDurablePersistence = @"durable-persistence";
  110. namespace {
  111. std::vector<TargetId> ConvertTargetsArray(NSArray<NSNumber *> *from) {
  112. std::vector<TargetId> result;
  113. for (NSNumber *targetID in from) {
  114. result.push_back(targetID.intValue);
  115. }
  116. return result;
  117. }
  118. ByteString MakeResumeToken(NSString *specString) {
  119. return MakeByteString([specString dataUsingEncoding:NSUTF8StringEncoding]);
  120. }
  121. } // namespace
  122. @interface FSTSpecTests ()
  123. @property(nonatomic, strong) FSTSyncEngineTestDriver *driver;
  124. @end
  125. @implementation FSTSpecTests {
  126. BOOL _gcEnabled;
  127. BOOL _networkEnabled;
  128. FSTUserDataConverter *_converter;
  129. }
  130. #define FSTAbstractMethodException() \
  131. [NSException exceptionWithName:NSInternalInconsistencyException \
  132. reason:[NSString stringWithFormat:@"You must override %s in a subclass", \
  133. __func__] \
  134. userInfo:nil];
  135. - (std::unique_ptr<Persistence>)persistenceWithGCEnabled:(BOOL)GCEnabled {
  136. @throw FSTAbstractMethodException(); // NOLINT
  137. }
  138. - (BOOL)shouldRunWithTags:(NSArray<NSString *> *)tags {
  139. if ([tags containsObject:kNoIOSTag]) {
  140. return NO;
  141. } else if ([tags containsObject:kMultiClientTag]) {
  142. return NO;
  143. } else if (!kRunBenchmarkTests && [tags containsObject:kBenchmarkTag]) {
  144. return NO;
  145. }
  146. return YES;
  147. }
  148. - (void)setUpForSpecWithConfig:(NSDictionary *)config {
  149. _converter = FSTTestUserDataConverter();
  150. // Store GCEnabled so we can re-use it in doRestart.
  151. NSNumber *GCEnabled = config[@"useGarbageCollection"];
  152. _gcEnabled = [GCEnabled boolValue];
  153. NSNumber *numClients = config[@"numClients"];
  154. if (numClients) {
  155. XCTAssertEqualObjects(numClients, @1, @"The iOS client does not support multi-client tests");
  156. }
  157. std::unique_ptr<Persistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  158. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:std::move(persistence)];
  159. [self.driver start];
  160. }
  161. - (void)tearDownForSpec {
  162. [self.driver shutdown];
  163. }
  164. /**
  165. * Xcode will run tests from any class that extends XCTestCase, but this doesn't work for
  166. * FSTSpecTests since it is incomplete without the implementations supplied by its subclasses.
  167. */
  168. - (BOOL)isTestBaseClass {
  169. return [self class] == [FSTSpecTests class];
  170. }
  171. #pragma mark - Methods for constructing objects from specs.
  172. - (Query)parseQuery:(id)querySpec {
  173. if ([querySpec isKindOfClass:[NSString class]]) {
  174. return testutil::Query(util::MakeString((NSString *)querySpec));
  175. } else if ([querySpec isKindOfClass:[NSDictionary class]]) {
  176. NSDictionary *queryDict = (NSDictionary *)querySpec;
  177. NSString *path = queryDict[@"path"];
  178. ResourcePath resource_path = ResourcePath::FromString(util::MakeString(path));
  179. std::shared_ptr<const std::string> collectionGroup =
  180. util::MakeStringPtr(queryDict[@"collectionGroup"]);
  181. Query query(std::move(resource_path), std::move(collectionGroup));
  182. if (queryDict[@"limit"]) {
  183. NSNumber *limitNumber = queryDict[@"limit"];
  184. auto limit = static_cast<int32_t>(limitNumber.integerValue);
  185. query = query.WithLimit(limit);
  186. }
  187. if (queryDict[@"filters"]) {
  188. NSArray<NSArray<id> *> *filters = queryDict[@"filters"];
  189. for (NSArray<id> *filter in filters) {
  190. std::string key = util::MakeString(filter[0]);
  191. std::string op = util::MakeString(filter[1]);
  192. FieldValue value = [_converter parsedQueryValue:filter[2]];
  193. query = query.AddingFilter(Filter(key, op, value));
  194. }
  195. }
  196. if (queryDict[@"orderBys"]) {
  197. NSArray *orderBys = queryDict[@"orderBys"];
  198. for (NSArray<NSString *> *orderBy in orderBys) {
  199. std::string field_path = util::MakeString(orderBy[0]);
  200. std::string direction = util::MakeString(orderBy[1]);
  201. query = query.AddingOrderBy(OrderBy(field_path, direction));
  202. }
  203. }
  204. return query;
  205. } else {
  206. XCTFail(@"Invalid query: %@", querySpec);
  207. return InvalidQuery();
  208. }
  209. }
  210. - (SnapshotVersion)parseVersion:(NSNumber *_Nullable)version {
  211. return testutil::Version(version.longLongValue);
  212. }
  213. - (DocumentViewChange)parseChange:(NSDictionary *)jsonDoc ofType:(DocumentViewChange::Type)type {
  214. NSNumber *version = jsonDoc[@"version"];
  215. NSDictionary *options = jsonDoc[@"options"];
  216. DocumentState documentState = [options[@"hasLocalMutations"] isEqualToNumber:@YES]
  217. ? DocumentState::kLocalMutations
  218. : ([options[@"hasCommittedMutations"] isEqualToNumber:@YES]
  219. ? DocumentState::kCommittedMutations
  220. : DocumentState::kSynced);
  221. XCTAssert([jsonDoc[@"key"] isKindOfClass:[NSString class]]);
  222. FieldValue data = [_converter parsedQueryValue:jsonDoc[@"value"]];
  223. Document doc = Doc(util::MakeString((NSString *)jsonDoc[@"key"]), version.longLongValue, data,
  224. documentState);
  225. return DocumentViewChange{doc, type};
  226. }
  227. #pragma mark - Methods for doing the steps of the spec test.
  228. - (void)doListen:(NSArray *)listenSpec {
  229. Query query = [self parseQuery:listenSpec[1]];
  230. TargetId actualID = [self.driver addUserListenerWithQuery:std::move(query)];
  231. TargetId expectedID = [listenSpec[0] intValue];
  232. XCTAssertEqual(actualID, expectedID, @"targetID assigned to listen");
  233. }
  234. - (void)doUnlisten:(NSArray *)unlistenSpec {
  235. Query query = [self parseQuery:unlistenSpec[1]];
  236. [self.driver removeUserListenerWithQuery:std::move(query)];
  237. }
  238. - (void)doSet:(NSArray *)setSpec {
  239. [self.driver writeUserMutation:FSTTestSetMutation(setSpec[0], setSpec[1])];
  240. }
  241. - (void)doPatch:(NSArray *)patchSpec {
  242. [self.driver
  243. writeUserMutation:FSTTestPatchMutation(util::MakeString(patchSpec[0]), patchSpec[1], {})];
  244. }
  245. - (void)doDelete:(NSString *)key {
  246. [self.driver writeUserMutation:FSTTestDeleteMutation(key)];
  247. }
  248. - (void)doAddSnapshotsInSyncListener {
  249. [self.driver addSnapshotsInSyncListener];
  250. }
  251. - (void)doRemoveSnapshotsInSyncListener {
  252. [self.driver removeSnapshotsInSyncListener];
  253. }
  254. - (void)doWatchAck:(NSArray<NSNumber *> *)ackedTargets {
  255. WatchTargetChange change{WatchTargetChangeState::Added, ConvertTargetsArray(ackedTargets)};
  256. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  257. }
  258. - (void)doWatchCurrent:(NSArray<id> *)currentSpec {
  259. NSArray<NSNumber *> *currentTargets = currentSpec[0];
  260. ByteString resumeToken = MakeResumeToken(currentSpec[1]);
  261. WatchTargetChange change{WatchTargetChangeState::Current, ConvertTargetsArray(currentTargets),
  262. resumeToken};
  263. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  264. }
  265. - (void)doWatchRemove:(NSDictionary *)watchRemoveSpec {
  266. Status error;
  267. NSDictionary *cause = watchRemoveSpec[@"cause"];
  268. if (cause) {
  269. int code = ((NSNumber *)cause[@"code"]).intValue;
  270. NSDictionary *userInfo = @{
  271. NSLocalizedDescriptionKey : @"Error from watchRemove.",
  272. };
  273. error = Status{static_cast<Error>(code), MakeString([userInfo description])};
  274. }
  275. WatchTargetChange change{WatchTargetChangeState::Removed,
  276. ConvertTargetsArray(watchRemoveSpec[@"targetIds"]), error};
  277. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  278. // Unlike web, the FSTMockDatastore detects a watch removal with cause and will remove active
  279. // targets
  280. }
  281. - (void)doWatchEntity:(NSDictionary *)watchEntity {
  282. if (watchEntity[@"docs"]) {
  283. HARD_ASSERT(!watchEntity[@"doc"], "Exactly one of |doc| or |docs| needs to be set.");
  284. NSArray *docs = watchEntity[@"docs"];
  285. for (NSDictionary *doc in docs) {
  286. NSMutableDictionary *watchSpec = [NSMutableDictionary dictionary];
  287. watchSpec[@"doc"] = doc;
  288. if (watchEntity[@"targets"]) {
  289. watchSpec[@"targets"] = watchEntity[@"targets"];
  290. }
  291. if (watchEntity[@"removedTargets"]) {
  292. watchSpec[@"removedTargets"] = watchEntity[@"removedTargets"];
  293. }
  294. [self doWatchEntity:watchSpec];
  295. }
  296. } else if (watchEntity[@"doc"]) {
  297. NSDictionary *docSpec = watchEntity[@"doc"];
  298. DocumentKey key = FSTTestDocKey(docSpec[@"key"]);
  299. absl::optional<ObjectValue> value = [docSpec[@"value"] isKindOfClass:[NSNull class]]
  300. ? absl::optional<ObjectValue>{}
  301. : FSTTestObjectValue(docSpec[@"value"]);
  302. SnapshotVersion version = [self parseVersion:docSpec[@"version"]];
  303. MaybeDocument doc;
  304. if (value) {
  305. doc = Document(*std::move(value), key, version, DocumentState::kSynced);
  306. } else {
  307. doc = NoDocument(key, version, /* has_committed_mutations= */ false);
  308. }
  309. DocumentWatchChange change{ConvertTargetsArray(watchEntity[@"targets"]),
  310. ConvertTargetsArray(watchEntity[@"removedTargets"]), std::move(key),
  311. std::move(doc)};
  312. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  313. } else if (watchEntity[@"key"]) {
  314. DocumentKey docKey = FSTTestDocKey(watchEntity[@"key"]);
  315. DocumentWatchChange change{
  316. {}, ConvertTargetsArray(watchEntity[@"removedTargets"]), docKey, absl::nullopt};
  317. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  318. } else {
  319. HARD_FAIL("Either key, doc or docs must be set.");
  320. }
  321. }
  322. - (void)doWatchFilter:(NSArray *)watchFilter {
  323. NSArray<NSNumber *> *targets = watchFilter[0];
  324. HARD_ASSERT(targets.count == 1, "ExistenceFilters currently support exactly one target only.");
  325. int keyCount = watchFilter.count == 0 ? 0 : (int)watchFilter.count - 1;
  326. ExistenceFilter filter{keyCount};
  327. ExistenceFilterWatchChange change{filter, targets[0].intValue};
  328. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  329. }
  330. - (void)doWatchReset:(NSArray<NSNumber *> *)watchReset {
  331. WatchTargetChange change{WatchTargetChangeState::Reset, ConvertTargetsArray(watchReset)};
  332. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  333. }
  334. - (void)doWatchSnapshot:(NSDictionary *)watchSnapshot {
  335. // The client will only respond to watchSnapshots if they are on a target change with an empty
  336. // set of target IDs.
  337. NSArray<NSNumber *> *targetIDs =
  338. watchSnapshot[@"targetIds"] ? watchSnapshot[@"targetIds"] : [NSArray array];
  339. ByteString resumeToken = MakeResumeToken(watchSnapshot[@"resumeToken"]);
  340. WatchTargetChange change{WatchTargetChangeState::NoChange, ConvertTargetsArray(targetIDs),
  341. resumeToken};
  342. [self.driver receiveWatchChange:change
  343. snapshotVersion:[self parseVersion:watchSnapshot[@"version"]]];
  344. }
  345. - (void)doWatchStreamClose:(NSDictionary *)closeSpec {
  346. NSDictionary *errorSpec = closeSpec[@"error"];
  347. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  348. NSNumber *runBackoffTimer = closeSpec[@"runBackoffTimer"];
  349. // TODO(b/72313632): Incorporate backoff in iOS Spec Tests.
  350. HARD_ASSERT(runBackoffTimer.boolValue, "iOS Spec Tests don't support backoff.");
  351. [self.driver receiveWatchStreamError:code userInfo:errorSpec];
  352. }
  353. - (void)doWriteAck:(NSDictionary *)spec {
  354. SnapshotVersion version = [self parseVersion:spec[@"version"]];
  355. NSNumber *keepInQueue = spec[@"keepInQueue"];
  356. XCTAssertTrue(keepInQueue == nil || keepInQueue.boolValue == NO,
  357. @"'keepInQueue=true' is not supported on iOS and should only be set in "
  358. @"multi-client tests");
  359. MutationResult mutationResult(version, absl::nullopt);
  360. [self.driver receiveWriteAckWithVersion:version mutationResults:{mutationResult}];
  361. }
  362. - (void)doFailWrite:(NSDictionary *)spec {
  363. NSDictionary *errorSpec = spec[@"error"];
  364. NSNumber *keepInQueue = spec[@"keepInQueue"];
  365. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  366. [self.driver receiveWriteError:code userInfo:errorSpec keepInQueue:keepInQueue.boolValue];
  367. }
  368. - (void)doDrainQueue {
  369. [self.driver drainQueue];
  370. }
  371. - (void)doRunTimer:(NSString *)timer {
  372. TimerId timerID;
  373. if ([timer isEqualToString:@"all"]) {
  374. timerID = TimerId::All;
  375. } else if ([timer isEqualToString:@"listen_stream_idle"]) {
  376. timerID = TimerId::ListenStreamIdle;
  377. } else if ([timer isEqualToString:@"listen_stream_connection_backoff"]) {
  378. timerID = TimerId::ListenStreamConnectionBackoff;
  379. } else if ([timer isEqualToString:@"write_stream_idle"]) {
  380. timerID = TimerId::WriteStreamIdle;
  381. } else if ([timer isEqualToString:@"write_stream_connection_backoff"]) {
  382. timerID = TimerId::WriteStreamConnectionBackoff;
  383. } else if ([timer isEqualToString:@"online_state_timeout"]) {
  384. timerID = TimerId::OnlineStateTimeout;
  385. } else {
  386. HARD_FAIL("runTimer spec step specified unknown timer: %s", timer);
  387. }
  388. [self.driver runTimer:timerID];
  389. }
  390. - (void)doDisableNetwork {
  391. _networkEnabled = NO;
  392. [self.driver disableNetwork];
  393. }
  394. - (void)doEnableNetwork {
  395. _networkEnabled = YES;
  396. [self.driver enableNetwork];
  397. }
  398. - (void)doChangeUser:(nullable id)UID {
  399. if ([UID isEqual:[NSNull null]]) {
  400. UID = nil;
  401. }
  402. [self.driver changeUser:User::FromUid(UID)];
  403. }
  404. - (void)doRestart {
  405. // Any outstanding user writes should be automatically re-sent, so we want to preserve them
  406. // when re-creating the driver.
  407. FSTOutstandingWriteQueues outstandingWrites = self.driver.outstandingWrites;
  408. User currentUser = self.driver.currentUser;
  409. [self.driver shutdown];
  410. std::unique_ptr<Persistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  411. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:std::move(persistence)
  412. initialUser:currentUser
  413. outstandingWrites:outstandingWrites];
  414. [self.driver start];
  415. }
  416. - (void)doStep:(NSDictionary *)step {
  417. NSNumber *clientIndex = step[@"clientIndex"];
  418. XCTAssertNil(clientIndex, @"The iOS client does not support switching clients");
  419. if (step[@"userListen"]) {
  420. [self doListen:step[@"userListen"]];
  421. } else if (step[@"userUnlisten"]) {
  422. [self doUnlisten:step[@"userUnlisten"]];
  423. } else if (step[@"userSet"]) {
  424. [self doSet:step[@"userSet"]];
  425. } else if (step[@"userPatch"]) {
  426. [self doPatch:step[@"userPatch"]];
  427. } else if (step[@"userDelete"]) {
  428. [self doDelete:step[@"userDelete"]];
  429. } else if (step[@"addSnapshotsInSyncListener"]) {
  430. [self doAddSnapshotsInSyncListener];
  431. } else if (step[@"removeSnapshotsInSyncListener"]) {
  432. [self doRemoveSnapshotsInSyncListener];
  433. } else if (step[@"drainQueue"]) {
  434. [self doDrainQueue];
  435. } else if (step[@"watchAck"]) {
  436. [self doWatchAck:step[@"watchAck"]];
  437. } else if (step[@"watchCurrent"]) {
  438. [self doWatchCurrent:step[@"watchCurrent"]];
  439. } else if (step[@"watchRemove"]) {
  440. [self doWatchRemove:step[@"watchRemove"]];
  441. } else if (step[@"watchEntity"]) {
  442. [self doWatchEntity:step[@"watchEntity"]];
  443. } else if (step[@"watchFilter"]) {
  444. [self doWatchFilter:step[@"watchFilter"]];
  445. } else if (step[@"watchReset"]) {
  446. [self doWatchReset:step[@"watchReset"]];
  447. } else if (step[@"watchSnapshot"]) {
  448. [self doWatchSnapshot:step[@"watchSnapshot"]];
  449. } else if (step[@"watchStreamClose"]) {
  450. [self doWatchStreamClose:step[@"watchStreamClose"]];
  451. } else if (step[@"watchProto"]) {
  452. // watchProto isn't yet used, and it's unclear how to create arbitrary protos from JSON.
  453. HARD_FAIL("watchProto is not yet supported.");
  454. } else if (step[@"writeAck"]) {
  455. [self doWriteAck:step[@"writeAck"]];
  456. } else if (step[@"failWrite"]) {
  457. [self doFailWrite:step[@"failWrite"]];
  458. } else if (step[@"runTimer"]) {
  459. [self doRunTimer:step[@"runTimer"]];
  460. } else if (step[@"enableNetwork"]) {
  461. if ([step[@"enableNetwork"] boolValue]) {
  462. [self doEnableNetwork];
  463. } else {
  464. [self doDisableNetwork];
  465. }
  466. } else if (step[@"changeUser"]) {
  467. [self doChangeUser:step[@"changeUser"]];
  468. } else if (step[@"restart"]) {
  469. [self doRestart];
  470. } else if (step[@"applyClientState"]) {
  471. XCTFail(@"'applyClientState' is not supported on iOS and should only be used in multi-client "
  472. @"tests");
  473. } else {
  474. XCTFail(@"Unknown step: %@", step);
  475. }
  476. }
  477. - (void)validateEvent:(FSTQueryEvent *)actual matches:(NSDictionary *)expected {
  478. Query expectedQuery = [self parseQuery:expected[@"query"]];
  479. XCTAssertEqual(actual.query, expectedQuery);
  480. if ([expected[@"errorCode"] integerValue] != 0) {
  481. XCTAssertNotNil(actual.error);
  482. XCTAssertEqual(actual.error.code, [expected[@"errorCode"] integerValue]);
  483. } else {
  484. std::vector<DocumentViewChange> expectedChanges;
  485. NSMutableArray *removed = expected[@"removed"];
  486. for (NSDictionary *changeSpec in removed) {
  487. expectedChanges.push_back([self parseChange:changeSpec
  488. ofType:DocumentViewChange::Type::Removed]);
  489. }
  490. NSMutableArray *added = expected[@"added"];
  491. for (NSDictionary *changeSpec in added) {
  492. expectedChanges.push_back([self parseChange:changeSpec
  493. ofType:DocumentViewChange::Type::Added]);
  494. }
  495. NSMutableArray *modified = expected[@"modified"];
  496. for (NSDictionary *changeSpec in modified) {
  497. expectedChanges.push_back([self parseChange:changeSpec
  498. ofType:DocumentViewChange::Type::Modified]);
  499. }
  500. NSMutableArray *metadata = expected[@"metadata"];
  501. for (NSDictionary *changeSpec in metadata) {
  502. expectedChanges.push_back([self parseChange:changeSpec
  503. ofType:DocumentViewChange::Type::Metadata]);
  504. }
  505. XCTAssertEqual(actual.viewSnapshot.value().document_changes().size(), expectedChanges.size());
  506. for (size_t i = 0; i != expectedChanges.size(); ++i) {
  507. XCTAssertTrue((actual.viewSnapshot.value().document_changes()[i] == expectedChanges[i]));
  508. }
  509. BOOL expectedHasPendingWrites =
  510. expected[@"hasPendingWrites"] ? [expected[@"hasPendingWrites"] boolValue] : NO;
  511. BOOL expectedIsFromCache = expected[@"fromCache"] ? [expected[@"fromCache"] boolValue] : NO;
  512. XCTAssertEqual(actual.viewSnapshot.value().has_pending_writes(), expectedHasPendingWrites,
  513. @"hasPendingWrites");
  514. XCTAssertEqual(actual.viewSnapshot.value().from_cache(), expectedIsFromCache, @"isFromCache");
  515. }
  516. }
  517. - (void)validateExpectedSnapshotEvents:(NSArray *_Nullable)expectedEvents {
  518. NSArray<FSTQueryEvent *> *events = self.driver.capturedEventsSinceLastCall;
  519. if (!expectedEvents) {
  520. XCTAssertEqual(events.count, 0u);
  521. for (FSTQueryEvent *event in events) {
  522. XCTFail(@"Unexpected event: %@", event);
  523. }
  524. return;
  525. }
  526. XCTAssertEqual(events.count, expectedEvents.count);
  527. events =
  528. [events sortedArrayUsingComparator:^NSComparisonResult(FSTQueryEvent *q1, FSTQueryEvent *q2) {
  529. return util::WrapCompare(q1.query.CanonicalId(), q2.query.CanonicalId());
  530. }];
  531. expectedEvents = [expectedEvents
  532. sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
  533. Query leftQuery = [self parseQuery:left[@"query"]];
  534. Query rightQuery = [self parseQuery:right[@"query"]];
  535. return util::WrapCompare(leftQuery.CanonicalId(), rightQuery.CanonicalId());
  536. }];
  537. NSUInteger i = 0;
  538. for (; i < expectedEvents.count && i < events.count; ++i) {
  539. [self validateEvent:events[i] matches:expectedEvents[i]];
  540. }
  541. for (; i < expectedEvents.count; ++i) {
  542. XCTFail(@"Missing event: %@", expectedEvents[i]);
  543. }
  544. for (; i < events.count; ++i) {
  545. XCTFail(@"Unexpected event: %@", events[i]);
  546. }
  547. }
  548. - (void)validateExpectedState:(nullable NSDictionary *)expectedState {
  549. if (expectedState) {
  550. if (expectedState[@"numOutstandingWrites"]) {
  551. XCTAssertEqual([self.driver sentWritesCount],
  552. [expectedState[@"numOutstandingWrites"] intValue]);
  553. }
  554. if (expectedState[@"writeStreamRequestCount"]) {
  555. XCTAssertEqual([self.driver writeStreamRequestCount],
  556. [expectedState[@"writeStreamRequestCount"] intValue]);
  557. }
  558. if (expectedState[@"watchStreamRequestCount"]) {
  559. XCTAssertEqual([self.driver watchStreamRequestCount],
  560. [expectedState[@"watchStreamRequestCount"] intValue]);
  561. }
  562. if (expectedState[@"limboDocs"]) {
  563. DocumentKeySet expectedLimboDocuments;
  564. NSArray *docNames = expectedState[@"limboDocs"];
  565. for (NSString *name in docNames) {
  566. expectedLimboDocuments = expectedLimboDocuments.insert(FSTTestDocKey(name));
  567. }
  568. // Update the expected limbo documents
  569. [self.driver setExpectedLimboDocuments:std::move(expectedLimboDocuments)];
  570. }
  571. if (expectedState[@"activeTargets"]) {
  572. __block std::unordered_map<TargetId, QueryData> expectedActiveTargets;
  573. [expectedState[@"activeTargets"]
  574. enumerateKeysAndObjectsUsingBlock:^(NSString *targetIDString, NSDictionary *queryData,
  575. BOOL *stop) {
  576. TargetId targetID = [targetIDString intValue];
  577. Query query = [self parseQuery:queryData[@"query"]];
  578. ByteString resumeToken = MakeResumeToken(queryData[@"resumeToken"]);
  579. // TODO(mcg): populate the purpose of the target once it's possible to encode that in
  580. // the spec tests. For now, hard-code that it's a listen despite the fact that it's not
  581. // always the right value.
  582. expectedActiveTargets[targetID] =
  583. QueryData(std::move(query), targetID, 0, QueryPurpose::Listen,
  584. SnapshotVersion::None(), std::move(resumeToken));
  585. }];
  586. [self.driver setExpectedActiveTargets:expectedActiveTargets];
  587. }
  588. }
  589. // Always validate the we received the expected number of callbacks.
  590. [self validateUserCallbacks:expectedState];
  591. // Always validate that the expected limbo docs match the actual limbo docs.
  592. [self validateLimboDocuments];
  593. // Always validate that the expected active targets match the actual active targets.
  594. [self validateActiveTargets];
  595. }
  596. - (void)validateSnapshotsInSyncEvents:(int)expectedSnapshotInSyncEvents {
  597. XCTAssertEqual(expectedSnapshotInSyncEvents, [self.driver snapshotsInSyncEvents]);
  598. [self.driver resetSnapshotsInSyncEvents];
  599. }
  600. - (void)validateUserCallbacks:(nullable NSDictionary *)expected {
  601. NSDictionary *expectedCallbacks = expected[@"userCallbacks"];
  602. NSArray<NSString *> *actualAcknowledgedDocs =
  603. [self.driver capturedAcknowledgedWritesSinceLastCall];
  604. NSArray<NSString *> *actualRejectedDocs = [self.driver capturedRejectedWritesSinceLastCall];
  605. if (expectedCallbacks) {
  606. XCTAssertTrue([actualAcknowledgedDocs isEqualToArray:expectedCallbacks[@"acknowledgedDocs"]]);
  607. XCTAssertTrue([actualRejectedDocs isEqualToArray:expectedCallbacks[@"rejectedDocs"]]);
  608. } else {
  609. XCTAssertEqual([actualAcknowledgedDocs count], 0u);
  610. XCTAssertEqual([actualRejectedDocs count], 0u);
  611. }
  612. }
  613. - (void)validateLimboDocuments {
  614. // Make a copy so it can modified while checking against the expected limbo docs.
  615. std::map<DocumentKey, TargetId> actualLimboDocs = self.driver.currentLimboDocuments;
  616. // Validate that each limbo doc has an expected active target
  617. for (const auto &kv : actualLimboDocs) {
  618. const auto &expected = [self.driver expectedActiveTargets];
  619. XCTAssertTrue(expected.find(kv.second) != expected.end(),
  620. @"Found limbo doc without an expected active target");
  621. }
  622. for (const DocumentKey &expectedLimboDoc : self.driver.expectedLimboDocuments) {
  623. XCTAssert(actualLimboDocs.find(expectedLimboDoc) != actualLimboDocs.end(),
  624. @"Expected doc to be in limbo, but was not: %s", expectedLimboDoc.ToString().c_str());
  625. actualLimboDocs.erase(expectedLimboDoc);
  626. }
  627. XCTAssertTrue(actualLimboDocs.empty(), "%lu Unexpected docs in limbo, the first one is <%s, %d>",
  628. actualLimboDocs.size(), actualLimboDocs.begin()->first.ToString().c_str(),
  629. actualLimboDocs.begin()->second);
  630. }
  631. - (void)validateActiveTargets {
  632. if (!_networkEnabled) {
  633. return;
  634. }
  635. // Create a copy so we can modify it below
  636. std::unordered_map<TargetId, QueryData> actualTargets = [self.driver activeTargets];
  637. for (const auto &kv : [self.driver activeTargets]) {
  638. TargetId targetID = kv.first;
  639. const QueryData &queryData = kv.second;
  640. auto found = actualTargets.find(targetID);
  641. XCTAssertNotEqual(found, actualTargets.end(), @"Expected active target not found: %s",
  642. queryData.ToString().c_str());
  643. // TODO(mcg): validate the purpose of the target once it's possible to encode that in the
  644. // spec tests. For now, only validate properties that can be validated.
  645. // XCTAssertEqualObjects(actualTargets[targetID], queryData);
  646. const QueryData &actual = found->second;
  647. XCTAssertEqual(actual.query(), queryData.query());
  648. XCTAssertEqual(actual.target_id(), queryData.target_id());
  649. XCTAssertEqual(actual.snapshot_version(), queryData.snapshot_version());
  650. XCTAssertEqual(actual.resume_token(), queryData.resume_token());
  651. actualTargets.erase(targetID);
  652. }
  653. XCTAssertTrue(actualTargets.empty(), "Unexpected active targets: %@",
  654. objc::Description(actualTargets));
  655. }
  656. - (void)runSpecTestSteps:(NSArray *)steps config:(NSDictionary *)config {
  657. @try {
  658. [self setUpForSpecWithConfig:config];
  659. for (NSDictionary *step in steps) {
  660. LOG_DEBUG("Doing step %s", step);
  661. [self doStep:step];
  662. [self validateExpectedSnapshotEvents:step[@"expectedSnapshotEvents"]];
  663. [self validateExpectedState:step[@"expectedState"]];
  664. int expectedSnapshotsInSyncEvents = [step[@"expectedSnapshotsInSyncEvents"] intValue];
  665. [self validateSnapshotsInSyncEvents:expectedSnapshotsInSyncEvents];
  666. }
  667. [self.driver validateUsage];
  668. } @finally {
  669. // Ensure that the driver is torn down even if the test is failing due to a thrown exception so
  670. // that any resources held by the driver are released. This is important when the driver is
  671. // backed by LevelDB because LevelDB locks its database. If -tearDownForSpec were not called
  672. // after an exception then subsequent attempts to open the LevelDB will fail, making it harder
  673. // to zero in on the spec tests as a culprit.
  674. [self tearDownForSpec];
  675. }
  676. }
  677. #pragma mark - The actual test methods.
  678. - (void)testSpecTests {
  679. if ([self isTestBaseClass]) return;
  680. // Enumerate the .json files containing the spec tests.
  681. NSMutableArray<NSString *> *specFiles = [NSMutableArray array];
  682. NSMutableArray<NSDictionary *> *parsedSpecs = [NSMutableArray array];
  683. BOOL exclusiveMode = NO;
  684. // TODO(wilhuff): Fix this when running spec tests using a real device
  685. auto source_file = Path::FromUtf8(__FILE__);
  686. Path json_ext = Path::FromUtf8(".json");
  687. auto spec_dir = source_file.Dirname();
  688. auto json_dir = spec_dir.AppendUtf8("json");
  689. auto iter = util::DirectoryIterator::Create(json_dir);
  690. for (; iter->Valid(); iter->Next()) {
  691. Path entry = iter->file();
  692. if (!entry.HasExtension(json_ext)) {
  693. continue;
  694. }
  695. // Read and parse the JSON from the file.
  696. NSString *path = entry.ToNSString();
  697. NSData *json = [NSData dataWithContentsOfFile:path];
  698. XCTAssertNotNil(json);
  699. NSError *error = nil;
  700. id _Nullable parsed = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
  701. XCTAssertNil(error, @"%@", error);
  702. XCTAssertTrue([parsed isKindOfClass:[NSDictionary class]]);
  703. NSDictionary *testDict = (NSDictionary *)parsed;
  704. exclusiveMode = exclusiveMode || [self anyTestsAreMarkedExclusive:testDict];
  705. [specFiles addObject:entry.Basename().ToNSString()];
  706. [parsedSpecs addObject:testDict];
  707. }
  708. // Now iterate over them and run them.
  709. __block bool ranAtLeastOneTest = NO;
  710. for (NSUInteger i = 0; i < specFiles.count; i++) {
  711. NSLog(@"Spec test file: %@", specFiles[i]);
  712. // Iterate over the tests in the file and run them.
  713. [parsedSpecs[i] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  714. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  715. NSDictionary *testDescription = (NSDictionary *)obj;
  716. NSString *describeName = testDescription[@"describeName"];
  717. NSString *itName = testDescription[@"itName"];
  718. NSString *name = [NSString stringWithFormat:@"%@ %@", describeName, itName];
  719. NSDictionary *config = testDescription[@"config"];
  720. NSArray *steps = testDescription[@"steps"];
  721. NSArray<NSString *> *tags = testDescription[@"tags"];
  722. BOOL runTest = !exclusiveMode || [tags indexOfObject:kExclusiveTag] != NSNotFound;
  723. if (runTest) {
  724. runTest = [self shouldRunWithTags:tags];
  725. }
  726. if (runTest) {
  727. NSLog(@" Spec test: %@", name);
  728. [self runSpecTestSteps:steps config:config];
  729. ranAtLeastOneTest = YES;
  730. } else {
  731. NSLog(@" [SKIPPED] Spec test: %@", name);
  732. NSString *comment = testDescription[@"comment"];
  733. if (comment) {
  734. NSLog(@" %@", comment);
  735. }
  736. }
  737. }];
  738. }
  739. XCTAssertTrue(ranAtLeastOneTest);
  740. }
  741. - (BOOL)anyTestsAreMarkedExclusive:(NSDictionary *)tests {
  742. __block BOOL found = NO;
  743. [tests enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  744. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  745. NSDictionary *testDescription = (NSDictionary *)obj;
  746. NSArray<NSString *> *tags = testDescription[@"tags"];
  747. if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  748. found = YES;
  749. *stop = YES;
  750. }
  751. }];
  752. return found;
  753. }
  754. @end
  755. NS_ASSUME_NONNULL_END