FSTSpecTests.mm 33 KB

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