FSTSpecTests.mm 33 KB

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