FSTSpecTests.mm 30 KB

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