FSTSpecTests.mm 32 KB

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