FSTSpecTests.mm 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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/FSTUserDataReader.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/bundle/bundle_reader.h"
  35. #include "Firestore/core/src/bundle/bundle_serializer.h"
  36. #include "Firestore/core/src/core/field_filter.h"
  37. #include "Firestore/core/src/credentials/user.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/mutable_document.h"
  45. #include "Firestore/core/src/model/patch_mutation.h"
  46. #include "Firestore/core/src/model/resource_path.h"
  47. #include "Firestore/core/src/model/set_mutation.h"
  48. #include "Firestore/core/src/model/snapshot_version.h"
  49. #include "Firestore/core/src/model/types.h"
  50. #include "Firestore/core/src/nanopb/message.h"
  51. #include "Firestore/core/src/nanopb/nanopb_util.h"
  52. #include "Firestore/core/src/remote/existence_filter.h"
  53. #include "Firestore/core/src/remote/serializer.h"
  54. #include "Firestore/core/src/remote/watch_change.h"
  55. #include "Firestore/core/src/util/async_queue.h"
  56. #include "Firestore/core/src/util/byte_stream_cpp.h"
  57. #include "Firestore/core/src/util/comparison.h"
  58. #include "Firestore/core/src/util/filesystem.h"
  59. #include "Firestore/core/src/util/hard_assert.h"
  60. #include "Firestore/core/src/util/log.h"
  61. #include "Firestore/core/src/util/path.h"
  62. #include "Firestore/core/src/util/status.h"
  63. #include "Firestore/core/src/util/string_apple.h"
  64. #include "Firestore/core/src/util/to_string.h"
  65. #include "Firestore/core/test/unit/testutil/testutil.h"
  66. #include "absl/memory/memory.h"
  67. #include "absl/types/optional.h"
  68. namespace objc = firebase::firestore::objc;
  69. namespace testutil = firebase::firestore::testutil;
  70. namespace util = firebase::firestore::util;
  71. using firebase::firestore::Error;
  72. using firebase::firestore::api::LoadBundleTask;
  73. using firebase::firestore::bundle::BundleReader;
  74. using firebase::firestore::bundle::BundleSerializer;
  75. using firebase::firestore::core::DocumentViewChange;
  76. using firebase::firestore::core::Query;
  77. using firebase::firestore::credentials::User;
  78. using firebase::firestore::google_firestore_v1_ArrayValue;
  79. using firebase::firestore::google_firestore_v1_Value;
  80. using firebase::firestore::local::Persistence;
  81. using firebase::firestore::local::QueryPurpose;
  82. using firebase::firestore::local::TargetData;
  83. using firebase::firestore::model::Document;
  84. using firebase::firestore::model::Document;
  85. using firebase::firestore::model::DocumentKey;
  86. using firebase::firestore::model::DocumentKeySet;
  87. using firebase::firestore::model::MutableDocument;
  88. using firebase::firestore::model::MutationResult;
  89. using firebase::firestore::model::ObjectValue;
  90. using firebase::firestore::model::ResourcePath;
  91. using firebase::firestore::model::SnapshotVersion;
  92. using firebase::firestore::model::TargetId;
  93. using firebase::firestore::nanopb::ByteString;
  94. using firebase::firestore::nanopb::MakeByteString;
  95. using firebase::firestore::nanopb::Message;
  96. using firebase::firestore::remote::DocumentWatchChange;
  97. using firebase::firestore::remote::ExistenceFilter;
  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. FSTUserDataReader *_reader;
  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. _reader = FSTTestUserDataReader();
  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. Message<google_firestore_v1_Value> value = [_reader parsedQueryValue:filter[2]];
  262. query = query.AddingFilter(Filter(key, op, std::move(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. XCTAssert([jsonDoc[@"key"] isKindOfClass:[NSString class]]);
  286. Message<google_firestore_v1_Value> data = [_reader parsedQueryValue:jsonDoc[@"value"]];
  287. MutableDocument doc =
  288. Doc(util::MakeString((NSString *)jsonDoc[@"key"]), version.longLongValue, std::move(data));
  289. if ([options[@"hasLocalMutations"] boolValue] == YES) {
  290. doc.SetHasLocalMutations();
  291. } else if ([options[@"hasCommittedMutations"] boolValue] == YES) {
  292. doc.SetHasCommittedMutations();
  293. }
  294. return DocumentViewChange{std::move(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. MutableDocument doc;
  385. if (value) {
  386. doc = MutableDocument::FoundDocument(key, version, *std::move(value));
  387. } else {
  388. doc = MutableDocument::NoDocument(key, version);
  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, Message<google_firestore_v1_ArrayValue>{});
  441. std::vector<MutationResult> mutationResults;
  442. mutationResults.emplace_back(std::move(mutationResult));
  443. [self.driver receiveWriteAckWithVersion:version mutationResults:std::move(mutationResults)];
  444. }
  445. - (void)doFailWrite:(NSDictionary *)spec {
  446. NSDictionary *errorSpec = spec[@"error"];
  447. NSNumber *keepInQueue = spec[@"keepInQueue"];
  448. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  449. [self.driver receiveWriteError:code userInfo:errorSpec keepInQueue:keepInQueue.boolValue];
  450. }
  451. - (void)doDrainQueue {
  452. [self.driver drainQueue];
  453. }
  454. - (void)doRunTimer:(NSString *)timer {
  455. TimerId timerID;
  456. if ([timer isEqualToString:@"all"]) {
  457. timerID = TimerId::All;
  458. } else if ([timer isEqualToString:@"listen_stream_idle"]) {
  459. timerID = TimerId::ListenStreamIdle;
  460. } else if ([timer isEqualToString:@"listen_stream_connection_backoff"]) {
  461. timerID = TimerId::ListenStreamConnectionBackoff;
  462. } else if ([timer isEqualToString:@"write_stream_idle"]) {
  463. timerID = TimerId::WriteStreamIdle;
  464. } else if ([timer isEqualToString:@"write_stream_connection_backoff"]) {
  465. timerID = TimerId::WriteStreamConnectionBackoff;
  466. } else if ([timer isEqualToString:@"online_state_timeout"]) {
  467. timerID = TimerId::OnlineStateTimeout;
  468. } else {
  469. HARD_FAIL("runTimer spec step specified unknown timer: %s", timer);
  470. }
  471. [self.driver runTimer:timerID];
  472. }
  473. - (void)doDisableNetwork {
  474. _networkEnabled = NO;
  475. [self.driver disableNetwork];
  476. }
  477. - (void)doEnableNetwork {
  478. _networkEnabled = YES;
  479. [self.driver enableNetwork];
  480. }
  481. - (void)doChangeUser:(nullable id)UID {
  482. if ([UID isEqual:[NSNull null]]) {
  483. UID = nil;
  484. }
  485. [self.driver changeUser:User::FromUid(UID)];
  486. }
  487. - (void)doRestart {
  488. // Any outstanding user writes should be automatically re-sent, so we want to preserve them
  489. // when re-creating the driver.
  490. FSTOutstandingWriteQueues outstandingWrites = self.driver.outstandingWrites;
  491. User currentUser = self.driver.currentUser;
  492. [self.driver shutdown];
  493. std::unique_ptr<Persistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  494. self.driver =
  495. [[FSTSyncEngineTestDriver alloc] initWithPersistence:std::move(persistence)
  496. initialUser:currentUser
  497. outstandingWrites:outstandingWrites
  498. maxConcurrentLimboResolutions:_maxConcurrentLimboResolutions];
  499. [self.driver start];
  500. }
  501. - (void)doStep:(NSDictionary *)step {
  502. NSNumber *clientIndex = step[@"clientIndex"];
  503. XCTAssertNil(clientIndex, @"The iOS client does not support switching clients");
  504. if (step[@"userListen"]) {
  505. [self doListen:step[@"userListen"]];
  506. } else if (step[@"userUnlisten"]) {
  507. [self doUnlisten:step[@"userUnlisten"]];
  508. } else if (step[@"userSet"]) {
  509. [self doSet:step[@"userSet"]];
  510. } else if (step[@"userPatch"]) {
  511. [self doPatch:step[@"userPatch"]];
  512. } else if (step[@"userDelete"]) {
  513. [self doDelete:step[@"userDelete"]];
  514. } else if (step[@"addSnapshotsInSyncListener"]) {
  515. [self doAddSnapshotsInSyncListener];
  516. } else if (step[@"removeSnapshotsInSyncListener"]) {
  517. [self doRemoveSnapshotsInSyncListener];
  518. } else if (step[@"drainQueue"]) {
  519. [self doDrainQueue];
  520. } else if (step[@"loadBundle"]) {
  521. [self doLoadBundle:step[@"loadBundle"]];
  522. } else if (step[@"watchAck"]) {
  523. [self doWatchAck:step[@"watchAck"]];
  524. } else if (step[@"watchCurrent"]) {
  525. [self doWatchCurrent:step[@"watchCurrent"]];
  526. } else if (step[@"watchRemove"]) {
  527. [self doWatchRemove:step[@"watchRemove"]];
  528. } else if (step[@"watchEntity"]) {
  529. [self doWatchEntity:step[@"watchEntity"]];
  530. } else if (step[@"watchFilter"]) {
  531. [self doWatchFilter:step[@"watchFilter"]];
  532. } else if (step[@"watchReset"]) {
  533. [self doWatchReset:step[@"watchReset"]];
  534. } else if (step[@"watchSnapshot"]) {
  535. [self doWatchSnapshot:step[@"watchSnapshot"]];
  536. } else if (step[@"watchStreamClose"]) {
  537. [self doWatchStreamClose:step[@"watchStreamClose"]];
  538. } else if (step[@"watchProto"]) {
  539. // watchProto isn't yet used, and it's unclear how to create arbitrary protos from JSON.
  540. HARD_FAIL("watchProto is not yet supported.");
  541. } else if (step[@"writeAck"]) {
  542. [self doWriteAck:step[@"writeAck"]];
  543. } else if (step[@"failWrite"]) {
  544. [self doFailWrite:step[@"failWrite"]];
  545. } else if (step[@"waitForPendingWrites"]) {
  546. [self doWaitForPendingWrites];
  547. } else if (step[@"runTimer"]) {
  548. [self doRunTimer:step[@"runTimer"]];
  549. } else if (step[@"enableNetwork"]) {
  550. if ([step[@"enableNetwork"] boolValue]) {
  551. [self doEnableNetwork];
  552. } else {
  553. [self doDisableNetwork];
  554. }
  555. } else if (step[@"changeUser"]) {
  556. [self doChangeUser:step[@"changeUser"]];
  557. } else if (step[@"restart"]) {
  558. [self doRestart];
  559. } else if (step[@"applyClientState"]) {
  560. XCTFail(@"'applyClientState' is not supported on iOS and should only be used in multi-client "
  561. @"tests");
  562. } else {
  563. XCTFail(@"Unknown step: %@", step);
  564. }
  565. }
  566. - (void)validateEvent:(FSTQueryEvent *)actual matches:(NSDictionary *)expected {
  567. Query expectedQuery = [self parseQuery:expected[@"query"]];
  568. XCTAssertEqual(actual.query, expectedQuery);
  569. if ([expected[@"errorCode"] integerValue] != 0) {
  570. XCTAssertNotNil(actual.error);
  571. XCTAssertEqual(actual.error.code, [expected[@"errorCode"] integerValue]);
  572. } else {
  573. std::vector<DocumentViewChange> expectedChanges;
  574. NSMutableArray *removed = expected[@"removed"];
  575. for (NSDictionary *changeSpec in removed) {
  576. expectedChanges.push_back([self parseChange:changeSpec
  577. ofType:DocumentViewChange::Type::Removed]);
  578. }
  579. NSMutableArray *added = expected[@"added"];
  580. for (NSDictionary *changeSpec in added) {
  581. expectedChanges.push_back([self parseChange:changeSpec
  582. ofType:DocumentViewChange::Type::Added]);
  583. }
  584. NSMutableArray *modified = expected[@"modified"];
  585. for (NSDictionary *changeSpec in modified) {
  586. expectedChanges.push_back([self parseChange:changeSpec
  587. ofType:DocumentViewChange::Type::Modified]);
  588. }
  589. NSMutableArray *metadata = expected[@"metadata"];
  590. for (NSDictionary *changeSpec in metadata) {
  591. expectedChanges.push_back([self parseChange:changeSpec
  592. ofType:DocumentViewChange::Type::Metadata]);
  593. }
  594. XCTAssertEqual(actual.viewSnapshot.value().document_changes().size(), expectedChanges.size());
  595. for (size_t i = 0; i != expectedChanges.size(); ++i) {
  596. XCTAssertTrue((actual.viewSnapshot.value().document_changes()[i] == expectedChanges[i]));
  597. }
  598. BOOL expectedHasPendingWrites =
  599. expected[@"hasPendingWrites"] ? [expected[@"hasPendingWrites"] boolValue] : NO;
  600. BOOL expectedIsFromCache = expected[@"fromCache"] ? [expected[@"fromCache"] boolValue] : NO;
  601. XCTAssertEqual(actual.viewSnapshot.value().has_pending_writes(), expectedHasPendingWrites,
  602. @"hasPendingWrites");
  603. XCTAssertEqual(actual.viewSnapshot.value().from_cache(), expectedIsFromCache, @"isFromCache");
  604. }
  605. }
  606. - (void)validateExpectedSnapshotEvents:(NSArray *_Nullable)expectedEvents {
  607. NSArray<FSTQueryEvent *> *events = self.driver.capturedEventsSinceLastCall;
  608. if (!expectedEvents) {
  609. XCTAssertEqual(events.count, 0u);
  610. for (FSTQueryEvent *event in events) {
  611. XCTFail(@"Unexpected event: %@", event);
  612. }
  613. return;
  614. }
  615. XCTAssertEqual(events.count, expectedEvents.count);
  616. events =
  617. [events sortedArrayUsingComparator:^NSComparisonResult(FSTQueryEvent *q1, FSTQueryEvent *q2) {
  618. return util::WrapCompare(q1.query.CanonicalId(), q2.query.CanonicalId());
  619. }];
  620. expectedEvents = [expectedEvents
  621. sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
  622. Query leftQuery = [self parseQuery:left[@"query"]];
  623. Query rightQuery = [self parseQuery:right[@"query"]];
  624. return util::WrapCompare(leftQuery.CanonicalId(), rightQuery.CanonicalId());
  625. }];
  626. NSUInteger i = 0;
  627. for (; i < expectedEvents.count && i < events.count; ++i) {
  628. [self validateEvent:events[i] matches:expectedEvents[i]];
  629. }
  630. for (; i < expectedEvents.count; ++i) {
  631. XCTFail(@"Missing event: %@", expectedEvents[i]);
  632. }
  633. for (; i < events.count; ++i) {
  634. XCTFail(@"Unexpected event: %@", events[i]);
  635. }
  636. }
  637. - (void)validateExpectedState:(nullable NSDictionary *)expectedState {
  638. if (expectedState) {
  639. if (expectedState[@"numOutstandingWrites"]) {
  640. XCTAssertEqual([self.driver sentWritesCount],
  641. [expectedState[@"numOutstandingWrites"] intValue]);
  642. }
  643. if (expectedState[@"writeStreamRequestCount"]) {
  644. XCTAssertEqual([self.driver writeStreamRequestCount],
  645. [expectedState[@"writeStreamRequestCount"] intValue]);
  646. }
  647. if (expectedState[@"watchStreamRequestCount"]) {
  648. XCTAssertEqual([self.driver watchStreamRequestCount],
  649. [expectedState[@"watchStreamRequestCount"] intValue]);
  650. }
  651. if (expectedState[@"activeLimboDocs"]) {
  652. DocumentKeySet expectedActiveLimboDocuments;
  653. NSArray *docNames = expectedState[@"activeLimboDocs"];
  654. for (NSString *name in docNames) {
  655. expectedActiveLimboDocuments = expectedActiveLimboDocuments.insert(FSTTestDocKey(name));
  656. }
  657. // Update the expected active limbo documents
  658. [self.driver setExpectedActiveLimboDocuments:std::move(expectedActiveLimboDocuments)];
  659. }
  660. if (expectedState[@"enqueuedLimboDocs"]) {
  661. DocumentKeySet expectedEnqueuedLimboDocuments;
  662. NSArray *docNames = expectedState[@"enqueuedLimboDocs"];
  663. for (NSString *name in docNames) {
  664. expectedEnqueuedLimboDocuments = expectedEnqueuedLimboDocuments.insert(FSTTestDocKey(name));
  665. }
  666. // Update the expected enqueued limbo documents
  667. [self.driver setExpectedEnqueuedLimboDocuments:std::move(expectedEnqueuedLimboDocuments)];
  668. }
  669. if (expectedState[@"activeTargets"]) {
  670. __block ActiveTargetMap expectedActiveTargets;
  671. [expectedState[@"activeTargets"]
  672. enumerateKeysAndObjectsUsingBlock:^(NSString *targetIDString, NSDictionary *queryData,
  673. BOOL *) {
  674. TargetId targetID = [targetIDString intValue];
  675. NSArray *queriesJson = queryData[@"queries"];
  676. std::vector<TargetData> queries;
  677. for (id queryJson in queriesJson) {
  678. Query query = [self parseQuery:queryJson];
  679. // TODO(mcg): populate the purpose of the target once it's possible to encode that in
  680. // the spec tests. For now, hard-code that it's a listen despite the fact that it's
  681. // not always the right value.
  682. TargetData target_data(query.ToTarget(), targetID, 0, QueryPurpose::Listen);
  683. if ([queryData objectForKey:@"resumeToken"] != nil) {
  684. target_data = target_data.WithResumeToken(
  685. MakeResumeToken(queryData[@"resumeToken"]), SnapshotVersion::None());
  686. } else {
  687. target_data = target_data.WithResumeToken(
  688. ByteString(), [self parseVersion:queryData[@"readTime"]]);
  689. }
  690. queries.push_back(std::move(target_data));
  691. }
  692. expectedActiveTargets[targetID] = std::move(queries);
  693. }];
  694. [self.driver setExpectedActiveTargets:std::move(expectedActiveTargets)];
  695. }
  696. }
  697. // Always validate the we received the expected number of callbacks.
  698. [self validateUserCallbacks:expectedState];
  699. // Always validate that the expected limbo docs match the actual limbo docs.
  700. [self validateActiveLimboDocuments];
  701. [self validateEnqueuedLimboDocuments];
  702. // Always validate that the expected active targets match the actual active targets.
  703. [self validateActiveTargets];
  704. }
  705. - (void)validateWaitForPendingWritesEvents:(int)expectedWaitForPendingWritesEvents {
  706. XCTAssertEqual(expectedWaitForPendingWritesEvents, [self.driver waitForPendingWritesEvents]);
  707. [self.driver resetWaitForPendingWritesEvents];
  708. }
  709. - (void)validateSnapshotsInSyncEvents:(int)expectedSnapshotInSyncEvents {
  710. XCTAssertEqual(expectedSnapshotInSyncEvents, [self.driver snapshotsInSyncEvents]);
  711. [self.driver resetSnapshotsInSyncEvents];
  712. }
  713. - (void)validateUserCallbacks:(nullable NSDictionary *)expected {
  714. NSDictionary *expectedCallbacks = expected[@"userCallbacks"];
  715. NSArray<NSString *> *actualAcknowledgedDocs =
  716. [self.driver capturedAcknowledgedWritesSinceLastCall];
  717. NSArray<NSString *> *actualRejectedDocs = [self.driver capturedRejectedWritesSinceLastCall];
  718. if (expectedCallbacks) {
  719. XCTAssertTrue([actualAcknowledgedDocs isEqualToArray:expectedCallbacks[@"acknowledgedDocs"]]);
  720. XCTAssertTrue([actualRejectedDocs isEqualToArray:expectedCallbacks[@"rejectedDocs"]]);
  721. } else {
  722. XCTAssertEqual([actualAcknowledgedDocs count], 0u);
  723. XCTAssertEqual([actualRejectedDocs count], 0u);
  724. }
  725. }
  726. - (void)validateActiveLimboDocuments {
  727. // Make a copy so it can modified while checking against the expected limbo docs.
  728. std::map<DocumentKey, TargetId> actualLimboDocs = self.driver.activeLimboDocumentResolutions;
  729. // Validate that each active limbo doc has an expected active target
  730. for (const auto &kv : actualLimboDocs) {
  731. const auto &expected = [self.driver expectedActiveTargets];
  732. XCTAssertTrue(expected.find(kv.second) != expected.end(),
  733. @"Found limbo doc %s, but its target ID %d was not in the "
  734. @"set of expected active target IDs %@",
  735. kv.first.ToString().c_str(), kv.second, ToTargetIdListString(expected));
  736. }
  737. for (const DocumentKey &expectedLimboDoc : self.driver.expectedActiveLimboDocuments) {
  738. XCTAssert(actualLimboDocs.find(expectedLimboDoc) != actualLimboDocs.end(),
  739. @"Expected doc to be in limbo, but was not: %s", expectedLimboDoc.ToString().c_str());
  740. actualLimboDocs.erase(expectedLimboDoc);
  741. }
  742. XCTAssertTrue(actualLimboDocs.empty(), @"Unexpected active docs in limbo: %@",
  743. ToDocumentListString(actualLimboDocs));
  744. }
  745. - (void)validateEnqueuedLimboDocuments {
  746. std::set<DocumentKey> actualLimboDocs;
  747. for (const auto &key : self.driver.enqueuedLimboDocumentResolutions) {
  748. actualLimboDocs.insert(key);
  749. }
  750. std::set<DocumentKey> expectedLimboDocs;
  751. for (const auto &key : self.driver.expectedEnqueuedLimboDocuments) {
  752. expectedLimboDocs.insert(key);
  753. }
  754. for (const auto &key : actualLimboDocs) {
  755. XCTAssertTrue(expectedLimboDocs.find(key) != expectedLimboDocs.end(),
  756. @"Found enqueued limbo doc %s, but it was not in the set of "
  757. @"expected enqueued limbo documents (%@)",
  758. key.ToString().c_str(), ToDocumentListString(expectedLimboDocs));
  759. }
  760. for (const auto &key : expectedLimboDocs) {
  761. XCTAssertTrue(actualLimboDocs.find(key) != actualLimboDocs.end(),
  762. @"Expected doc %s to be enqueued for limbo resolution, "
  763. @"but it was not in the queue (%@)",
  764. key.ToString().c_str(), ToDocumentListString(actualLimboDocs));
  765. }
  766. }
  767. - (void)validateActiveTargets {
  768. if (!_networkEnabled) {
  769. return;
  770. }
  771. // Create a copy so we can modify it below
  772. std::unordered_map<TargetId, TargetData> actualTargets = [self.driver activeTargets];
  773. for (const auto &kv : [self.driver expectedActiveTargets]) {
  774. TargetId targetID = kv.first;
  775. const std::vector<TargetData> &queries = kv.second;
  776. const TargetData &targetData = queries[0];
  777. auto found = actualTargets.find(targetID);
  778. XCTAssertNotEqual(found, actualTargets.end(), @"Expected active target not found: %s",
  779. targetData.ToString().c_str());
  780. // TODO(mcg): validate the purpose of the target once it's possible to encode that in the
  781. // spec tests. For now, only validate properties that can be validated.
  782. // XCTAssertEqualObjects(actualTargets[targetID], TargetData);
  783. const TargetData &actual = found->second;
  784. XCTAssertEqual(actual.target(), targetData.target());
  785. XCTAssertEqual(actual.target_id(), targetData.target_id());
  786. XCTAssertEqual(actual.snapshot_version(), targetData.snapshot_version());
  787. XCTAssertEqual(actual.resume_token(), targetData.resume_token());
  788. actualTargets.erase(targetID);
  789. }
  790. XCTAssertTrue(actualTargets.empty(), "Unexpected active targets: %s",
  791. util::ToString(actualTargets).c_str());
  792. }
  793. - (void)runSpecTestSteps:(NSArray *)steps config:(NSDictionary *)config {
  794. @autoreleasepool {
  795. @try {
  796. [self setUpForSpecWithConfig:config];
  797. for (NSDictionary *step in steps) {
  798. LOG_DEBUG("Doing step %s", step);
  799. [self doStep:step];
  800. [self validateExpectedSnapshotEvents:step[@"expectedSnapshotEvents"]];
  801. [self validateExpectedState:step[@"expectedState"]];
  802. int expectedSnapshotsInSyncEvents = [step[@"expectedSnapshotsInSyncEvents"] intValue];
  803. [self validateSnapshotsInSyncEvents:expectedSnapshotsInSyncEvents];
  804. int expectedWaitForPendingWritesEvents =
  805. [step[@"expectedWaitForPendingWritesEvents"] intValue];
  806. [self validateWaitForPendingWritesEvents:expectedWaitForPendingWritesEvents];
  807. }
  808. [self.driver validateUsage];
  809. } @finally {
  810. // Ensure that the driver is torn down even if the test is failing due to a thrown exception
  811. // so that any resources held by the driver are released. This is important when the driver is
  812. // backed by LevelDB because LevelDB locks its database. If -tearDownForSpec were not called
  813. // after an exception then subsequent attempts to open the LevelDB will fail, making it harder
  814. // to zero in on the spec tests as a culprit.
  815. [self tearDownForSpec];
  816. }
  817. }
  818. }
  819. #pragma mark - The actual test methods.
  820. - (void)testSpecTests {
  821. if ([self isTestBaseClass]) return;
  822. // Enumerate the .json files containing the spec tests.
  823. NSMutableArray<NSString *> *specFiles = [NSMutableArray array];
  824. NSMutableArray<NSDictionary *> *parsedSpecs = [NSMutableArray array];
  825. BOOL exclusiveMode = NO;
  826. // TODO(wilhuff): Fix this when running spec tests using a real device
  827. auto source_file = Path::FromUtf8(__FILE__);
  828. Path json_ext = Path::FromUtf8(".json");
  829. auto spec_dir = source_file.Dirname();
  830. auto json_dir = spec_dir.AppendUtf8("json");
  831. auto iter = util::DirectoryIterator::Create(json_dir);
  832. for (; iter->Valid(); iter->Next()) {
  833. Path entry = iter->file();
  834. if (!entry.HasExtension(json_ext)) {
  835. continue;
  836. }
  837. // Read and parse the JSON from the file.
  838. NSString *path = entry.ToNSString();
  839. NSData *json = [NSData dataWithContentsOfFile:path];
  840. XCTAssertNotNil(json);
  841. NSError *error = nil;
  842. id _Nullable parsed = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
  843. XCTAssertNil(error, @"%@", error);
  844. XCTAssertTrue([parsed isKindOfClass:[NSDictionary class]]);
  845. NSDictionary *testDict = (NSDictionary *)parsed;
  846. exclusiveMode = exclusiveMode || [self anyTestsAreMarkedExclusive:testDict];
  847. [specFiles addObject:entry.Basename().ToNSString()];
  848. [parsedSpecs addObject:testDict];
  849. }
  850. NSString *testNameFilterFromEnv = NSProcessInfo.processInfo.environment[kTestFilterEnvKey];
  851. NSRegularExpression *testNameFilter;
  852. if (testNameFilterFromEnv.length == 0) {
  853. testNameFilter = nil;
  854. } else {
  855. exclusiveMode = YES;
  856. NSError *error;
  857. testNameFilter =
  858. [NSRegularExpression regularExpressionWithPattern:testNameFilterFromEnv
  859. options:NSRegularExpressionAnchorsMatchLines
  860. error:&error];
  861. XCTAssertNotNil(testNameFilter, @"Invalid regular expression: %@ (%@)", testNameFilterFromEnv,
  862. error);
  863. }
  864. // Now iterate over them and run them.
  865. __block int testPassCount = 0;
  866. __block int testSkipCount = 0;
  867. __block bool ranAtLeastOneTest = NO;
  868. for (NSUInteger i = 0; i < specFiles.count; i++) {
  869. NSLog(@"Spec test file: %@", specFiles[i]);
  870. // Iterate over the tests in the file and run them.
  871. [parsedSpecs[i] enumerateKeysAndObjectsUsingBlock:^(id, id obj, BOOL *) {
  872. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  873. NSDictionary *testDescription = (NSDictionary *)obj;
  874. NSString *describeName = testDescription[@"describeName"];
  875. NSString *itName = testDescription[@"itName"];
  876. NSString *name = [NSString stringWithFormat:@"%@ %@", describeName, itName];
  877. NSDictionary *config = testDescription[@"config"];
  878. NSArray *steps = testDescription[@"steps"];
  879. NSArray<NSString *> *tags = testDescription[@"tags"];
  880. BOOL runTest;
  881. if (![self shouldRunWithTags:tags]) {
  882. runTest = NO;
  883. } else if (!exclusiveMode) {
  884. runTest = YES;
  885. } else if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  886. runTest = YES;
  887. } else if (testNameFilter != nil) {
  888. NSRange testNameFilterMatchRange =
  889. [testNameFilter rangeOfFirstMatchInString:name
  890. options:0
  891. range:NSMakeRange(0, [name length])];
  892. runTest = !NSEqualRanges(testNameFilterMatchRange, NSMakeRange(NSNotFound, 0));
  893. } else {
  894. runTest = NO;
  895. }
  896. if (runTest) {
  897. NSLog(@" Spec test: %@", name);
  898. [self runSpecTestSteps:steps config:config];
  899. ranAtLeastOneTest = YES;
  900. ++testPassCount;
  901. } else {
  902. ++testSkipCount;
  903. NSLog(@" [SKIPPED] Spec test: %@", name);
  904. NSString *comment = testDescription[@"comment"];
  905. if (comment) {
  906. NSLog(@" %@", comment);
  907. }
  908. }
  909. }];
  910. }
  911. NSLog(@"%@ completed; pass=%d skip=%d", NSStringFromClass([self class]), testPassCount,
  912. testSkipCount);
  913. XCTAssertTrue(ranAtLeastOneTest);
  914. }
  915. - (BOOL)anyTestsAreMarkedExclusive:(NSDictionary *)tests {
  916. __block BOOL found = NO;
  917. [tests enumerateKeysAndObjectsUsingBlock:^(id, id obj, BOOL *stop) {
  918. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  919. NSDictionary *testDescription = (NSDictionary *)obj;
  920. NSArray<NSString *> *tags = testDescription[@"tags"];
  921. if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  922. found = YES;
  923. *stop = YES;
  924. }
  925. }];
  926. return found;
  927. }
  928. @end
  929. NS_ASSUME_NONNULL_END