FSTSpecTests.mm 43 KB

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