FSTSpecTests.mm 35 KB

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