FSTSpecTests.mm 29 KB

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