FSTSpecTests.mm 29 KB

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