FSTSpecTests.mm 32 KB

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