FSTSpecTests.mm 42 KB

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