FSTSpecTests.mm 28 KB

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