FSTSpecTests.mm 35 KB

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