FSTSpecTests.mm 32 KB

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