FSTSpecTests.mm 42 KB

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