FSTSpecTests.mm 38 KB

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