FSTSpecTests.mm 33 KB

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