FSTSpecTests.mm 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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. QueryPurpose purpose = QueryPurpose::Listen;
  684. if ([queryData objectForKey:@"targetPurpose"] != nil) {
  685. purpose = static_cast<QueryPurpose>([queryData[@"targetPurpose"] intValue]);
  686. }
  687. TargetData target_data(query.ToTarget(), targetID, 0, purpose);
  688. if ([queryData objectForKey:@"resumeToken"] != nil) {
  689. target_data = target_data.WithResumeToken(
  690. MakeResumeToken(queryData[@"resumeToken"]), SnapshotVersion::None());
  691. } else {
  692. target_data = target_data.WithResumeToken(
  693. ByteString(), [self parseVersion:queryData[@"readTime"]]);
  694. }
  695. queries.push_back(std::move(target_data));
  696. }
  697. expectedActiveTargets[targetID] = std::move(queries);
  698. }];
  699. [self.driver setExpectedActiveTargets:std::move(expectedActiveTargets)];
  700. }
  701. }
  702. // Always validate the we received the expected number of callbacks.
  703. [self validateUserCallbacks:expectedState];
  704. // Always validate that the expected limbo docs match the actual limbo docs.
  705. [self validateActiveLimboDocuments];
  706. [self validateEnqueuedLimboDocuments];
  707. // Always validate that the expected active targets match the actual active targets.
  708. [self validateActiveTargets];
  709. }
  710. - (void)validateWaitForPendingWritesEvents:(int)expectedWaitForPendingWritesEvents {
  711. XCTAssertEqual(expectedWaitForPendingWritesEvents, [self.driver waitForPendingWritesEvents]);
  712. [self.driver resetWaitForPendingWritesEvents];
  713. }
  714. - (void)validateSnapshotsInSyncEvents:(int)expectedSnapshotInSyncEvents {
  715. XCTAssertEqual(expectedSnapshotInSyncEvents, [self.driver snapshotsInSyncEvents]);
  716. [self.driver resetSnapshotsInSyncEvents];
  717. }
  718. - (void)validateUserCallbacks:(nullable NSDictionary *)expected {
  719. NSDictionary *expectedCallbacks = expected[@"userCallbacks"];
  720. NSArray<NSString *> *actualAcknowledgedDocs =
  721. [self.driver capturedAcknowledgedWritesSinceLastCall];
  722. NSArray<NSString *> *actualRejectedDocs = [self.driver capturedRejectedWritesSinceLastCall];
  723. if (expectedCallbacks) {
  724. XCTAssertTrue([actualAcknowledgedDocs isEqualToArray:expectedCallbacks[@"acknowledgedDocs"]]);
  725. XCTAssertTrue([actualRejectedDocs isEqualToArray:expectedCallbacks[@"rejectedDocs"]]);
  726. } else {
  727. XCTAssertEqual([actualAcknowledgedDocs count], 0u);
  728. XCTAssertEqual([actualRejectedDocs count], 0u);
  729. }
  730. }
  731. - (void)validateActiveLimboDocuments {
  732. // Make a copy so it can modified while checking against the expected limbo docs.
  733. std::map<DocumentKey, TargetId> actualLimboDocs = self.driver.activeLimboDocumentResolutions;
  734. // Validate that each active limbo doc has an expected active target
  735. for (const auto &kv : actualLimboDocs) {
  736. const auto &expected = [self.driver expectedActiveTargets];
  737. XCTAssertTrue(expected.find(kv.second) != expected.end(),
  738. @"Found limbo doc %s, but its target ID %d was not in the "
  739. @"set of expected active target IDs %@",
  740. kv.first.ToString().c_str(), kv.second, ToTargetIdListString(expected));
  741. }
  742. for (const DocumentKey &expectedLimboDoc : self.driver.expectedActiveLimboDocuments) {
  743. XCTAssert(actualLimboDocs.find(expectedLimboDoc) != actualLimboDocs.end(),
  744. @"Expected doc to be in limbo, but was not: %s", expectedLimboDoc.ToString().c_str());
  745. actualLimboDocs.erase(expectedLimboDoc);
  746. }
  747. XCTAssertTrue(actualLimboDocs.empty(), @"Unexpected active docs in limbo: %@",
  748. ToDocumentListString(actualLimboDocs));
  749. }
  750. - (void)validateEnqueuedLimboDocuments {
  751. std::set<DocumentKey> actualLimboDocs;
  752. for (const auto &key : self.driver.enqueuedLimboDocumentResolutions) {
  753. actualLimboDocs.insert(key);
  754. }
  755. std::set<DocumentKey> expectedLimboDocs;
  756. for (const auto &key : self.driver.expectedEnqueuedLimboDocuments) {
  757. expectedLimboDocs.insert(key);
  758. }
  759. for (const auto &key : actualLimboDocs) {
  760. XCTAssertTrue(expectedLimboDocs.find(key) != expectedLimboDocs.end(),
  761. @"Found enqueued limbo doc %s, but it was not in the set of "
  762. @"expected enqueued limbo documents (%@)",
  763. key.ToString().c_str(), ToDocumentListString(expectedLimboDocs));
  764. }
  765. for (const auto &key : expectedLimboDocs) {
  766. XCTAssertTrue(actualLimboDocs.find(key) != actualLimboDocs.end(),
  767. @"Expected doc %s to be enqueued for limbo resolution, "
  768. @"but it was not in the queue (%@)",
  769. key.ToString().c_str(), ToDocumentListString(actualLimboDocs));
  770. }
  771. }
  772. - (void)validateActiveTargets {
  773. if (!_networkEnabled) {
  774. return;
  775. }
  776. // Create a copy so we can modify it below
  777. std::unordered_map<TargetId, TargetData> actualTargets = [self.driver activeTargets];
  778. for (const auto &kv : [self.driver expectedActiveTargets]) {
  779. TargetId targetID = kv.first;
  780. const std::vector<TargetData> &queries = kv.second;
  781. const TargetData &targetData = queries[0];
  782. auto found = actualTargets.find(targetID);
  783. XCTAssertNotEqual(found, actualTargets.end(), @"Expected active target not found: %s",
  784. targetData.ToString().c_str());
  785. // TODO(Mila): Replace the XCTAssertEqual() checks on the individual properties of TargetData
  786. // below with the single assertEquals on the TargetData objects themselves if the sequenceNumber
  787. // is ever made to be consistent.
  788. // XCTAssertEqualObjects(actualTargets[targetID], TargetData);
  789. const TargetData &actual = found->second;
  790. XCTAssertEqual(actual.purpose(), targetData.purpose());
  791. XCTAssertEqual(actual.target(), targetData.target());
  792. XCTAssertEqual(actual.target_id(), targetData.target_id());
  793. XCTAssertEqual(actual.snapshot_version(), targetData.snapshot_version());
  794. XCTAssertEqual(actual.resume_token(), targetData.resume_token());
  795. actualTargets.erase(targetID);
  796. }
  797. XCTAssertTrue(actualTargets.empty(), "Unexpected active targets: %s",
  798. ToString(actualTargets).c_str());
  799. }
  800. - (void)runSpecTestSteps:(NSArray *)steps config:(NSDictionary *)config {
  801. @autoreleasepool {
  802. @try {
  803. [self setUpForSpecWithConfig:config];
  804. for (NSDictionary *step in steps) {
  805. LOG_DEBUG("Doing step %s", step);
  806. [self doStep:step];
  807. [self validateExpectedSnapshotEvents:step[@"expectedSnapshotEvents"]];
  808. [self validateExpectedState:step[@"expectedState"]];
  809. int expectedSnapshotsInSyncEvents = [step[@"expectedSnapshotsInSyncEvents"] intValue];
  810. [self validateSnapshotsInSyncEvents:expectedSnapshotsInSyncEvents];
  811. int expectedWaitForPendingWritesEvents =
  812. [step[@"expectedWaitForPendingWritesEvents"] intValue];
  813. [self validateWaitForPendingWritesEvents:expectedWaitForPendingWritesEvents];
  814. }
  815. [self.driver validateUsage];
  816. } @finally {
  817. // Ensure that the driver is torn down even if the test is failing due to a thrown exception
  818. // so that any resources held by the driver are released. This is important when the driver is
  819. // backed by LevelDB because LevelDB locks its database. If -tearDownForSpec were not called
  820. // after an exception then subsequent attempts to open the LevelDB will fail, making it harder
  821. // to zero in on the spec tests as a culprit.
  822. [self tearDownForSpec];
  823. }
  824. }
  825. }
  826. #pragma mark - The actual test methods.
  827. - (void)testSpecTests {
  828. if ([self isTestBaseClass]) return;
  829. // Enumerate the .json files containing the spec tests.
  830. NSMutableArray<NSString *> *specFiles = [NSMutableArray array];
  831. NSMutableArray<NSDictionary *> *parsedSpecs = [NSMutableArray array];
  832. BOOL exclusiveMode = NO;
  833. // TODO(wilhuff): Fix this when running spec tests using a real device
  834. auto source_file = Path::FromUtf8(__FILE__);
  835. Path json_ext = Path::FromUtf8(".json");
  836. auto spec_dir = source_file.Dirname();
  837. auto json_dir = spec_dir.AppendUtf8("json");
  838. auto iter = DirectoryIterator::Create(json_dir);
  839. for (; iter->Valid(); iter->Next()) {
  840. Path entry = iter->file();
  841. if (!entry.HasExtension(json_ext)) {
  842. continue;
  843. }
  844. // Read and parse the JSON from the file.
  845. NSString *path = entry.ToNSString();
  846. NSData *json = [NSData dataWithContentsOfFile:path];
  847. XCTAssertNotNil(json);
  848. NSError *error = nil;
  849. id _Nullable parsed = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
  850. XCTAssertNil(error, @"%@", error);
  851. XCTAssertTrue([parsed isKindOfClass:[NSDictionary class]]);
  852. NSDictionary *testDict = (NSDictionary *)parsed;
  853. exclusiveMode = exclusiveMode || [self anyTestsAreMarkedExclusive:testDict];
  854. [specFiles addObject:entry.Basename().ToNSString()];
  855. [parsedSpecs addObject:testDict];
  856. }
  857. NSString *testNameFilterFromEnv = NSProcessInfo.processInfo.environment[kTestFilterEnvKey];
  858. NSRegularExpression *testNameFilter;
  859. if (testNameFilterFromEnv.length == 0) {
  860. testNameFilter = nil;
  861. } else {
  862. exclusiveMode = YES;
  863. NSError *error;
  864. testNameFilter =
  865. [NSRegularExpression regularExpressionWithPattern:testNameFilterFromEnv
  866. options:NSRegularExpressionAnchorsMatchLines
  867. error:&error];
  868. XCTAssertNotNil(testNameFilter, @"Invalid regular expression: %@ (%@)", testNameFilterFromEnv,
  869. error);
  870. }
  871. // Now iterate over them and run them.
  872. __block int testPassCount = 0;
  873. __block int testSkipCount = 0;
  874. __block bool ranAtLeastOneTest = NO;
  875. for (NSUInteger i = 0; i < specFiles.count; i++) {
  876. NSLog(@"Spec test file: %@", specFiles[i]);
  877. // Iterate over the tests in the file and run them.
  878. [parsedSpecs[i] enumerateKeysAndObjectsUsingBlock:^(id, id obj, BOOL *) {
  879. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  880. NSDictionary *testDescription = (NSDictionary *)obj;
  881. NSString *describeName = testDescription[@"describeName"];
  882. NSString *itName = testDescription[@"itName"];
  883. NSString *name = [NSString stringWithFormat:@"%@ %@", describeName, itName];
  884. NSDictionary *config = testDescription[@"config"];
  885. NSArray *steps = testDescription[@"steps"];
  886. NSArray<NSString *> *tags = testDescription[@"tags"];
  887. BOOL runTest;
  888. if (![self shouldRunWithTags:tags]) {
  889. runTest = NO;
  890. } else if (!exclusiveMode) {
  891. runTest = YES;
  892. } else if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  893. runTest = YES;
  894. } else if (testNameFilter != nil) {
  895. NSRange testNameFilterMatchRange =
  896. [testNameFilter rangeOfFirstMatchInString:name
  897. options:0
  898. range:NSMakeRange(0, [name length])];
  899. runTest = !NSEqualRanges(testNameFilterMatchRange, NSMakeRange(NSNotFound, 0));
  900. } else {
  901. runTest = NO;
  902. }
  903. if (runTest) {
  904. NSLog(@" Spec test: %@", name);
  905. [self runSpecTestSteps:steps config:config];
  906. ranAtLeastOneTest = YES;
  907. ++testPassCount;
  908. } else {
  909. ++testSkipCount;
  910. NSLog(@" [SKIPPED] Spec test: %@", name);
  911. NSString *comment = testDescription[@"comment"];
  912. if (comment) {
  913. NSLog(@" %@", comment);
  914. }
  915. }
  916. }];
  917. }
  918. NSLog(@"%@ completed; pass=%d skip=%d", NSStringFromClass([self class]), testPassCount,
  919. testSkipCount);
  920. XCTAssertTrue(ranAtLeastOneTest);
  921. }
  922. - (BOOL)anyTestsAreMarkedExclusive:(NSDictionary *)tests {
  923. __block BOOL found = NO;
  924. [tests enumerateKeysAndObjectsUsingBlock:^(id, id obj, BOOL *stop) {
  925. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  926. NSDictionary *testDescription = (NSDictionary *)obj;
  927. NSArray<NSString *> *tags = testDescription[@"tags"];
  928. if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  929. found = YES;
  930. *stop = YES;
  931. }
  932. }];
  933. return found;
  934. }
  935. @end
  936. NS_ASSUME_NONNULL_END