FSTSpecTests.mm 32 KB

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