FSTSpecTests.mm 33 KB

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