FSTSpecTests.mm 40 KB

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