FSTSpecTests.mm 43 KB

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