FSTSpecTests.mm 42 KB

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