FSTSpecTests.mm 34 KB

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