FSTSpecTests.mm 30 KB

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