FSTSpecTests.mm 35 KB

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