FSTSpecTests.mm 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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. #include <map>
  19. #include <unordered_map>
  20. #include <utility>
  21. #include <vector>
  22. #import "Firestore/Source/Core/FSTEventManager.h"
  23. #import "Firestore/Source/Core/FSTQuery.h"
  24. #import "Firestore/Source/Local/FSTPersistence.h"
  25. #import "Firestore/Source/Local/FSTQueryData.h"
  26. #import "Firestore/Source/Model/FSTDocument.h"
  27. #import "Firestore/Source/Model/FSTFieldValue.h"
  28. #import "Firestore/Source/Model/FSTMutation.h"
  29. #import "Firestore/Source/Util/FSTClasses.h"
  30. #import "Firestore/Example/Tests/SpecTests/FSTSyncEngineTestDriver.h"
  31. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  32. #include "Firestore/core/include/firebase/firestore/firestore_errors.h"
  33. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  34. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  35. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  36. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  37. #include "Firestore/core/src/firebase/firestore/model/types.h"
  38. #include "Firestore/core/src/firebase/firestore/remote/existence_filter.h"
  39. #include "Firestore/core/src/firebase/firestore/remote/watch_change.h"
  40. #include "Firestore/core/src/firebase/firestore/util/async_queue.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/objc_compatibility.h"
  44. #include "Firestore/core/src/firebase/firestore/util/status.h"
  45. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  46. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  47. namespace testutil = firebase::firestore::testutil;
  48. namespace util = firebase::firestore::util;
  49. namespace objc = util::objc;
  50. using firebase::firestore::FirestoreErrorCode;
  51. using firebase::firestore::auth::User;
  52. using firebase::firestore::core::DocumentViewChange;
  53. using firebase::firestore::model::DocumentKey;
  54. using firebase::firestore::model::DocumentKeySet;
  55. using firebase::firestore::model::SnapshotVersion;
  56. using firebase::firestore::model::TargetId;
  57. using firebase::firestore::remote::ExistenceFilter;
  58. using firebase::firestore::remote::DocumentWatchChange;
  59. using firebase::firestore::remote::ExistenceFilterWatchChange;
  60. using firebase::firestore::remote::WatchTargetChange;
  61. using firebase::firestore::remote::WatchTargetChangeState;
  62. using firebase::firestore::util::MakeString;
  63. using firebase::firestore::util::Status;
  64. using firebase::firestore::util::TimerId;
  65. NS_ASSUME_NONNULL_BEGIN
  66. // Whether to run the benchmark spec tests.
  67. // TODO(mrschmidt): Make this configurable via the tests schema.
  68. static BOOL kRunBenchmarkTests = NO;
  69. // Disables all other tests; useful for debugging. Multiple tests can have this tag and they'll all
  70. // be run (but all others won't).
  71. static NSString *const kExclusiveTag = @"exclusive";
  72. // A tag for tests that should be excluded from execution (on iOS), useful to allow the platforms
  73. // to temporarily diverge.
  74. static NSString *const kNoIOSTag = @"no-ios";
  75. // A tag for tests that exercise the multi-client behavior of the Web client. These tests are
  76. // ignored on iOS.
  77. static NSString *const kMultiClientTag = @"multi-client";
  78. // A tag for tests that is assigned to the perf tests in "perf_spec.json". These tests are only run
  79. // if `kRunBenchmarkTests` is set to 'YES'.
  80. static NSString *const kBenchmarkTag = @"benchmark";
  81. NSString *const kEagerGC = @"eager-gc";
  82. NSString *const kDurablePersistence = @"durable-persistence";
  83. namespace {
  84. NSString *Describe(NSData *data) {
  85. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  86. }
  87. std::vector<TargetId> ConvertTargetsArray(NSArray<NSNumber *> *from) {
  88. std::vector<TargetId> result;
  89. for (NSNumber *targetID in from) {
  90. result.push_back(targetID.intValue);
  91. }
  92. return result;
  93. }
  94. } // namespace
  95. @interface FSTSpecTests ()
  96. @property(nonatomic, strong) FSTSyncEngineTestDriver *driver;
  97. @end
  98. @implementation FSTSpecTests {
  99. BOOL _gcEnabled;
  100. BOOL _networkEnabled;
  101. }
  102. - (id<FSTPersistence>)persistenceWithGCEnabled:(BOOL)GCEnabled {
  103. @throw FSTAbstractMethodException(); // NOLINT
  104. }
  105. - (BOOL)shouldRunWithTags:(NSArray<NSString *> *)tags {
  106. if ([tags containsObject:kNoIOSTag]) {
  107. return NO;
  108. } else if ([tags containsObject:kMultiClientTag]) {
  109. return NO;
  110. } else if (!kRunBenchmarkTests && [tags containsObject:kBenchmarkTag]) {
  111. return NO;
  112. }
  113. return YES;
  114. }
  115. - (void)setUpForSpecWithConfig:(NSDictionary *)config {
  116. // Store GCEnabled so we can re-use it in doRestart.
  117. NSNumber *GCEnabled = config[@"useGarbageCollection"];
  118. _gcEnabled = [GCEnabled boolValue];
  119. NSNumber *numClients = config[@"numClients"];
  120. if (numClients) {
  121. XCTAssertEqualObjects(numClients, @1, @"The iOS client does not support multi-client tests");
  122. }
  123. id<FSTPersistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  124. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:persistence];
  125. [self.driver start];
  126. }
  127. - (void)tearDownForSpec {
  128. [self.driver shutdown];
  129. }
  130. /**
  131. * Xcode will run tests from any class that extends XCTestCase, but this doesn't work for
  132. * FSTSpecTests since it is incomplete without the implementations supplied by its subclasses.
  133. */
  134. - (BOOL)isTestBaseClass {
  135. return [self class] == [FSTSpecTests class];
  136. }
  137. #pragma mark - Methods for constructing objects from specs.
  138. - (nullable FSTQuery *)parseQuery:(id)querySpec {
  139. if ([querySpec isKindOfClass:[NSString class]]) {
  140. return FSTTestQuery(util::MakeString((NSString *)querySpec));
  141. } else if ([querySpec isKindOfClass:[NSDictionary class]]) {
  142. NSDictionary *queryDict = (NSDictionary *)querySpec;
  143. NSString *path = queryDict[@"path"];
  144. __block FSTQuery *query = FSTTestQuery(util::MakeString(path));
  145. if (queryDict[@"limit"]) {
  146. NSNumber *limit = queryDict[@"limit"];
  147. query = [query queryBySettingLimit:limit.integerValue];
  148. }
  149. if (queryDict[@"filters"]) {
  150. NSArray *filters = queryDict[@"filters"];
  151. [filters enumerateObjectsUsingBlock:^(NSArray *_Nonnull filter, NSUInteger idx,
  152. BOOL *_Nonnull stop) {
  153. query = [query
  154. queryByAddingFilter:FSTTestFilter(util::MakeString(filter[0]), filter[1], filter[2])];
  155. }];
  156. }
  157. if (queryDict[@"orderBys"]) {
  158. NSArray *orderBys = queryDict[@"orderBys"];
  159. [orderBys enumerateObjectsUsingBlock:^(NSArray *_Nonnull orderBy, NSUInteger idx,
  160. BOOL *_Nonnull stop) {
  161. query =
  162. [query queryByAddingSortOrder:FSTTestOrderBy(util::MakeString(orderBy[0]), orderBy[1])];
  163. }];
  164. }
  165. return query;
  166. } else {
  167. XCTFail(@"Invalid query: %@", querySpec);
  168. return nil;
  169. }
  170. }
  171. - (SnapshotVersion)parseVersion:(NSNumber *_Nullable)version {
  172. return testutil::Version(version.longLongValue);
  173. }
  174. - (DocumentViewChange)parseChange:(NSDictionary *)jsonDoc ofType:(DocumentViewChange::Type)type {
  175. NSNumber *version = jsonDoc[@"version"];
  176. NSDictionary *options = jsonDoc[@"options"];
  177. FSTDocumentState documentState = [options[@"hasLocalMutations"] isEqualToNumber:@YES]
  178. ? FSTDocumentStateLocalMutations
  179. : ([options[@"hasCommittedMutations"] isEqualToNumber:@YES]
  180. ? FSTDocumentStateCommittedMutations
  181. : FSTDocumentStateSynced);
  182. XCTAssert([jsonDoc[@"key"] isKindOfClass:[NSString class]]);
  183. FSTDocument *doc = FSTTestDoc(util::MakeString((NSString *)jsonDoc[@"key"]),
  184. version.longLongValue, jsonDoc[@"value"], documentState);
  185. return DocumentViewChange{doc, type};
  186. }
  187. #pragma mark - Methods for doing the steps of the spec test.
  188. - (void)doListen:(NSArray *)listenSpec {
  189. FSTQuery *query = [self parseQuery:listenSpec[1]];
  190. TargetId actualID = [self.driver addUserListenerWithQuery:query];
  191. TargetId expectedID = [listenSpec[0] intValue];
  192. XCTAssertEqual(actualID, expectedID, @"targetID assigned to listen");
  193. }
  194. - (void)doUnlisten:(NSArray *)unlistenSpec {
  195. FSTQuery *query = [self parseQuery:unlistenSpec[1]];
  196. [self.driver removeUserListenerWithQuery:query];
  197. }
  198. - (void)doSet:(NSArray *)setSpec {
  199. [self.driver writeUserMutation:FSTTestSetMutation(setSpec[0], setSpec[1])];
  200. }
  201. - (void)doPatch:(NSArray *)patchSpec {
  202. [self.driver
  203. writeUserMutation:FSTTestPatchMutation(util::MakeString(patchSpec[0]), patchSpec[1], {})];
  204. }
  205. - (void)doDelete:(NSString *)key {
  206. [self.driver writeUserMutation:FSTTestDeleteMutation(key)];
  207. }
  208. - (void)doWatchAck:(NSArray<NSNumber *> *)ackedTargets {
  209. WatchTargetChange change{WatchTargetChangeState::Added, ConvertTargetsArray(ackedTargets)};
  210. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  211. }
  212. - (void)doWatchCurrent:(NSArray<id> *)currentSpec {
  213. NSArray<NSNumber *> *currentTargets = currentSpec[0];
  214. NSData *resumeToken = [currentSpec[1] dataUsingEncoding:NSUTF8StringEncoding];
  215. WatchTargetChange change{WatchTargetChangeState::Current, ConvertTargetsArray(currentTargets),
  216. resumeToken};
  217. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  218. }
  219. - (void)doWatchRemove:(NSDictionary *)watchRemoveSpec {
  220. Status error;
  221. NSDictionary *cause = watchRemoveSpec[@"cause"];
  222. if (cause) {
  223. int code = ((NSNumber *)cause[@"code"]).intValue;
  224. NSDictionary *userInfo = @{
  225. NSLocalizedDescriptionKey : @"Error from watchRemove.",
  226. };
  227. error = Status{static_cast<FirestoreErrorCode>(code), MakeString([userInfo description])};
  228. }
  229. WatchTargetChange change{WatchTargetChangeState::Removed,
  230. ConvertTargetsArray(watchRemoveSpec[@"targetIds"]), error};
  231. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  232. // Unlike web, the FSTMockDatastore detects a watch removal with cause and will remove active
  233. // targets
  234. }
  235. - (void)doWatchEntity:(NSDictionary *)watchEntity {
  236. if (watchEntity[@"docs"]) {
  237. HARD_ASSERT(!watchEntity[@"doc"], "Exactly one of |doc| or |docs| needs to be set.");
  238. NSArray *docs = watchEntity[@"docs"];
  239. for (NSDictionary *doc in docs) {
  240. NSMutableDictionary *watchSpec = [NSMutableDictionary dictionary];
  241. watchSpec[@"doc"] = doc;
  242. if (watchEntity[@"targets"]) {
  243. watchSpec[@"targets"] = watchEntity[@"targets"];
  244. }
  245. if (watchEntity[@"removedTargets"]) {
  246. watchSpec[@"removedTargets"] = watchEntity[@"removedTargets"];
  247. }
  248. [self doWatchEntity:watchSpec];
  249. }
  250. } else if (watchEntity[@"doc"]) {
  251. NSDictionary *docSpec = watchEntity[@"doc"];
  252. DocumentKey key = FSTTestDocKey(docSpec[@"key"]);
  253. FSTObjectValue *_Nullable value = [docSpec[@"value"] isKindOfClass:[NSNull class]]
  254. ? nil
  255. : FSTTestObjectValue(docSpec[@"value"]);
  256. SnapshotVersion version = [self parseVersion:docSpec[@"version"]];
  257. FSTMaybeDocument *doc = value ? [FSTDocument documentWithData:value
  258. key:key
  259. version:std::move(version)
  260. state:FSTDocumentStateSynced]
  261. : [FSTDeletedDocument documentWithKey:key
  262. version:std::move(version)
  263. hasCommittedMutations:NO];
  264. DocumentWatchChange change{ConvertTargetsArray(watchEntity[@"targets"]),
  265. ConvertTargetsArray(watchEntity[@"removedTargets"]), doc.key, doc};
  266. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  267. } else if (watchEntity[@"key"]) {
  268. DocumentKey docKey = FSTTestDocKey(watchEntity[@"key"]);
  269. DocumentWatchChange change{
  270. {}, ConvertTargetsArray(watchEntity[@"removedTargets"]), docKey, nil};
  271. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  272. } else {
  273. HARD_FAIL("Either key, doc or docs must be set.");
  274. }
  275. }
  276. - (void)doWatchFilter:(NSArray *)watchFilter {
  277. NSArray<NSNumber *> *targets = watchFilter[0];
  278. HARD_ASSERT(targets.count == 1, "ExistenceFilters currently support exactly one target only.");
  279. int keyCount = watchFilter.count == 0 ? 0 : (int)watchFilter.count - 1;
  280. ExistenceFilter filter{keyCount};
  281. ExistenceFilterWatchChange change{filter, targets[0].intValue};
  282. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  283. }
  284. - (void)doWatchReset:(NSArray<NSNumber *> *)watchReset {
  285. WatchTargetChange change{WatchTargetChangeState::Reset, ConvertTargetsArray(watchReset)};
  286. [self.driver receiveWatchChange:change snapshotVersion:SnapshotVersion::None()];
  287. }
  288. - (void)doWatchSnapshot:(NSDictionary *)watchSnapshot {
  289. // The client will only respond to watchSnapshots if they are on a target change with an empty
  290. // set of target IDs.
  291. NSArray<NSNumber *> *targetIDs =
  292. watchSnapshot[@"targetIds"] ? watchSnapshot[@"targetIds"] : [NSArray array];
  293. NSData *resumeToken = [watchSnapshot[@"resumeToken"] dataUsingEncoding:NSUTF8StringEncoding];
  294. WatchTargetChange change{WatchTargetChangeState::NoChange, ConvertTargetsArray(targetIDs),
  295. resumeToken};
  296. [self.driver receiveWatchChange:change
  297. snapshotVersion:[self parseVersion:watchSnapshot[@"version"]]];
  298. }
  299. - (void)doWatchStreamClose:(NSDictionary *)closeSpec {
  300. NSDictionary *errorSpec = closeSpec[@"error"];
  301. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  302. NSNumber *runBackoffTimer = closeSpec[@"runBackoffTimer"];
  303. // TODO(b/72313632): Incorporate backoff in iOS Spec Tests.
  304. HARD_ASSERT(runBackoffTimer.boolValue, "iOS Spec Tests don't support backoff.");
  305. [self.driver receiveWatchStreamError:code userInfo:errorSpec];
  306. }
  307. - (void)doWriteAck:(NSDictionary *)spec {
  308. SnapshotVersion version = [self parseVersion:spec[@"version"]];
  309. NSNumber *keepInQueue = spec[@"keepInQueue"];
  310. XCTAssertTrue(keepInQueue == nil || keepInQueue.boolValue == NO,
  311. @"'keepInQueue=true' is not supported on iOS and should only be set in "
  312. @"multi-client tests");
  313. FSTMutationResult *mutationResult = [[FSTMutationResult alloc] initWithVersion:version
  314. transformResults:nil];
  315. [self.driver receiveWriteAckWithVersion:version mutationResults:{mutationResult}];
  316. }
  317. - (void)doFailWrite:(NSDictionary *)spec {
  318. NSDictionary *errorSpec = spec[@"error"];
  319. NSNumber *keepInQueue = spec[@"keepInQueue"];
  320. int code = ((NSNumber *)(errorSpec[@"code"])).intValue;
  321. [self.driver receiveWriteError:code userInfo:errorSpec keepInQueue:keepInQueue.boolValue];
  322. }
  323. - (void)doDrainQueue {
  324. [self.driver drainQueue];
  325. }
  326. - (void)doRunTimer:(NSString *)timer {
  327. TimerId timerID;
  328. if ([timer isEqualToString:@"all"]) {
  329. timerID = TimerId::All;
  330. } else if ([timer isEqualToString:@"listen_stream_idle"]) {
  331. timerID = TimerId::ListenStreamIdle;
  332. } else if ([timer isEqualToString:@"listen_stream_connection_backoff"]) {
  333. timerID = TimerId::ListenStreamConnectionBackoff;
  334. } else if ([timer isEqualToString:@"write_stream_idle"]) {
  335. timerID = TimerId::WriteStreamIdle;
  336. } else if ([timer isEqualToString:@"write_stream_connection_backoff"]) {
  337. timerID = TimerId::WriteStreamConnectionBackoff;
  338. } else if ([timer isEqualToString:@"online_state_timeout"]) {
  339. timerID = TimerId::OnlineStateTimeout;
  340. } else {
  341. HARD_FAIL("runTimer spec step specified unknown timer: %s", timer);
  342. }
  343. [self.driver runTimer:timerID];
  344. }
  345. - (void)doDisableNetwork {
  346. _networkEnabled = NO;
  347. [self.driver disableNetwork];
  348. }
  349. - (void)doEnableNetwork {
  350. _networkEnabled = YES;
  351. [self.driver enableNetwork];
  352. }
  353. - (void)doChangeUser:(nullable id)UID {
  354. if ([UID isEqual:[NSNull null]]) {
  355. UID = nil;
  356. }
  357. [self.driver changeUser:User::FromUid(UID)];
  358. }
  359. - (void)doRestart {
  360. // Any outstanding user writes should be automatically re-sent, so we want to preserve them
  361. // when re-creating the driver.
  362. FSTOutstandingWriteQueues outstandingWrites = self.driver.outstandingWrites;
  363. User currentUser = self.driver.currentUser;
  364. [self.driver shutdown];
  365. id<FSTPersistence> persistence = [self persistenceWithGCEnabled:_gcEnabled];
  366. self.driver = [[FSTSyncEngineTestDriver alloc] initWithPersistence:persistence
  367. initialUser:currentUser
  368. outstandingWrites:outstandingWrites];
  369. [self.driver start];
  370. }
  371. - (void)doStep:(NSDictionary *)step {
  372. NSNumber *clientIndex = step[@"clientIndex"];
  373. XCTAssertNil(clientIndex, @"The iOS client does not support switching clients");
  374. if (step[@"userListen"]) {
  375. [self doListen:step[@"userListen"]];
  376. } else if (step[@"userUnlisten"]) {
  377. [self doUnlisten:step[@"userUnlisten"]];
  378. } else if (step[@"userSet"]) {
  379. [self doSet:step[@"userSet"]];
  380. } else if (step[@"userPatch"]) {
  381. [self doPatch:step[@"userPatch"]];
  382. } else if (step[@"userDelete"]) {
  383. [self doDelete:step[@"userDelete"]];
  384. } else if (step[@"drainQueue"]) {
  385. [self doDrainQueue];
  386. } else if (step[@"watchAck"]) {
  387. [self doWatchAck:step[@"watchAck"]];
  388. } else if (step[@"watchCurrent"]) {
  389. [self doWatchCurrent:step[@"watchCurrent"]];
  390. } else if (step[@"watchRemove"]) {
  391. [self doWatchRemove:step[@"watchRemove"]];
  392. } else if (step[@"watchEntity"]) {
  393. [self doWatchEntity:step[@"watchEntity"]];
  394. } else if (step[@"watchFilter"]) {
  395. [self doWatchFilter:step[@"watchFilter"]];
  396. } else if (step[@"watchReset"]) {
  397. [self doWatchReset:step[@"watchReset"]];
  398. } else if (step[@"watchSnapshot"]) {
  399. [self doWatchSnapshot:step[@"watchSnapshot"]];
  400. } else if (step[@"watchStreamClose"]) {
  401. [self doWatchStreamClose:step[@"watchStreamClose"]];
  402. } else if (step[@"watchProto"]) {
  403. // watchProto isn't yet used, and it's unclear how to create arbitrary protos from JSON.
  404. HARD_FAIL("watchProto is not yet supported.");
  405. } else if (step[@"writeAck"]) {
  406. [self doWriteAck:step[@"writeAck"]];
  407. } else if (step[@"failWrite"]) {
  408. [self doFailWrite:step[@"failWrite"]];
  409. } else if (step[@"runTimer"]) {
  410. [self doRunTimer:step[@"runTimer"]];
  411. } else if (step[@"enableNetwork"]) {
  412. if ([step[@"enableNetwork"] boolValue]) {
  413. [self doEnableNetwork];
  414. } else {
  415. [self doDisableNetwork];
  416. }
  417. } else if (step[@"changeUser"]) {
  418. [self doChangeUser:step[@"changeUser"]];
  419. } else if (step[@"restart"]) {
  420. [self doRestart];
  421. } else if (step[@"applyClientState"]) {
  422. XCTFail(@"'applyClientState' is not supported on iOS and should only be used in multi-client "
  423. @"tests");
  424. } else {
  425. XCTFail(@"Unknown step: %@", step);
  426. }
  427. }
  428. - (void)validateEvent:(FSTQueryEvent *)actual matches:(NSDictionary *)expected {
  429. FSTQuery *expectedQuery = [self parseQuery:expected[@"query"]];
  430. XCTAssertEqualObjects(actual.query, expectedQuery);
  431. if ([expected[@"errorCode"] integerValue] != 0) {
  432. XCTAssertNotNil(actual.error);
  433. XCTAssertEqual(actual.error.code, [expected[@"errorCode"] integerValue]);
  434. } else {
  435. std::vector<DocumentViewChange> expectedChanges;
  436. NSMutableArray *removed = expected[@"removed"];
  437. for (NSDictionary *changeSpec in removed) {
  438. expectedChanges.push_back([self parseChange:changeSpec
  439. ofType:DocumentViewChange::Type::kRemoved]);
  440. }
  441. NSMutableArray *added = expected[@"added"];
  442. for (NSDictionary *changeSpec in added) {
  443. expectedChanges.push_back([self parseChange:changeSpec
  444. ofType:DocumentViewChange::Type::kAdded]);
  445. }
  446. NSMutableArray *modified = expected[@"modified"];
  447. for (NSDictionary *changeSpec in modified) {
  448. expectedChanges.push_back([self parseChange:changeSpec
  449. ofType:DocumentViewChange::Type::kModified]);
  450. }
  451. NSMutableArray *metadata = expected[@"metadata"];
  452. for (NSDictionary *changeSpec in metadata) {
  453. expectedChanges.push_back([self parseChange:changeSpec
  454. ofType:DocumentViewChange::Type::kMetadata]);
  455. }
  456. XCTAssertEqual(actual.viewSnapshot.documentChanges.size(), expectedChanges.size());
  457. for (size_t i = 0; i != expectedChanges.size(); ++i) {
  458. XCTAssertTrue((actual.viewSnapshot.documentChanges[i] == expectedChanges[i]));
  459. }
  460. BOOL expectedHasPendingWrites =
  461. expected[@"hasPendingWrites"] ? [expected[@"hasPendingWrites"] boolValue] : NO;
  462. BOOL expectedIsFromCache = expected[@"fromCache"] ? [expected[@"fromCache"] boolValue] : NO;
  463. XCTAssertEqual(actual.viewSnapshot.hasPendingWrites, expectedHasPendingWrites,
  464. @"hasPendingWrites");
  465. XCTAssertEqual(actual.viewSnapshot.isFromCache, expectedIsFromCache, @"isFromCache");
  466. }
  467. }
  468. - (void)validateStepExpectations:(NSArray *_Nullable)stepExpectations {
  469. NSArray<FSTQueryEvent *> *events = self.driver.capturedEventsSinceLastCall;
  470. if (!stepExpectations) {
  471. XCTAssertEqual(events.count, 0);
  472. for (FSTQueryEvent *event in events) {
  473. XCTFail(@"Unexpected event: %@", event);
  474. }
  475. return;
  476. }
  477. XCTAssertEqual(events.count, stepExpectations.count);
  478. events =
  479. [events sortedArrayUsingComparator:^NSComparisonResult(FSTQueryEvent *q1, FSTQueryEvent *q2) {
  480. return [q1.query.canonicalID compare:q2.query.canonicalID];
  481. }];
  482. stepExpectations = [stepExpectations
  483. sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
  484. FSTQuery *leftQuery = [self parseQuery:left[@"query"]];
  485. FSTQuery *rightQuery = [self parseQuery:right[@"query"]];
  486. return [leftQuery.canonicalID compare:rightQuery.canonicalID];
  487. }];
  488. NSUInteger i = 0;
  489. for (; i < stepExpectations.count && i < events.count; ++i) {
  490. [self validateEvent:events[i] matches:stepExpectations[i]];
  491. }
  492. for (; i < stepExpectations.count; ++i) {
  493. XCTFail(@"Missing event: %@", stepExpectations[i]);
  494. }
  495. for (; i < events.count; ++i) {
  496. XCTFail(@"Unexpected event: %@", events[i]);
  497. }
  498. }
  499. - (void)validateStateExpectations:(nullable NSDictionary *)expected {
  500. if (expected) {
  501. if (expected[@"numOutstandingWrites"]) {
  502. XCTAssertEqual([self.driver sentWritesCount], [expected[@"numOutstandingWrites"] intValue]);
  503. }
  504. if (expected[@"writeStreamRequestCount"]) {
  505. XCTAssertEqual([self.driver writeStreamRequestCount],
  506. [expected[@"writeStreamRequestCount"] intValue]);
  507. }
  508. if (expected[@"watchStreamRequestCount"]) {
  509. XCTAssertEqual([self.driver watchStreamRequestCount],
  510. [expected[@"watchStreamRequestCount"] intValue]);
  511. }
  512. if (expected[@"limboDocs"]) {
  513. DocumentKeySet expectedLimboDocuments;
  514. NSArray *docNames = expected[@"limboDocs"];
  515. for (NSString *name in docNames) {
  516. expectedLimboDocuments = expectedLimboDocuments.insert(FSTTestDocKey(name));
  517. }
  518. // Update the expected limbo documents
  519. [self.driver setExpectedLimboDocuments:std::move(expectedLimboDocuments)];
  520. }
  521. if (expected[@"activeTargets"]) {
  522. __block std::unordered_map<TargetId, FSTQueryData *> expectedActiveTargets;
  523. [expected[@"activeTargets"] enumerateKeysAndObjectsUsingBlock:^(NSString *targetIDString,
  524. NSDictionary *queryData,
  525. BOOL *stop) {
  526. TargetId targetID = [targetIDString intValue];
  527. FSTQuery *query = [self parseQuery:queryData[@"query"]];
  528. NSData *resumeToken = [queryData[@"resumeToken"] dataUsingEncoding:NSUTF8StringEncoding];
  529. // TODO(mcg): populate the purpose of the target once it's possible to encode that in the
  530. // spec tests. For now, hard-code that it's a listen despite the fact that it's not always
  531. // the right value.
  532. expectedActiveTargets[targetID] =
  533. [[FSTQueryData alloc] initWithQuery:query
  534. targetID:targetID
  535. listenSequenceNumber:0
  536. purpose:FSTQueryPurposeListen
  537. snapshotVersion:SnapshotVersion::None()
  538. resumeToken:resumeToken];
  539. }];
  540. [self.driver setExpectedActiveTargets:expectedActiveTargets];
  541. }
  542. }
  543. // Always validate the we received the expected number of callbacks.
  544. [self validateUserCallbacks:expected];
  545. // Always validate that the expected limbo docs match the actual limbo docs.
  546. [self validateLimboDocuments];
  547. // Always validate that the expected active targets match the actual active targets.
  548. [self validateActiveTargets];
  549. }
  550. - (void)validateUserCallbacks:(nullable NSDictionary *)expected {
  551. NSDictionary *expectedCallbacks = expected[@"userCallbacks"];
  552. NSArray<NSString *> *actualAcknowledgedDocs =
  553. [self.driver capturedAcknowledgedWritesSinceLastCall];
  554. NSArray<NSString *> *actualRejectedDocs = [self.driver capturedRejectedWritesSinceLastCall];
  555. if (expectedCallbacks) {
  556. XCTAssertTrue([actualAcknowledgedDocs isEqualToArray:expectedCallbacks[@"acknowledgedDocs"]]);
  557. XCTAssertTrue([actualRejectedDocs isEqualToArray:expectedCallbacks[@"rejectedDocs"]]);
  558. } else {
  559. XCTAssertEqual([actualAcknowledgedDocs count], 0);
  560. XCTAssertEqual([actualRejectedDocs count], 0);
  561. }
  562. }
  563. - (void)validateLimboDocuments {
  564. // Make a copy so it can modified while checking against the expected limbo docs.
  565. std::map<DocumentKey, TargetId> actualLimboDocs = self.driver.currentLimboDocuments;
  566. // Validate that each limbo doc has an expected active target
  567. for (const auto &kv : actualLimboDocs) {
  568. const auto &expected = [self.driver expectedActiveTargets];
  569. XCTAssertTrue(expected.find(kv.second) != expected.end(),
  570. @"Found limbo doc without an expected active target");
  571. }
  572. for (const DocumentKey &expectedLimboDoc : self.driver.expectedLimboDocuments) {
  573. XCTAssert(actualLimboDocs.find(expectedLimboDoc) != actualLimboDocs.end(),
  574. @"Expected doc to be in limbo, but was not: %s", expectedLimboDoc.ToString().c_str());
  575. actualLimboDocs.erase(expectedLimboDoc);
  576. }
  577. XCTAssertTrue(actualLimboDocs.empty(), "%lu Unexpected docs in limbo, the first one is <%s, %d>",
  578. actualLimboDocs.size(), actualLimboDocs.begin()->first.ToString().c_str(),
  579. actualLimboDocs.begin()->second);
  580. }
  581. - (void)validateActiveTargets {
  582. if (!_networkEnabled) {
  583. return;
  584. }
  585. // Create a copy so we can modify it in tests
  586. std::unordered_map<TargetId, FSTQueryData *> actualTargets = [self.driver activeTargets];
  587. for (const auto &kv : [self.driver activeTargets]) {
  588. TargetId targetID = kv.first;
  589. FSTQueryData *queryData = kv.second;
  590. XCTAssertNotNil(actualTargets[targetID], @"Expected active target not found: %@", queryData);
  591. // TODO(mcg): validate the purpose of the target once it's possible to encode that in the
  592. // spec tests. For now, only validate properties that can be validated.
  593. // XCTAssertEqualObjects(actualTargets[targetID], queryData);
  594. FSTQueryData *actual = actualTargets[targetID];
  595. XCTAssertNotNil(actual);
  596. if (actual) {
  597. XCTAssertEqualObjects(actual.query, queryData.query);
  598. XCTAssertEqual(actual.targetID, queryData.targetID);
  599. XCTAssertEqual(actual.snapshotVersion, queryData.snapshotVersion);
  600. XCTAssertEqualObjects(Describe(actual.resumeToken), Describe(queryData.resumeToken));
  601. }
  602. actualTargets.erase(targetID);
  603. }
  604. XCTAssertTrue(actualTargets.empty(), "Unexpected active targets: %@",
  605. objc::Description(actualTargets));
  606. }
  607. - (void)runSpecTestSteps:(NSArray *)steps config:(NSDictionary *)config {
  608. @try {
  609. [self setUpForSpecWithConfig:config];
  610. for (NSDictionary *step in steps) {
  611. LOG_DEBUG("Doing step %s", step);
  612. [self doStep:step];
  613. [self validateStepExpectations:step[@"expect"]];
  614. [self validateStateExpectations:step[@"stateExpect"]];
  615. }
  616. [self.driver validateUsage];
  617. } @finally {
  618. // Ensure that the driver is torn down even if the test is failing due to a thrown exception so
  619. // that any resources held by the driver are released. This is important when the driver is
  620. // backed by LevelDB because LevelDB locks its database. If -tearDownForSpec were not called
  621. // after an exception then subsequent attempts to open the LevelDB will fail, making it harder
  622. // to zero in on the spec tests as a culprit.
  623. [self tearDownForSpec];
  624. }
  625. }
  626. #pragma mark - The actual test methods.
  627. - (void)testSpecTests {
  628. if ([self isTestBaseClass]) return;
  629. // Enumerate the .json files containing the spec tests.
  630. NSMutableArray<NSString *> *specFiles = [NSMutableArray array];
  631. NSMutableArray<NSDictionary *> *parsedSpecs = [NSMutableArray array];
  632. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  633. NSFileManager *fs = [NSFileManager defaultManager];
  634. BOOL exclusiveMode = NO;
  635. for (NSString *file in [fs enumeratorAtPath:[bundle bundlePath]]) {
  636. if (![@"json" isEqual:[file pathExtension]]) {
  637. continue;
  638. }
  639. // Read and parse the JSON from the file.
  640. NSString *fileName = [file stringByDeletingPathExtension];
  641. NSString *path = [bundle pathForResource:fileName ofType:@"json"];
  642. NSData *json = [NSData dataWithContentsOfFile:path];
  643. XCTAssertNotNil(json);
  644. NSError *error = nil;
  645. id _Nullable parsed = [NSJSONSerialization JSONObjectWithData:json options:0 error:&error];
  646. XCTAssertNil(error, @"%@", error);
  647. XCTAssertTrue([parsed isKindOfClass:[NSDictionary class]]);
  648. NSDictionary *testDict = (NSDictionary *)parsed;
  649. exclusiveMode = exclusiveMode || [self anyTestsAreMarkedExclusive:testDict];
  650. [specFiles addObject:fileName];
  651. [parsedSpecs addObject:testDict];
  652. }
  653. // Now iterate over them and run them.
  654. __block bool ranAtLeastOneTest = NO;
  655. for (NSUInteger i = 0; i < specFiles.count; i++) {
  656. NSLog(@"Spec test file: %@", specFiles[i]);
  657. // Iterate over the tests in the file and run them.
  658. [parsedSpecs[i] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  659. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  660. NSDictionary *testDescription = (NSDictionary *)obj;
  661. NSString *describeName = testDescription[@"describeName"];
  662. NSString *itName = testDescription[@"itName"];
  663. NSString *name = [NSString stringWithFormat:@"%@ %@", describeName, itName];
  664. NSDictionary *config = testDescription[@"config"];
  665. NSArray *steps = testDescription[@"steps"];
  666. NSArray<NSString *> *tags = testDescription[@"tags"];
  667. BOOL runTest = !exclusiveMode || [tags indexOfObject:kExclusiveTag] != NSNotFound;
  668. if (runTest) {
  669. runTest = [self shouldRunWithTags:tags];
  670. }
  671. if (runTest) {
  672. NSLog(@" Spec test: %@", name);
  673. [self runSpecTestSteps:steps config:config];
  674. ranAtLeastOneTest = YES;
  675. } else {
  676. NSLog(@" [SKIPPED] Spec test: %@", name);
  677. NSString *comment = testDescription[@"comment"];
  678. if (comment) {
  679. NSLog(@" %@", comment);
  680. }
  681. }
  682. }];
  683. }
  684. XCTAssertTrue(ranAtLeastOneTest);
  685. }
  686. - (BOOL)anyTestsAreMarkedExclusive:(NSDictionary *)tests {
  687. __block BOOL found = NO;
  688. [tests enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  689. XCTAssertTrue([obj isKindOfClass:[NSDictionary class]]);
  690. NSDictionary *testDescription = (NSDictionary *)obj;
  691. NSArray<NSString *> *tags = testDescription[@"tags"];
  692. if ([tags indexOfObject:kExclusiveTag] != NSNotFound) {
  693. found = YES;
  694. *stop = YES;
  695. }
  696. }];
  697. return found;
  698. }
  699. @end
  700. NS_ASSUME_NONNULL_END