FSTSpecTests.mm 31 KB

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