FSTSpecTests.mm 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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:(NSDictionary *)listenSpec {
  286. Query query = [self parseQuery:listenSpec[@"query"]];
  287. TargetId actualID = [self.driver addUserListenerWithQuery:std::move(query)];
  288. TargetId expectedID = [listenSpec[@"targetId"] 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 writeUserMutation:FSTTestPatchMutation(patchSpec[0], patchSpec[1], {})];
  300. }
  301. - (void)doDelete:(NSString *)key {
  302. [self.driver writeUserMutation:FSTTestDeleteMutation(key)];
  303. }
  304. - (void)doWaitForPendingWrites {
  305. [self.driver waitForPendingWrites];
  306. }
  307. - (void)doAddSnapshotsInSyncListener {
  308. [self.driver addSnapshotsInSyncListener];
  309. }
  310. - (void)doRemoveSnapshotsInSyncListener {
  311. [self.driver removeSnapshotsInSyncListener];
  312. }
  313. - (void)doWatchAck:(NSArray<NSNumber *> *)ackedTargets {
  314. WatchTargetChange change{WatchTargetChangeState::Added, ConvertTargetsArray(ackedTargets)};
  315. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  316. }
  317. - (void)doWatchCurrent:(NSArray<id> *)currentSpec {
  318. NSArray<NSNumber *> *currentTargets = currentSpec[0];
  319. ByteString resumeToken = MakeResumeToken(currentSpec[1]);
  320. WatchTargetChange change{WatchTargetChangeState::Current, ConvertTargetsArray(currentTargets),
  321. resumeToken};
  322. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  323. }
  324. - (void)doWatchRemove:(NSDictionary *)watchRemoveSpec {
  325. Status error;
  326. NSDictionary *cause = watchRemoveSpec[@"cause"];
  327. if (cause) {
  328. int code = ((NSNumber *)cause[@"code"]).intValue;
  329. NSDictionary *userInfo = @{
  330. NSLocalizedDescriptionKey : @"Error from watchRemove.",
  331. };
  332. error = Status{static_cast<Error>(code), MakeString([userInfo description])};
  333. }
  334. WatchTargetChange change{WatchTargetChangeState::Removed,
  335. ConvertTargetsArray(watchRemoveSpec[@"targetIds"]), error};
  336. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  337. // Unlike web, the FSTMockDatastore detects a watch removal with cause and will remove active
  338. // targets
  339. }
  340. - (void)doWatchEntity:(NSDictionary *)watchEntity {
  341. if (watchEntity[@"docs"]) {
  342. HARD_ASSERT(!watchEntity[@"doc"], "Exactly one of |doc| or |docs| needs to be set.");
  343. NSArray *docs = watchEntity[@"docs"];
  344. for (NSDictionary *doc in docs) {
  345. NSMutableDictionary *watchSpec = [NSMutableDictionary dictionary];
  346. watchSpec[@"doc"] = doc;
  347. if (watchEntity[@"targets"]) {
  348. watchSpec[@"targets"] = watchEntity[@"targets"];
  349. }
  350. if (watchEntity[@"removedTargets"]) {
  351. watchSpec[@"removedTargets"] = watchEntity[@"removedTargets"];
  352. }
  353. [self doWatchEntity:watchSpec];
  354. }
  355. } else if (watchEntity[@"doc"]) {
  356. NSDictionary *docSpec = watchEntity[@"doc"];
  357. DocumentKey key = FSTTestDocKey(docSpec[@"key"]);
  358. absl::optional<ObjectValue> value = [docSpec[@"value"] isKindOfClass:[NSNull class]]
  359. ? absl::optional<ObjectValue>{}
  360. : FSTTestObjectValue(docSpec[@"value"]);
  361. SnapshotVersion version = [self parseVersion:docSpec[@"version"]];
  362. MaybeDocument doc;
  363. if (value) {
  364. doc = Document(*std::move(value), key, version, DocumentState::kSynced);
  365. } else {
  366. doc = NoDocument(key, version, /* has_committed_mutations= */ false);
  367. }
  368. DocumentWatchChange change{ConvertTargetsArray(watchEntity[@"targets"]),
  369. ConvertTargetsArray(watchEntity[@"removedTargets"]), std::move(key),
  370. std::move(doc)};
  371. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  372. } else if (watchEntity[@"key"]) {
  373. DocumentKey docKey = FSTTestDocKey(watchEntity[@"key"]);
  374. DocumentWatchChange change{
  375. {}, ConvertTargetsArray(watchEntity[@"removedTargets"]), docKey, absl::nullopt};
  376. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  377. } else {
  378. HARD_FAIL("Either key, doc or docs must be set.");
  379. }
  380. }
  381. - (void)doWatchFilter:(NSArray *)watchFilter {
  382. NSArray<NSNumber *> *targets = watchFilter[0];
  383. HARD_ASSERT(targets.count == 1, "ExistenceFilters currently support exactly one target only.");
  384. int keyCount = watchFilter.count == 0 ? 0 : (int)watchFilter.count - 1;
  385. ExistenceFilter filter{keyCount};
  386. ExistenceFilterWatchChange change{filter, targets[0].intValue};
  387. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  388. }
  389. - (void)doWatchReset:(NSArray<NSNumber *> *)watchReset {
  390. WatchTargetChange change{WatchTargetChangeState::Reset, ConvertTargetsArray(watchReset)};
  391. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  392. }
  393. - (void)doWatchSnapshot:(NSDictionary *)watchSnapshot {
  394. // The client will only respond to watchSnapshots if they are on a target change with an empty
  395. // set of target IDs.
  396. NSArray<NSNumber *> *targetIDs =
  397. watchSnapshot[@"targetIds"] ? watchSnapshot[@"targetIds"] : [NSArray array];
  398. ByteString resumeToken = MakeResumeToken(watchSnapshot[@"resumeToken"]);
  399. WatchTargetChange change{WatchTargetChangeState::NoChange, ConvertTargetsArray(targetIDs),
  400. resumeToken};
  401. [self.driver receiveWatchChange:change
  402. snapshotVersion:[self parseVersion:watchSnapshot[@"version"]]];
  403. }
  404. - (void)doWatchStreamClose:(NSDictionary *)closeSpec {
  405. NSDictionary *errorSpec = closeSpec[@"error"];
  406. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  407. NSNumber *runBackoffTimer = closeSpec[@"runBackoffTimer"];
  408. // TODO(b/72313632): Incorporate backoff in iOS Spec Tests.
  409. HARD_ASSERT(runBackoffTimer.boolValue, "iOS Spec Tests don't support backoff.");
  410. [self.driver receiveWatchStreamError:code userInfo:errorSpec];
  411. }
  412. - (void)doWriteAck:(NSDictionary *)spec {
  413. SnapshotVersion version = [self parseVersion:spec[@"version"]];
  414. NSNumber *keepInQueue = spec[@"keepInQueue"];
  415. XCTAssertTrue(keepInQueue == nil || keepInQueue.boolValue == NO,
  416. @"'keepInQueue=true' is not supported on iOS and should only be set in "
  417. @"multi-client tests");
  418. MutationResult mutationResult(version, absl::nullopt);
  419. [self.driver receiveWriteAckWithVersion:version mutationResults:{mutationResult}];
  420. }
  421. - (void)doFailWrite:(NSDictionary *)spec {
  422. NSDictionary *errorSpec = spec[@"error"];
  423. NSNumber *keepInQueue = spec[@"keepInQueue"];
  424. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  425. [self.driver receiveWriteError:code userInfo:errorSpec keepInQueue:keepInQueue.boolValue];
  426. }
  427. - (void)doDrainQueue {
  428. [self.driver drainQueue];
  429. }
  430. - (void)doRunTimer:(NSString *)timer {
  431. TimerId timerID;
  432. if ([timer isEqualToString:@"all"]) {
  433. timerID = TimerId::All;
  434. } else if ([timer isEqualToString:@"listen_stream_idle"]) {
  435. timerID = TimerId::ListenStreamIdle;
  436. } else if ([timer isEqualToString:@"listen_stream_connection_backoff"]) {
  437. timerID = TimerId::ListenStreamConnectionBackoff;
  438. } else if ([timer isEqualToString:@"write_stream_idle"]) {
  439. timerID = TimerId::WriteStreamIdle;
  440. } else if ([timer isEqualToString:@"write_stream_connection_backoff"]) {
  441. timerID = TimerId::WriteStreamConnectionBackoff;
  442. } else if ([timer isEqualToString:@"online_state_timeout"]) {
  443. timerID = TimerId::OnlineStateTimeout;
  444. } else {
  445. HARD_FAIL("runTimer spec step specified unknown timer: %s", timer);
  446. }
  447. [self.driver runTimer:timerID];
  448. }
  449. - (void)doDisableNetwork {
  450. _networkEnabled = NO;
  451. [self.driver disableNetwork];
  452. }
  453. - (void)doEnableNetwork {
  454. _networkEnabled = YES;
  455. [self.driver enableNetwork];
  456. }
  457. - (void)doChangeUser:(nullable id)UID {
  458. if ([UID isEqual:[NSNull null]]) {
  459. UID = nil;
  460. }
  461. [self.driver changeUser:User::FromUid(UID)];
  462. }
  463. - (void)doRestart {
  464. // Any outstanding user writes should be automatically re-sent, so we want to preserve them
  465. // when re-creating the driver.
  466. FSTOutstandingWriteQueues outstandingWrites = self.driver.outstandingWrites;
  467. User currentUser = self.driver.currentUser;
  468. [self.driver shutdown];
  469. std::unique_ptr<Persistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  470. self.driver =
  471. [[FSTSyncEngineTestDriver alloc] initWithPersistence:std::move(persistence)
  472. initialUser:currentUser
  473. outstandingWrites:outstandingWrites
  474. maxConcurrentLimboResolutions:_maxConcurrentLimboResolutions];
  475. [self.driver start];
  476. }
  477. - (void)doStep:(NSDictionary *)step {
  478. NSNumber *clientIndex = step[@"clientIndex"];
  479. XCTAssertNil(clientIndex, @"The iOS client does not support switching clients");
  480. if (step[@"userListen"]) {
  481. [self doListen:step[@"userListen"]];
  482. } else if (step[@"userUnlisten"]) {
  483. [self doUnlisten:step[@"userUnlisten"]];
  484. } else if (step[@"userSet"]) {
  485. [self doSet:step[@"userSet"]];
  486. } else if (step[@"userPatch"]) {
  487. [self doPatch:step[@"userPatch"]];
  488. } else if (step[@"userDelete"]) {
  489. [self doDelete:step[@"userDelete"]];
  490. } else if (step[@"addSnapshotsInSyncListener"]) {
  491. [self doAddSnapshotsInSyncListener];
  492. } else if (step[@"removeSnapshotsInSyncListener"]) {
  493. [self doRemoveSnapshotsInSyncListener];
  494. } else if (step[@"drainQueue"]) {
  495. [self doDrainQueue];
  496. } else if (step[@"watchAck"]) {
  497. [self doWatchAck:step[@"watchAck"]];
  498. } else if (step[@"watchCurrent"]) {
  499. [self doWatchCurrent:step[@"watchCurrent"]];
  500. } else if (step[@"watchRemove"]) {
  501. [self doWatchRemove:step[@"watchRemove"]];
  502. } else if (step[@"watchEntity"]) {
  503. [self doWatchEntity:step[@"watchEntity"]];
  504. } else if (step[@"watchFilter"]) {
  505. [self doWatchFilter:step[@"watchFilter"]];
  506. } else if (step[@"watchReset"]) {
  507. [self doWatchReset:step[@"watchReset"]];
  508. } else if (step[@"watchSnapshot"]) {
  509. [self doWatchSnapshot:step[@"watchSnapshot"]];
  510. } else if (step[@"watchStreamClose"]) {
  511. [self doWatchStreamClose:step[@"watchStreamClose"]];
  512. } else if (step[@"watchProto"]) {
  513. // watchProto isn't yet used, and it's unclear how to create arbitrary protos from JSON.
  514. HARD_FAIL("watchProto is not yet supported.");
  515. } else if (step[@"writeAck"]) {
  516. [self doWriteAck:step[@"writeAck"]];
  517. } else if (step[@"failWrite"]) {
  518. [self doFailWrite:step[@"failWrite"]];
  519. } else if (step[@"waitForPendingWrites"]) {
  520. [self doWaitForPendingWrites];
  521. } else if (step[@"runTimer"]) {
  522. [self doRunTimer:step[@"runTimer"]];
  523. } else if (step[@"enableNetwork"]) {
  524. if ([step[@"enableNetwork"] boolValue]) {
  525. [self doEnableNetwork];
  526. } else {
  527. [self doDisableNetwork];
  528. }
  529. } else if (step[@"changeUser"]) {
  530. [self doChangeUser:step[@"changeUser"]];
  531. } else if (step[@"restart"]) {
  532. [self doRestart];
  533. } else if (step[@"applyClientState"]) {
  534. XCTFail(@"'applyClientState' is not supported on iOS and should only be used in multi-client "
  535. @"tests");
  536. } else {
  537. XCTFail(@"Unknown step: %@", step);
  538. }
  539. }
  540. - (void)validateEvent:(FSTQueryEvent *)actual matches:(NSDictionary *)expected {
  541. Query expectedQuery = [self parseQuery:expected[@"query"]];
  542. XCTAssertEqual(actual.query, expectedQuery);
  543. if ([expected[@"errorCode"] integerValue] != 0) {
  544. XCTAssertNotNil(actual.error);
  545. XCTAssertEqual(actual.error.code, [expected[@"errorCode"] integerValue]);
  546. } else {
  547. std::vector<DocumentViewChange> expectedChanges;
  548. NSMutableArray *removed = expected[@"removed"];
  549. for (NSDictionary *changeSpec in removed) {
  550. expectedChanges.push_back([self parseChange:changeSpec
  551. ofType:DocumentViewChange::Type::Removed]);
  552. }
  553. NSMutableArray *added = expected[@"added"];
  554. for (NSDictionary *changeSpec in added) {
  555. expectedChanges.push_back([self parseChange:changeSpec
  556. ofType:DocumentViewChange::Type::Added]);
  557. }
  558. NSMutableArray *modified = expected[@"modified"];
  559. for (NSDictionary *changeSpec in modified) {
  560. expectedChanges.push_back([self parseChange:changeSpec
  561. ofType:DocumentViewChange::Type::Modified]);
  562. }
  563. NSMutableArray *metadata = expected[@"metadata"];
  564. for (NSDictionary *changeSpec in metadata) {
  565. expectedChanges.push_back([self parseChange:changeSpec
  566. ofType:DocumentViewChange::Type::Metadata]);
  567. }
  568. XCTAssertEqual(actual.viewSnapshot.value().document_changes().size(), expectedChanges.size());
  569. for (size_t i = 0; i != expectedChanges.size(); ++i) {
  570. XCTAssertTrue((actual.viewSnapshot.value().document_changes()[i] == expectedChanges[i]));
  571. }
  572. BOOL expectedHasPendingWrites =
  573. expected[@"hasPendingWrites"] ? [expected[@"hasPendingWrites"] boolValue] : NO;
  574. BOOL expectedIsFromCache = expected[@"fromCache"] ? [expected[@"fromCache"] boolValue] : NO;
  575. XCTAssertEqual(actual.viewSnapshot.value().has_pending_writes(), expectedHasPendingWrites,
  576. @"hasPendingWrites");
  577. XCTAssertEqual(actual.viewSnapshot.value().from_cache(), expectedIsFromCache, @"isFromCache");
  578. }
  579. }
  580. - (void)validateExpectedSnapshotEvents:(NSArray *_Nullable)expectedEvents {
  581. NSArray<FSTQueryEvent *> *events = self.driver.capturedEventsSinceLastCall;
  582. if (!expectedEvents) {
  583. XCTAssertEqual(events.count, 0u);
  584. for (FSTQueryEvent *event in events) {
  585. XCTFail(@"Unexpected event: %@", event);
  586. }
  587. return;
  588. }
  589. XCTAssertEqual(events.count, expectedEvents.count);
  590. events =
  591. [events sortedArrayUsingComparator:^NSComparisonResult(FSTQueryEvent *q1, FSTQueryEvent *q2) {
  592. return util::WrapCompare(q1.query.CanonicalId(), q2.query.CanonicalId());
  593. }];
  594. expectedEvents = [expectedEvents
  595. sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
  596. Query leftQuery = [self parseQuery:left[@"query"]];
  597. Query rightQuery = [self parseQuery:right[@"query"]];
  598. return util::WrapCompare(leftQuery.CanonicalId(), rightQuery.CanonicalId());
  599. }];
  600. NSUInteger i = 0;
  601. for (; i < expectedEvents.count && i < events.count; ++i) {
  602. [self validateEvent:events[i] matches:expectedEvents[i]];
  603. }
  604. for (; i < expectedEvents.count; ++i) {
  605. XCTFail(@"Missing event: %@", expectedEvents[i]);
  606. }
  607. for (; i < events.count; ++i) {
  608. XCTFail(@"Unexpected event: %@", events[i]);
  609. }
  610. }
  611. - (void)validateExpectedState:(nullable NSDictionary *)expectedState {
  612. if (expectedState) {
  613. if (expectedState[@"numOutstandingWrites"]) {
  614. XCTAssertEqual([self.driver sentWritesCount],
  615. [expectedState[@"numOutstandingWrites"] intValue]);
  616. }
  617. if (expectedState[@"writeStreamRequestCount"]) {
  618. XCTAssertEqual([self.driver writeStreamRequestCount],
  619. [expectedState[@"writeStreamRequestCount"] intValue]);
  620. }
  621. if (expectedState[@"watchStreamRequestCount"]) {
  622. XCTAssertEqual([self.driver watchStreamRequestCount],
  623. [expectedState[@"watchStreamRequestCount"] intValue]);
  624. }
  625. if (expectedState[@"activeLimboDocs"]) {
  626. DocumentKeySet expectedActiveLimboDocuments;
  627. NSArray *docNames = expectedState[@"activeLimboDocs"];
  628. for (NSString *name in docNames) {
  629. expectedActiveLimboDocuments = expectedActiveLimboDocuments.insert(FSTTestDocKey(name));
  630. }
  631. // Update the expected active limbo documents
  632. [self.driver setExpectedActiveLimboDocuments:std::move(expectedActiveLimboDocuments)];
  633. }
  634. if (expectedState[@"enqueuedLimboDocs"]) {
  635. DocumentKeySet expectedEnqueuedLimboDocuments;
  636. NSArray *docNames = expectedState[@"enqueuedLimboDocs"];
  637. for (NSString *name in docNames) {
  638. expectedEnqueuedLimboDocuments = expectedEnqueuedLimboDocuments.insert(FSTTestDocKey(name));
  639. }
  640. // Update the expected enqueued limbo documents
  641. [self.driver setExpectedEnqueuedLimboDocuments:std::move(expectedEnqueuedLimboDocuments)];
  642. }
  643. if (expectedState[@"activeTargets"]) {
  644. __block ActiveTargetMap expectedActiveTargets;
  645. [expectedState[@"activeTargets"]
  646. enumerateKeysAndObjectsUsingBlock:^(NSString *targetIDString, NSDictionary *queryData,
  647. BOOL *) {
  648. TargetId targetID = [targetIDString intValue];
  649. ByteString resumeToken = MakeResumeToken(queryData[@"resumeToken"]);
  650. NSArray *queriesJson = queryData[@"queries"];
  651. std::vector<TargetData> queries;
  652. for (id queryJson in queriesJson) {
  653. Query query = [self parseQuery:queryJson];
  654. // TODO(mcg): populate the purpose of the target once it's possible to encode that in
  655. // the spec tests. For now, hard-code that it's a listen despite the fact that it's
  656. // not always the right value.
  657. queries.push_back(TargetData(query.ToTarget(), targetID, 0, QueryPurpose::Listen,
  658. SnapshotVersion::None(), SnapshotVersion::None(),
  659. std::move(resumeToken)));
  660. }
  661. expectedActiveTargets[targetID] = std::make_pair(std::move(queries), resumeToken);
  662. }];
  663. [self.driver setExpectedActiveTargets:std::move(expectedActiveTargets)];
  664. }
  665. }
  666. // Always validate the we received the expected number of callbacks.
  667. [self validateUserCallbacks:expectedState];
  668. // Always validate that the expected limbo docs match the actual limbo docs.
  669. [self validateActiveLimboDocuments];
  670. [self validateEnqueuedLimboDocuments];
  671. // Always validate that the expected active targets match the actual active targets.
  672. [self validateActiveTargets];
  673. }
  674. - (void)validateWaitForPendingWritesEvents:(int)expectedWaitForPendingWritesEvents {
  675. XCTAssertEqual(expectedWaitForPendingWritesEvents, [self.driver waitForPendingWritesEvents]);
  676. [self.driver resetWaitForPendingWritesEvents];
  677. }
  678. - (void)validateSnapshotsInSyncEvents:(int)expectedSnapshotInSyncEvents {
  679. XCTAssertEqual(expectedSnapshotInSyncEvents, [self.driver snapshotsInSyncEvents]);
  680. [self.driver resetSnapshotsInSyncEvents];
  681. }
  682. - (void)validateUserCallbacks:(nullable NSDictionary *)expected {
  683. NSDictionary *expectedCallbacks = expected[@"userCallbacks"];
  684. NSArray<NSString *> *actualAcknowledgedDocs =
  685. [self.driver capturedAcknowledgedWritesSinceLastCall];
  686. NSArray<NSString *> *actualRejectedDocs = [self.driver capturedRejectedWritesSinceLastCall];
  687. if (expectedCallbacks) {
  688. XCTAssertTrue([actualAcknowledgedDocs isEqualToArray:expectedCallbacks[@"acknowledgedDocs"]]);
  689. XCTAssertTrue([actualRejectedDocs isEqualToArray:expectedCallbacks[@"rejectedDocs"]]);
  690. } else {
  691. XCTAssertEqual([actualAcknowledgedDocs count], 0u);
  692. XCTAssertEqual([actualRejectedDocs count], 0u);
  693. }
  694. }
  695. - (void)validateActiveLimboDocuments {
  696. // Make a copy so it can modified while checking against the expected limbo docs.
  697. std::map<DocumentKey, TargetId> actualLimboDocs = self.driver.activeLimboDocumentResolutions;
  698. // Validate that each active limbo doc has an expected active target
  699. for (const auto &kv : actualLimboDocs) {
  700. const auto &expected = [self.driver expectedActiveTargets];
  701. XCTAssertTrue(expected.find(kv.second) != expected.end(),
  702. @"Found limbo doc %s, but its target ID %d was not in the "
  703. @"set of expected active target IDs %@",
  704. kv.first.ToString().c_str(), kv.second, ToTargetIdListString(expected));
  705. }
  706. for (const DocumentKey &expectedLimboDoc : self.driver.expectedActiveLimboDocuments) {
  707. XCTAssert(actualLimboDocs.find(expectedLimboDoc) != actualLimboDocs.end(),
  708. @"Expected doc to be in limbo, but was not: %s", expectedLimboDoc.ToString().c_str());
  709. actualLimboDocs.erase(expectedLimboDoc);
  710. }
  711. XCTAssertTrue(actualLimboDocs.empty(), @"Unexpected active docs in limbo: %@",
  712. ToDocumentListString(actualLimboDocs));
  713. }
  714. - (void)validateEnqueuedLimboDocuments {
  715. std::set<DocumentKey> actualLimboDocs;
  716. for (const auto &key : self.driver.enqueuedLimboDocumentResolutions) {
  717. actualLimboDocs.insert(key);
  718. }
  719. std::set<DocumentKey> expectedLimboDocs;
  720. for (const auto &key : self.driver.expectedEnqueuedLimboDocuments) {
  721. expectedLimboDocs.insert(key);
  722. }
  723. for (const auto &key : actualLimboDocs) {
  724. XCTAssertTrue(expectedLimboDocs.find(key) != expectedLimboDocs.end(),
  725. @"Found enqueued limbo doc %s, but it was not in the set of "
  726. @"expected enqueued limbo documents (%@)",
  727. key.ToString().c_str(), ToDocumentListString(expectedLimboDocs));
  728. }
  729. for (const auto &key : expectedLimboDocs) {
  730. XCTAssertTrue(actualLimboDocs.find(key) != actualLimboDocs.end(),
  731. @"Expected doc %s to be enqueued for limbo resolution, "
  732. @"but it was not in the queue (%@)",
  733. key.ToString().c_str(), ToDocumentListString(actualLimboDocs));
  734. }
  735. }
  736. - (void)validateActiveTargets {
  737. if (!_networkEnabled) {
  738. return;
  739. }
  740. // Create a copy so we can modify it below
  741. std::unordered_map<TargetId, TargetData> actualTargets = [self.driver activeTargets];
  742. for (const auto &kv : [self.driver expectedActiveTargets]) {
  743. TargetId targetID = kv.first;
  744. const std::pair<std::vector<TargetData>, ByteString> &queries = kv.second;
  745. const TargetData &targetData = queries.first[0];
  746. auto found = actualTargets.find(targetID);
  747. XCTAssertNotEqual(found, actualTargets.end(), @"Expected active target not found: %s",
  748. targetData.ToString().c_str());
  749. // TODO(mcg): validate the purpose of the target once it's possible to encode that in the
  750. // spec tests. For now, only validate properties that can be validated.
  751. // XCTAssertEqualObjects(actualTargets[targetID], TargetData);
  752. const TargetData &actual = found->second;
  753. XCTAssertEqual(actual.target(), targetData.target());
  754. XCTAssertEqual(actual.target_id(), targetData.target_id());
  755. XCTAssertEqual(actual.snapshot_version(), targetData.snapshot_version());
  756. XCTAssertEqual(actual.resume_token(), targetData.resume_token());
  757. actualTargets.erase(targetID);
  758. }
  759. XCTAssertTrue(actualTargets.empty(), "Unexpected active targets: %s",
  760. util::ToString(actualTargets).c_str());
  761. }
  762. - (void)runSpecTestSteps:(NSArray *)steps config:(NSDictionary *)config {
  763. @autoreleasepool {
  764. @try {
  765. [self setUpForSpecWithConfig:config];
  766. for (NSDictionary *step in steps) {
  767. LOG_DEBUG("Doing step %s", step);
  768. [self doStep:step];
  769. [self validateExpectedSnapshotEvents:step[@"expectedSnapshotEvents"]];
  770. [self validateExpectedState:step[@"expectedState"]];
  771. int expectedSnapshotsInSyncEvents = [step[@"expectedSnapshotsInSyncEvents"] intValue];
  772. [self validateSnapshotsInSyncEvents:expectedSnapshotsInSyncEvents];
  773. int expectedWaitForPendingWritesEvents =
  774. [step[@"expectedWaitForPendingWritesEvents"] intValue];
  775. [self validateWaitForPendingWritesEvents:expectedWaitForPendingWritesEvents];
  776. }
  777. [self.driver validateUsage];
  778. } @finally {
  779. // Ensure that the driver is torn down even if the test is failing due to a thrown exception
  780. // so that any resources held by the driver are released. This is important when the driver is
  781. // backed by LevelDB because LevelDB locks its database. If -tearDownForSpec were not called
  782. // after an exception then subsequent attempts to open the LevelDB will fail, making it harder
  783. // to zero in on the spec tests as a culprit.
  784. [self tearDownForSpec];
  785. }
  786. }
  787. }
  788. #pragma mark - The actual test methods.
  789. - (void)testSpecTests {
  790. if ([self isTestBaseClass]) return;
  791. // Enumerate the .json files containing the spec tests.
  792. NSMutableArray<NSString *> *specFiles = [NSMutableArray array];
  793. NSMutableArray<NSDictionary *> *parsedSpecs = [NSMutableArray array];
  794. BOOL exclusiveMode = NO;
  795. // TODO(wilhuff): Fix this when running spec tests using a real device
  796. auto source_file = Path::FromUtf8(__FILE__);
  797. Path json_ext = Path::FromUtf8(".json");
  798. auto spec_dir = source_file.Dirname();
  799. auto json_dir = spec_dir.AppendUtf8("json");
  800. auto iter = util::DirectoryIterator::Create(json_dir);
  801. for (; iter->Valid(); iter->Next()) {
  802. Path entry = iter->file();
  803. if (!entry.HasExtension(json_ext)) {
  804. continue;
  805. }
  806. // Read and parse the JSON from the file.
  807. NSString *path = entry.ToNSString();
  808. NSData *json = [NSData dataWithContentsOfFile:path];
  809. XCTAssertNotNil(json);
  810. NSError *error = nil;
  811. id _Nullable parsed = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
  812. XCTAssertNil(error, @"%@", error);
  813. XCTAssertTrue([parsed isKindOfClass:[NSDictionary class]]);
  814. NSDictionary *testDict = (NSDictionary *)parsed;
  815. exclusiveMode = exclusiveMode || [self anyTestsAreMarkedExclusive:testDict];
  816. [specFiles addObject:entry.Basename().ToNSString()];
  817. [parsedSpecs addObject:testDict];
  818. }
  819. NSString *testNameFilterFromEnv = NSProcessInfo.processInfo.environment[kTestFilterEnvKey];
  820. NSRegularExpression *testNameFilter;
  821. if (testNameFilterFromEnv.length == 0) {
  822. testNameFilter = nil;
  823. } else {
  824. exclusiveMode = YES;
  825. NSError *error;
  826. testNameFilter =
  827. [NSRegularExpression regularExpressionWithPattern:testNameFilterFromEnv
  828. options:NSRegularExpressionAnchorsMatchLines
  829. error:&error];
  830. XCTAssertNotNil(testNameFilter, @"Invalid regular expression: %@ (%@)", testNameFilterFromEnv,
  831. error);
  832. }
  833. // Now iterate over them and run them.
  834. __block int testPassCount = 0;
  835. __block int testSkipCount = 0;
  836. __block bool ranAtLeastOneTest = NO;
  837. for (NSUInteger i = 0; i < specFiles.count; i++) {
  838. NSLog(@"Spec test file: %@", specFiles[i]);
  839. // Iterate over the tests in the file and run them.
  840. [parsedSpecs[i] enumerateKeysAndObjectsUsingBlock:^(id, id obj, BOOL *) {
  841. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  842. NSDictionary *testDescription = (NSDictionary *)obj;
  843. NSString *describeName = testDescription[@"describeName"];
  844. NSString *itName = testDescription[@"itName"];
  845. NSString *name = [NSString stringWithFormat:@"%@ %@", describeName, itName];
  846. NSDictionary *config = testDescription[@"config"];
  847. NSArray *steps = testDescription[@"steps"];
  848. NSArray<NSString *> *tags = testDescription[@"tags"];
  849. BOOL runTest;
  850. if (![self shouldRunWithTags:tags]) {
  851. runTest = NO;
  852. } else if (!exclusiveMode) {
  853. runTest = YES;
  854. } else if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  855. runTest = YES;
  856. } else if (testNameFilter != nil) {
  857. NSRange testNameFilterMatchRange =
  858. [testNameFilter rangeOfFirstMatchInString:name
  859. options:0
  860. range:NSMakeRange(0, [name length])];
  861. runTest = !NSEqualRanges(testNameFilterMatchRange, NSMakeRange(NSNotFound, 0));
  862. } else {
  863. runTest = NO;
  864. }
  865. if (runTest) {
  866. NSLog(@" Spec test: %@", name);
  867. [self runSpecTestSteps:steps config:config];
  868. ranAtLeastOneTest = YES;
  869. ++testPassCount;
  870. } else {
  871. ++testSkipCount;
  872. NSLog(@" [SKIPPED] Spec test: %@", name);
  873. NSString *comment = testDescription[@"comment"];
  874. if (comment) {
  875. NSLog(@" %@", comment);
  876. }
  877. }
  878. }];
  879. }
  880. NSLog(@"%@ completed; pass=%d skip=%d", NSStringFromClass([self class]), testPassCount,
  881. testSkipCount);
  882. XCTAssertTrue(ranAtLeastOneTest);
  883. }
  884. - (BOOL)anyTestsAreMarkedExclusive:(NSDictionary *)tests {
  885. __block BOOL found = NO;
  886. [tests enumerateKeysAndObjectsUsingBlock:^(id, id obj, BOOL *stop) {
  887. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  888. NSDictionary *testDescription = (NSDictionary *)obj;
  889. NSArray<NSString *> *tags = testDescription[@"tags"];
  890. if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  891. found = YES;
  892. *stop = YES;
  893. }
  894. }];
  895. return found;
  896. }
  897. @end
  898. NS_ASSUME_NONNULL_END