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/FSTFieldValue.h"
  26. #import "Firestore/Source/Model/FSTMutation.h"
  27. #import "Firestore/Source/Remote/FSTWatchChange.h"
  28. #import "Firestore/Source/Util/FSTClasses.h"
  29. #import "Firestore/Example/Tests/Remote/FSTWatchChange+Testing.h"
  30. #import "Firestore/Example/Tests/SpecTests/FSTSyncEngineTestDriver.h"
  31. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  32. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  33. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  34. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  35. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  36. #include "Firestore/core/src/firebase/firestore/remote/existence_filter.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::DocumentKeySet;
  47. using firebase::firestore::model::SnapshotVersion;
  48. using firebase::firestore::model::TargetId;
  49. using firebase::firestore::remote::ExistenceFilter;
  50. using firebase::firestore::util::TimerId;
  51. NS_ASSUME_NONNULL_BEGIN
  52. // Whether to run the benchmark spec tests.
  53. // TODO(mrschmidt): Make this configurable via the tests schema.
  54. static BOOL kRunBenchmarkTests = NO;
  55. // Disables all other tests; useful for debugging. Multiple tests can have this tag and they'll all
  56. // be run (but all others won't).
  57. static NSString *const kExclusiveTag = @"exclusive";
  58. // A tag for tests that should be excluded from execution (on iOS), useful to allow the platforms
  59. // to temporarily diverge.
  60. static NSString *const kNoIOSTag = @"no-ios";
  61. // A tag for tests that exercise the multi-client behavior of the Web client. These tests are
  62. // ignored on iOS.
  63. static NSString *const kMultiClientTag = @"multi-client";
  64. // A tag for tests that is assigned to the perf tests in "perf_spec.json". These tests are only run
  65. // if `kRunBenchmarkTests` is set to 'YES'.
  66. static NSString *const kBenchmarkTag = @"benchmark";
  67. NSString *const kEagerGC = @"eager-gc";
  68. NSString *const kDurablePersistence = @"durable-persistence";
  69. static NSString *Describe(NSData *data) {
  70. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  71. }
  72. @interface FSTSpecTests ()
  73. @property(nonatomic, strong) FSTSyncEngineTestDriver *driver;
  74. @end
  75. @implementation FSTSpecTests {
  76. BOOL _gcEnabled;
  77. BOOL _networkEnabled;
  78. }
  79. - (id<FSTPersistence>)persistenceWithGCEnabled:(BOOL)GCEnabled {
  80. @throw FSTAbstractMethodException(); // NOLINT
  81. }
  82. - (BOOL)shouldRunWithTags:(NSArray<NSString *> *)tags {
  83. if ([tags containsObject:kNoIOSTag]) {
  84. return NO;
  85. } else if ([tags containsObject:kMultiClientTag]) {
  86. return NO;
  87. } else if (!kRunBenchmarkTests && [tags containsObject:kBenchmarkTag]) {
  88. return NO;
  89. }
  90. return YES;
  91. }
  92. - (void)setUpForSpecWithConfig:(NSDictionary *)config {
  93. // Store GCEnabled so we can re-use it in doRestart.
  94. NSNumber *GCEnabled = config[@"useGarbageCollection"];
  95. _gcEnabled = [GCEnabled boolValue];
  96. NSNumber *numClients = config[@"numClients"];
  97. if (numClients) {
  98. XCTAssertEqualObjects(numClients, @1, @"The iOS client does not support multi-client tests");
  99. }
  100. id<FSTPersistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  101. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:persistence];
  102. [self.driver start];
  103. }
  104. - (void)tearDownForSpec {
  105. [self.driver shutdown];
  106. }
  107. /**
  108. * Xcode will run tests from any class that extends XCTestCase, but this doesn't work for
  109. * FSTSpecTests since it is incomplete without the implementations supplied by its subclasses.
  110. */
  111. - (BOOL)isTestBaseClass {
  112. return [self class] == [FSTSpecTests class];
  113. }
  114. #pragma mark - Methods for constructing objects from specs.
  115. - (nullable FSTQuery *)parseQuery:(id)querySpec {
  116. if ([querySpec isKindOfClass:[NSString class]]) {
  117. return FSTTestQuery(util::MakeString((NSString *)querySpec));
  118. } else if ([querySpec isKindOfClass:[NSDictionary class]]) {
  119. NSDictionary *queryDict = (NSDictionary *)querySpec;
  120. NSString *path = queryDict[@"path"];
  121. __block FSTQuery *query = FSTTestQuery(util::MakeString(path));
  122. if (queryDict[@"limit"]) {
  123. NSNumber *limit = queryDict[@"limit"];
  124. query = [query queryBySettingLimit:limit.integerValue];
  125. }
  126. if (queryDict[@"filters"]) {
  127. NSArray *filters = queryDict[@"filters"];
  128. [filters enumerateObjectsUsingBlock:^(NSArray *_Nonnull filter, NSUInteger idx,
  129. BOOL *_Nonnull stop) {
  130. query = [query
  131. queryByAddingFilter:FSTTestFilter(util::MakeString(filter[0]), filter[1], filter[2])];
  132. }];
  133. }
  134. if (queryDict[@"orderBys"]) {
  135. NSArray *orderBys = queryDict[@"orderBys"];
  136. [orderBys enumerateObjectsUsingBlock:^(NSArray *_Nonnull orderBy, NSUInteger idx,
  137. BOOL *_Nonnull stop) {
  138. query =
  139. [query queryByAddingSortOrder:FSTTestOrderBy(util::MakeString(orderBy[0]), orderBy[1])];
  140. }];
  141. }
  142. return query;
  143. } else {
  144. XCTFail(@"Invalid query: %@", querySpec);
  145. return nil;
  146. }
  147. }
  148. - (SnapshotVersion)parseVersion:(NSNumber *_Nullable)version {
  149. return testutil::Version(version.longLongValue);
  150. }
  151. - (FSTDocumentViewChange *)parseChange:(NSDictionary *)jsonDoc
  152. ofType:(FSTDocumentViewChangeType)type {
  153. NSNumber *version = jsonDoc[@"version"];
  154. NSDictionary *options = jsonDoc[@"options"];
  155. FSTDocumentState documentState = [options[@"hasLocalMutations"] isEqualToNumber:@YES]
  156. ? FSTDocumentStateLocalMutations
  157. : ([options[@"hasCommittedMutations"] isEqualToNumber:@YES]
  158. ? FSTDocumentStateCommittedMutations
  159. : FSTDocumentStateSynced);
  160. XCTAssert([jsonDoc[@"key"] isKindOfClass:[NSString class]]);
  161. FSTDocument *doc = FSTTestDoc(util::MakeString((NSString *)jsonDoc[@"key"]),
  162. version.longLongValue, jsonDoc[@"value"], documentState);
  163. return [FSTDocumentViewChange changeWithDocument:doc type:type];
  164. }
  165. #pragma mark - Methods for doing the steps of the spec test.
  166. - (void)doListen:(NSArray *)listenSpec {
  167. FSTQuery *query = [self parseQuery:listenSpec[1]];
  168. TargetId actualID = [self.driver addUserListenerWithQuery:query];
  169. TargetId expectedID = [listenSpec[0] intValue];
  170. XCTAssertEqual(actualID, expectedID, @"targetID assigned to listen");
  171. }
  172. - (void)doUnlisten:(NSArray *)unlistenSpec {
  173. FSTQuery *query = [self parseQuery:unlistenSpec[1]];
  174. [self.driver removeUserListenerWithQuery:query];
  175. }
  176. - (void)doSet:(NSArray *)setSpec {
  177. [self.driver writeUserMutation:FSTTestSetMutation(setSpec[0], setSpec[1])];
  178. }
  179. - (void)doPatch:(NSArray *)patchSpec {
  180. [self.driver
  181. writeUserMutation:FSTTestPatchMutation(util::MakeString(patchSpec[0]), patchSpec[1], {})];
  182. }
  183. - (void)doDelete:(NSString *)key {
  184. [self.driver writeUserMutation:FSTTestDeleteMutation(key)];
  185. }
  186. - (void)doWatchAck:(NSArray<NSNumber *> *)ackedTargets {
  187. FSTWatchTargetChange *change =
  188. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateAdded
  189. targetIDs:ackedTargets
  190. cause:nil];
  191. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  192. }
  193. - (void)doWatchCurrent:(NSArray<id> *)currentSpec {
  194. NSArray<NSNumber *> *currentTargets = currentSpec[0];
  195. NSData *resumeToken = [currentSpec[1] dataUsingEncoding:NSUTF8StringEncoding];
  196. FSTWatchTargetChange *change =
  197. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateCurrent
  198. targetIDs:currentTargets
  199. resumeToken:resumeToken];
  200. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  201. }
  202. - (void)doWatchRemove:(NSDictionary *)watchRemoveSpec {
  203. NSError *error = nil;
  204. NSDictionary *cause = watchRemoveSpec[@"cause"];
  205. if (cause) {
  206. int code = ((NSNumber *)cause[@"code"]).intValue;
  207. NSDictionary *userInfo = @{
  208. NSLocalizedDescriptionKey : @"Error from watchRemove.",
  209. };
  210. error = [NSError errorWithDomain:FIRFirestoreErrorDomain code:code userInfo:userInfo];
  211. }
  212. FSTWatchTargetChange *change =
  213. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateRemoved
  214. targetIDs:watchRemoveSpec[@"targetIds"]
  215. cause:error];
  216. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  217. // Unlike web, the FSTMockDatastore detects a watch removal with cause and will remove active
  218. // targets
  219. }
  220. - (void)doWatchEntity:(NSDictionary *)watchEntity {
  221. if (watchEntity[@"docs"]) {
  222. HARD_ASSERT(!watchEntity[@"doc"], "Exactly one of |doc| or |docs| needs to be set.");
  223. NSArray *docs = watchEntity[@"docs"];
  224. for (NSDictionary *doc in docs) {
  225. NSMutableDictionary *watchSpec = [NSMutableDictionary dictionary];
  226. watchSpec[@"doc"] = doc;
  227. if (watchEntity[@"targets"]) {
  228. watchSpec[@"targets"] = watchEntity[@"targets"];
  229. }
  230. if (watchEntity[@"removedTargets"]) {
  231. watchSpec[@"removedTargets"] = watchEntity[@"removedTargets"];
  232. }
  233. [self doWatchEntity:watchSpec];
  234. }
  235. } else if (watchEntity[@"doc"]) {
  236. NSDictionary *docSpec = watchEntity[@"doc"];
  237. DocumentKey key = FSTTestDocKey(docSpec[@"key"]);
  238. FSTObjectValue *_Nullable value = [docSpec[@"value"] isKindOfClass:[NSNull class]]
  239. ? nil
  240. : FSTTestObjectValue(docSpec[@"value"]);
  241. SnapshotVersion version = [self parseVersion:docSpec[@"version"]];
  242. FSTMaybeDocument *doc = value ? [FSTDocument documentWithData:value
  243. key:key
  244. version:std::move(version)
  245. state:FSTDocumentStateSynced]
  246. : [FSTDeletedDocument documentWithKey:key
  247. version:std::move(version)
  248. hasCommittedMutations:NO];
  249. FSTWatchChange *change =
  250. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:watchEntity[@"targets"]
  251. removedTargetIDs:watchEntity[@"removedTargets"]
  252. documentKey:doc.key
  253. document:doc];
  254. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  255. } else if (watchEntity[@"key"]) {
  256. DocumentKey docKey = FSTTestDocKey(watchEntity[@"key"]);
  257. FSTWatchChange *change =
  258. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:@[]
  259. removedTargetIDs:watchEntity[@"removedTargets"]
  260. documentKey:docKey
  261. document:nil];
  262. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  263. } else {
  264. HARD_FAIL("Either key, doc or docs must be set.");
  265. }
  266. }
  267. - (void)doWatchFilter:(NSArray *)watchFilter {
  268. NSArray<NSNumber *> *targets = watchFilter[0];
  269. HARD_ASSERT(targets.count == 1, "ExistenceFilters currently support exactly one target only.");
  270. int keyCount = watchFilter.count == 0 ? 0 : (int)watchFilter.count - 1;
  271. ExistenceFilter filter{keyCount};
  272. FSTExistenceFilterWatchChange *change =
  273. [FSTExistenceFilterWatchChange changeWithFilter:filter targetID:targets[0].intValue];
  274. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  275. }
  276. - (void)doWatchReset:(NSArray<NSNumber *> *)watchReset {
  277. FSTWatchTargetChange *change =
  278. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateReset
  279. targetIDs:watchReset
  280. cause:nil];
  281. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  282. }
  283. - (void)doWatchSnapshot:(NSDictionary *)watchSnapshot {
  284. // The client will only respond to watchSnapshots if they are on a target change with an empty
  285. // set of target IDs.
  286. NSArray<NSNumber *> *targetIDs =
  287. watchSnapshot[@"targetIds"] ? watchSnapshot[@"targetIds"] : [NSArray array];
  288. NSData *resumeToken = [watchSnapshot[@"resumeToken"] dataUsingEncoding:NSUTF8StringEncoding];
  289. FSTWatchTargetChange *change =
  290. [FSTWatchTargetChange changeWithState:FSTWatchTargetChangeStateNoChange
  291. targetIDs:targetIDs
  292. resumeToken:resumeToken];
  293. [self.driver receiveWatchChange:change
  294. snapshotVersion:[self parseVersion:watchSnapshot[@"version"]]];
  295. }
  296. - (void)doWatchStreamClose:(NSDictionary *)closeSpec {
  297. NSDictionary *errorSpec = closeSpec[@"error"];
  298. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  299. NSNumber *runBackoffTimer = closeSpec[@"runBackoffTimer"];
  300. // TODO(b/72313632): Incorporate backoff in iOS Spec Tests.
  301. HARD_ASSERT(runBackoffTimer.boolValue, "iOS Spec Tests don't support backoff.");
  302. [self.driver receiveWatchStreamError:code userInfo:errorSpec];
  303. }
  304. - (void)doWriteAck:(NSDictionary *)spec {
  305. SnapshotVersion version = [self parseVersion:spec[@"version"]];
  306. NSNumber *keepInQueue = spec[@"keepInQueue"];
  307. XCTAssertTrue(keepInQueue == nil || keepInQueue.boolValue == NO,
  308. @"'keepInQueue=true' is not supported on iOS and should only be set in "
  309. @"multi-client tests");
  310. FSTMutationResult *mutationResult = [[FSTMutationResult alloc] initWithVersion:version
  311. transformResults:nil];
  312. [self.driver receiveWriteAckWithVersion:version mutationResults:@[ mutationResult ]];
  313. }
  314. - (void)doFailWrite:(NSDictionary *)spec {
  315. NSDictionary *errorSpec = spec[@"error"];
  316. NSNumber *keepInQueue = spec[@"keepInQueue"];
  317. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  318. [self.driver receiveWriteError:code userInfo:errorSpec keepInQueue:keepInQueue.boolValue];
  319. }
  320. - (void)doDrainQueue {
  321. [self.driver drainQueue];
  322. }
  323. - (void)doRunTimer:(NSString *)timer {
  324. TimerId timerID;
  325. if ([timer isEqualToString:@"all"]) {
  326. timerID = TimerId::All;
  327. } else if ([timer isEqualToString:@"listen_stream_idle"]) {
  328. timerID = TimerId::ListenStreamIdle;
  329. } else if ([timer isEqualToString:@"listen_stream_connection_backoff"]) {
  330. timerID = TimerId::ListenStreamConnectionBackoff;
  331. } else if ([timer isEqualToString:@"write_stream_idle"]) {
  332. timerID = TimerId::WriteStreamIdle;
  333. } else if ([timer isEqualToString:@"write_stream_connection_backoff"]) {
  334. timerID = TimerId::WriteStreamConnectionBackoff;
  335. } else if ([timer isEqualToString:@"online_state_timeout"]) {
  336. timerID = TimerId::OnlineStateTimeout;
  337. } else {
  338. HARD_FAIL("runTimer spec step specified unknown timer: %s", timer);
  339. }
  340. [self.driver runTimer:timerID];
  341. }
  342. - (void)doDisableNetwork {
  343. _networkEnabled = NO;
  344. [self.driver disableNetwork];
  345. }
  346. - (void)doEnableNetwork {
  347. _networkEnabled = YES;
  348. [self.driver enableNetwork];
  349. }
  350. - (void)doChangeUser:(nullable id)UID {
  351. if ([UID isEqual:[NSNull null]]) {
  352. UID = nil;
  353. }
  354. [self.driver changeUser:User::FromUid(UID)];
  355. }
  356. - (void)doRestart {
  357. // Any outstanding user writes should be automatically re-sent, so we want to preserve them
  358. // when re-creating the driver.
  359. FSTOutstandingWriteQueues outstandingWrites = self.driver.outstandingWrites;
  360. User currentUser = self.driver.currentUser;
  361. [self.driver shutdown];
  362. id<FSTPersistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  363. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:persistence
  364. initialUser:currentUser
  365. outstandingWrites:outstandingWrites];
  366. [self.driver start];
  367. }
  368. - (void)doStep:(NSDictionary *)step {
  369. NSNumber *clientIndex = step[@"clientIndex"];
  370. XCTAssertNil(clientIndex, @"The iOS client does not support switching clients");
  371. if (step[@"userListen"]) {
  372. [self doListen:step[@"userListen"]];
  373. } else if (step[@"userUnlisten"]) {
  374. [self doUnlisten:step[@"userUnlisten"]];
  375. } else if (step[@"userSet"]) {
  376. [self doSet:step[@"userSet"]];
  377. } else if (step[@"userPatch"]) {
  378. [self doPatch:step[@"userPatch"]];
  379. } else if (step[@"userDelete"]) {
  380. [self doDelete:step[@"userDelete"]];
  381. } else if (step[@"drainQueue"]) {
  382. [self doDrainQueue];
  383. } else if (step[@"watchAck"]) {
  384. [self doWatchAck:step[@"watchAck"]];
  385. } else if (step[@"watchCurrent"]) {
  386. [self doWatchCurrent:step[@"watchCurrent"]];
  387. } else if (step[@"watchRemove"]) {
  388. [self doWatchRemove:step[@"watchRemove"]];
  389. } else if (step[@"watchEntity"]) {
  390. [self doWatchEntity:step[@"watchEntity"]];
  391. } else if (step[@"watchFilter"]) {
  392. [self doWatchFilter:step[@"watchFilter"]];
  393. } else if (step[@"watchReset"]) {
  394. [self doWatchReset:step[@"watchReset"]];
  395. } else if (step[@"watchSnapshot"]) {
  396. [self doWatchSnapshot:step[@"watchSnapshot"]];
  397. } else if (step[@"watchStreamClose"]) {
  398. [self doWatchStreamClose:step[@"watchStreamClose"]];
  399. } else if (step[@"watchProto"]) {
  400. // watchProto isn't yet used, and it's unclear how to create arbitrary protos from JSON.
  401. HARD_FAIL("watchProto is not yet supported.");
  402. } else if (step[@"writeAck"]) {
  403. [self doWriteAck:step[@"writeAck"]];
  404. } else if (step[@"failWrite"]) {
  405. [self doFailWrite:step[@"failWrite"]];
  406. } else if (step[@"runTimer"]) {
  407. [self doRunTimer:step[@"runTimer"]];
  408. } else if (step[@"enableNetwork"]) {
  409. if ([step[@"enableNetwork"] boolValue]) {
  410. [self doEnableNetwork];
  411. } else {
  412. [self doDisableNetwork];
  413. }
  414. } else if (step[@"changeUser"]) {
  415. [self doChangeUser:step[@"changeUser"]];
  416. } else if (step[@"restart"]) {
  417. [self doRestart];
  418. } else if (step[@"applyClientState"]) {
  419. XCTFail(@"'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 addObject:[self parseChange:changeSpec
  436. ofType:FSTDocumentViewChangeTypeRemoved]];
  437. }
  438. NSMutableArray *added = expected[@"added"];
  439. for (NSDictionary *changeSpec in added) {
  440. [expectedChanges addObject:[self parseChange:changeSpec
  441. ofType:FSTDocumentViewChangeTypeAdded]];
  442. }
  443. NSMutableArray *modified = expected[@"modified"];
  444. for (NSDictionary *changeSpec in modified) {
  445. [expectedChanges addObject:[self parseChange:changeSpec
  446. ofType:FSTDocumentViewChangeTypeModified]];
  447. }
  448. NSMutableArray *metadata = expected[@"metadata"];
  449. for (NSDictionary *changeSpec in metadata) {
  450. [expectedChanges addObject:[self parseChange:changeSpec
  451. 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. DocumentKeySet expectedLimboDocuments;
  508. NSArray *docNames = expected[@"limboDocs"];
  509. for (NSString *name in docNames) {
  510. expectedLimboDocuments = expectedLimboDocuments.insert(FSTTestDocKey(name));
  511. }
  512. // Update the expected limbo documents
  513. [self.driver setExpectedLimboDocuments:std::move(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 (const DocumentKey &expectedLimboDoc : self.driver.expectedLimboDocuments) {
  566. XCTAssert(actualLimboDocs.find(expectedLimboDoc) != actualLimboDocs.end(),
  567. @"Expected doc to be in limbo, but was not: %s", expectedLimboDoc.ToString().c_str());
  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