FSTSpecTests.mm 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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 kEagerGC = @"eager-gc";
  66. NSString *const kDurablePersistence = @"durable-persistence";
  67. static NSString *Describe(NSData *data) {
  68. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  69. }
  70. @interface FSTSpecTests ()
  71. @property(nonatomic, strong) FSTSyncEngineTestDriver *driver;
  72. @end
  73. @implementation FSTSpecTests {
  74. BOOL _gcEnabled;
  75. }
  76. - (id<FSTPersistence>)persistenceWithGCEnabled:(BOOL)GCEnabled {
  77. @throw FSTAbstractMethodException(); // NOLINT
  78. }
  79. - (BOOL)shouldRunWithTags:(NSArray<NSString *> *)tags {
  80. if ([tags containsObject:kNoIOSTag]) {
  81. return NO;
  82. } else if ([tags containsObject:kMultiClientTag]) {
  83. return NO;
  84. } else if (!kRunBenchmarkTests && [tags containsObject:kBenchmarkTag]) {
  85. return NO;
  86. }
  87. return YES;
  88. }
  89. - (void)setUpForSpecWithConfig:(NSDictionary *)config {
  90. // Store GCEnabled so we can re-use it in doRestart.
  91. NSNumber *GCEnabled = config[@"useGarbageCollection"];
  92. _gcEnabled = [GCEnabled boolValue];
  93. NSNumber *numClients = config[@"numClients"];
  94. if (numClients) {
  95. XCTAssertEqualObjects(numClients, @1, @"The iOS client does not support multi-client tests");
  96. }
  97. id<FSTPersistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  98. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:persistence];
  99. [self.driver start];
  100. }
  101. - (void)tearDownForSpec {
  102. [self.driver shutdown];
  103. }
  104. /**
  105. * Xcode will run tests from any class that extends XCTestCase, but this doesn't work for
  106. * FSTSpecTests since it is incomplete without the implementations supplied by its subclasses.
  107. */
  108. - (BOOL)isTestBaseClass {
  109. return [self class] == [FSTSpecTests class];
  110. }
  111. #pragma mark - Methods for constructing objects from specs.
  112. - (nullable FSTQuery *)parseQuery:(id)querySpec {
  113. if ([querySpec isKindOfClass:[NSString class]]) {
  114. return FSTTestQuery(util::MakeString((NSString *)querySpec));
  115. } else if ([querySpec isKindOfClass:[NSDictionary class]]) {
  116. NSDictionary *queryDict = (NSDictionary *)querySpec;
  117. NSString *path = queryDict[@"path"];
  118. __block FSTQuery *query = FSTTestQuery(util::MakeString(path));
  119. if (queryDict[@"limit"]) {
  120. NSNumber *limit = queryDict[@"limit"];
  121. query = [query queryBySettingLimit:limit.integerValue];
  122. }
  123. if (queryDict[@"filters"]) {
  124. NSArray *filters = queryDict[@"filters"];
  125. [filters enumerateObjectsUsingBlock:^(NSArray *_Nonnull filter, NSUInteger idx,
  126. BOOL *_Nonnull stop) {
  127. query = [query
  128. queryByAddingFilter:FSTTestFilter(util::MakeString(filter[0]), filter[1], filter[2])];
  129. }];
  130. }
  131. if (queryDict[@"orderBys"]) {
  132. NSArray *orderBys = queryDict[@"orderBys"];
  133. [orderBys enumerateObjectsUsingBlock:^(NSArray *_Nonnull orderBy, NSUInteger idx,
  134. BOOL *_Nonnull stop) {
  135. query =
  136. [query queryByAddingSortOrder:FSTTestOrderBy(util::MakeString(orderBy[0]), orderBy[1])];
  137. }];
  138. }
  139. return query;
  140. } else {
  141. XCTFail(@"Invalid query: %@", querySpec);
  142. return nil;
  143. }
  144. }
  145. - (SnapshotVersion)parseVersion:(NSNumber *_Nullable)version {
  146. return testutil::Version(version.longLongValue);
  147. }
  148. - (FSTDocumentViewChange *)parseChange:(NSArray *)change ofType:(FSTDocumentViewChangeType)type {
  149. BOOL hasMutations = NO;
  150. for (NSUInteger i = 3; i < change.count; ++i) {
  151. if ([change[i] isEqual:@"local"]) {
  152. hasMutations = YES;
  153. }
  154. }
  155. NSNumber *version = change[1];
  156. XCTAssert([change[0] isKindOfClass:[NSString class]]);
  157. FSTDocument *doc = FSTTestDoc(util::MakeString((NSString *)change[0]), version.longLongValue,
  158. change[2], hasMutations);
  159. return [FSTDocumentViewChange changeWithDocument:doc type:type];
  160. }
  161. #pragma mark - Methods for doing the steps of the spec test.
  162. - (void)doListen:(NSArray *)listenSpec {
  163. FSTQuery *query = [self parseQuery:listenSpec[1]];
  164. TargetId actualID = [self.driver addUserListenerWithQuery:query];
  165. TargetId expectedID = [listenSpec[0] intValue];
  166. XCTAssertEqual(actualID, expectedID, @"targetID assigned to listen");
  167. }
  168. - (void)doUnlisten:(NSArray *)unlistenSpec {
  169. FSTQuery *query = [self parseQuery:unlistenSpec[1]];
  170. [self.driver removeUserListenerWithQuery:query];
  171. }
  172. - (void)doSet:(NSArray *)setSpec {
  173. [self.driver writeUserMutation:FSTTestSetMutation(setSpec[0], setSpec[1])];
  174. }
  175. - (void)doPatch:(NSArray *)patchSpec {
  176. [self.driver
  177. writeUserMutation:FSTTestPatchMutation(util::MakeString(patchSpec[0]), patchSpec[1], {})];
  178. }
  179. - (void)doDelete:(NSString *)key {
  180. [self.driver writeUserMutation:FSTTestDeleteMutation(key)];
  181. }
  182. - (void)doWatchAck:(NSArray<NSNumber *> *)ackedTargets {
  183. FSTWatchTargetChange *change =
  184. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateAdded
  185. targetIDs:ackedTargets
  186. cause:nil];
  187. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  188. }
  189. - (void)doWatchCurrent:(NSArray<id> *)currentSpec {
  190. NSArray<NSNumber *> *currentTargets = currentSpec[0];
  191. NSData *resumeToken = [currentSpec[1] dataUsingEncoding:NSUTF8StringEncoding];
  192. FSTWatchTargetChange *change =
  193. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateCurrent
  194. targetIDs:currentTargets
  195. resumeToken:resumeToken];
  196. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  197. }
  198. - (void)doWatchRemove:(NSDictionary *)watchRemoveSpec {
  199. NSError *error = nil;
  200. NSDictionary *cause = watchRemoveSpec[@"cause"];
  201. if (cause) {
  202. int code = ((NSNumber *)cause[@"code"]).intValue;
  203. NSDictionary *userInfo = @{
  204. NSLocalizedDescriptionKey : @"Error from watchRemove.",
  205. };
  206. error = [NSError errorWithDomain:FIRFirestoreErrorDomain code:code userInfo:userInfo];
  207. }
  208. FSTWatchTargetChange *change =
  209. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateRemoved
  210. targetIDs:watchRemoveSpec[@"targetIds"]
  211. cause:error];
  212. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  213. // Unlike web, the FSTMockDatastore detects a watch removal with cause and will remove active
  214. // targets
  215. }
  216. - (void)doWatchEntity:(NSDictionary *)watchEntity {
  217. if (watchEntity[@"docs"]) {
  218. HARD_ASSERT(!watchEntity[@"doc"], "Exactly one of |doc| or |docs| needs to be set.");
  219. NSArray *docs = watchEntity[@"docs"];
  220. for (NSDictionary *doc in docs) {
  221. NSMutableDictionary *watchSpec = [NSMutableDictionary dictionary];
  222. watchSpec[@"doc"] = doc;
  223. if (watchEntity[@"targets"]) {
  224. watchSpec[@"targets"] = watchEntity[@"targets"];
  225. }
  226. if (watchEntity[@"removedTargets"]) {
  227. watchSpec[@"removedTargets"] = watchEntity[@"removedTargets"];
  228. }
  229. [self doWatchEntity:watchSpec];
  230. }
  231. } else if (watchEntity[@"doc"]) {
  232. NSArray *docSpec = watchEntity[@"doc"];
  233. FSTDocumentKey *key = FSTTestDocKey(docSpec[0]);
  234. FSTObjectValue *_Nullable value =
  235. [docSpec[2] isKindOfClass:[NSNull class]] ? nil : FSTTestObjectValue(docSpec[2]);
  236. SnapshotVersion version = [self parseVersion:docSpec[1]];
  237. FSTMaybeDocument *doc =
  238. value ? [FSTDocument documentWithData:value
  239. key:key
  240. version:std::move(version)
  241. hasLocalMutations:NO]
  242. : [FSTDeletedDocument documentWithKey:key version:std::move(version)];
  243. FSTWatchChange *change =
  244. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:watchEntity[@"targets"]
  245. removedTargetIDs:watchEntity[@"removedTargets"]
  246. documentKey:doc.key
  247. document:doc];
  248. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  249. } else if (watchEntity[@"key"]) {
  250. FSTDocumentKey *docKey = FSTTestDocKey(watchEntity[@"key"]);
  251. FSTWatchChange *change =
  252. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:@[]
  253. removedTargetIDs:watchEntity[@"removedTargets"]
  254. documentKey:docKey
  255. document:nil];
  256. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  257. } else {
  258. HARD_FAIL("Either key, doc or docs must be set.");
  259. }
  260. }
  261. - (void)doWatchFilter:(NSArray *)watchFilter {
  262. NSArray<NSNumber *> *targets = watchFilter[0];
  263. HARD_ASSERT(targets.count == 1, "ExistenceFilters currently support exactly one target only.");
  264. int keyCount = watchFilter.count == 0 ? 0 : (int)watchFilter.count - 1;
  265. // TODO(dimond): extend this with different existence filters over time.
  266. FSTExistenceFilter *filter = [FSTExistenceFilter filterWithCount:keyCount];
  267. FSTExistenceFilterWatchChange *change =
  268. [FSTExistenceFilterWatchChange changeWithFilter:filter targetID:targets[0].intValue];
  269. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  270. }
  271. - (void)doWatchReset:(NSArray<NSNumber *> *)watchReset {
  272. FSTWatchTargetChange *change =
  273. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateReset
  274. targetIDs:watchReset
  275. cause:nil];
  276. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  277. }
  278. - (void)doWatchSnapshot:(NSDictionary *)watchSnapshot {
  279. // The client will only respond to watchSnapshots if they are on a target change with an empty
  280. // set of target IDs.
  281. NSArray<NSNumber *> *targetIDs =
  282. watchSnapshot[@"targetIds"] ? watchSnapshot[@"targetIds"] : [NSArray array];
  283. NSData *resumeToken = [watchSnapshot[@"resumeToken"] dataUsingEncoding:NSUTF8StringEncoding];
  284. FSTWatchTargetChange *change =
  285. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateNoChange
  286. targetIDs:targetIDs
  287. resumeToken:resumeToken];
  288. [self.driver receiveWatchChange:change
  289. snapshotVersion:[self parseVersion:watchSnapshot[@"version"]]];
  290. }
  291. - (void)doWatchStreamClose:(NSDictionary *)closeSpec {
  292. NSDictionary *errorSpec = closeSpec[@"error"];
  293. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  294. NSNumber *runBackoffTimer = closeSpec[@"runBackoffTimer"];
  295. // TODO(b/72313632): Incorporate backoff in iOS Spec Tests.
  296. HARD_ASSERT(runBackoffTimer.boolValue, "iOS Spec Tests don't support backoff.");
  297. [self.driver receiveWatchStreamError:code userInfo:errorSpec];
  298. }
  299. - (void)doWriteAck:(NSDictionary *)spec {
  300. SnapshotVersion version = [self parseVersion:spec[@"version"]];
  301. NSNumber *keepInQueue = spec[@"keepInQueue"];
  302. XCTAssertTrue(keepInQueue == nil || keepInQueue.boolValue == NO,
  303. @"'keepInQueue=true' is not supported on iOS and should only be set in "
  304. @"multi-client tests");
  305. FSTMutationResult *mutationResult =
  306. [[FSTMutationResult alloc] initWithVersion:version transformResults:nil];
  307. [self.driver receiveWriteAckWithVersion:version mutationResults:@[ mutationResult ]];
  308. }
  309. - (void)doFailWrite:(NSDictionary *)spec {
  310. NSDictionary *errorSpec = spec[@"error"];
  311. NSNumber *keepInQueue = spec[@"keepInQueue"];
  312. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  313. [self.driver receiveWriteError:code userInfo:errorSpec keepInQueue:keepInQueue.boolValue];
  314. }
  315. - (void)doDrainQueue {
  316. [self.driver drainQueue];
  317. }
  318. - (void)doRunTimer:(NSString *)timer {
  319. FSTTimerID timerID;
  320. if ([timer isEqualToString:@"all"]) {
  321. timerID = FSTTimerIDAll;
  322. } else if ([timer isEqualToString:@"listen_stream_idle"]) {
  323. timerID = FSTTimerIDListenStreamIdle;
  324. } else if ([timer isEqualToString:@"listen_stream_connection_backoff"]) {
  325. timerID = FSTTimerIDListenStreamConnectionBackoff;
  326. } else if ([timer isEqualToString:@"write_stream_idle"]) {
  327. timerID = FSTTimerIDWriteStreamIdle;
  328. } else if ([timer isEqualToString:@"write_stream_connection_backoff"]) {
  329. timerID = FSTTimerIDWriteStreamConnectionBackoff;
  330. } else if ([timer isEqualToString:@"online_state_timeout"]) {
  331. timerID = FSTTimerIDOnlineStateTimeout;
  332. } else {
  333. HARD_FAIL("runTimer spec step specified unknown timer: %s", timer);
  334. }
  335. [self.driver runTimer:timerID];
  336. }
  337. - (void)doDisableNetwork {
  338. [self.driver disableNetwork];
  339. }
  340. - (void)doEnableNetwork {
  341. [self.driver enableNetwork];
  342. }
  343. - (void)doChangeUser:(nullable id)UID {
  344. if ([UID isEqual:[NSNull null]]) {
  345. UID = nil;
  346. }
  347. [self.driver changeUser:User::FromUid(UID)];
  348. }
  349. - (void)doRestart {
  350. // Any outstanding user writes should be automatically re-sent, so we want to preserve them
  351. // when re-creating the driver.
  352. FSTOutstandingWriteQueues outstandingWrites = self.driver.outstandingWrites;
  353. User currentUser = self.driver.currentUser;
  354. [self.driver shutdown];
  355. id<FSTPersistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  356. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:persistence
  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. TargetId 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(Describe(actual.resumeToken), Describe(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