FSTHelpers.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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/Util/FSTHelpers.h"
  17. #include <inttypes.h>
  18. #include <list>
  19. #include <map>
  20. #include <vector>
  21. #import <FirebaseFirestore/FIRFieldPath.h>
  22. #import <FirebaseFirestore/FIRGeoPoint.h>
  23. #import <FirebaseFirestore/FIRTimestamp.h>
  24. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  25. #import "Firestore/Source/API/FSTUserDataConverter.h"
  26. #import "Firestore/Source/Core/FSTQuery.h"
  27. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  28. #import "Firestore/Source/Core/FSTView.h"
  29. #import "Firestore/Source/Core/FSTViewSnapshot.h"
  30. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  31. #import "Firestore/Source/Local/FSTQueryData.h"
  32. #import "Firestore/Source/Model/FSTDocument.h"
  33. #import "Firestore/Source/Model/FSTDocumentKey.h"
  34. #import "Firestore/Source/Model/FSTDocumentSet.h"
  35. #import "Firestore/Source/Model/FSTFieldValue.h"
  36. #import "Firestore/Source/Model/FSTMutation.h"
  37. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  38. #import "Firestore/Source/Remote/FSTWatchChange.h"
  39. #import "Firestore/Source/Util/FSTAssert.h"
  40. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  41. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  42. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  43. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  44. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  45. namespace util = firebase::firestore::util;
  46. namespace testutil = firebase::firestore::testutil;
  47. using firebase::firestore::model::DatabaseId;
  48. using firebase::firestore::model::FieldPath;
  49. using firebase::firestore::model::FieldValue;
  50. using firebase::firestore::model::ResourcePath;
  51. NS_ASSUME_NONNULL_BEGIN
  52. /** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
  53. static NSString *const kDeleteSentinel = @"<DELETE>";
  54. static const int kMicrosPerSec = 1000000;
  55. static const int kMillisPerSec = 1000;
  56. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  57. NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  58. return [FIRTimestamp timestampWithDate:date];
  59. }
  60. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  61. NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  62. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  63. }
  64. NSData *FSTTestData(int bytes, ...) {
  65. va_list args;
  66. va_start(args, bytes); /* Initialize the argument list. */
  67. NSMutableData *data = [NSMutableData data];
  68. int next = bytes;
  69. while (next >= 0) {
  70. uint8_t byte = (uint8_t)next;
  71. [data appendBytes:&byte length:1];
  72. next = va_arg(args, int);
  73. }
  74. va_end(args);
  75. return [data copy];
  76. }
  77. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  78. return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
  79. }
  80. NSDateComponents *FSTTestDateComponents(
  81. int year, int month, int day, int hour, int minute, int second) {
  82. NSDateComponents *comps = [[NSDateComponents alloc] init];
  83. comps.year = year;
  84. comps.month = month;
  85. comps.day = day;
  86. comps.hour = hour;
  87. comps.minute = minute;
  88. comps.second = second;
  89. // Force time zone to UTC to avoid these values changing due to daylight saving.
  90. comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  91. return comps;
  92. }
  93. FSTFieldValue *FSTTestFieldValue(id _Nullable value) {
  94. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  95. static DatabaseId database_id{"project", DatabaseId::kDefault};
  96. FSTUserDataConverter *converter =
  97. [[FSTUserDataConverter alloc] initWithDatabaseID:&database_id
  98. preConverter:^id _Nullable(id _Nullable input) {
  99. return input;
  100. }];
  101. // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  102. // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  103. return [converter parsedQueryValue:value];
  104. }
  105. FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  106. FSTFieldValue *wrapped = FSTTestFieldValue(data);
  107. FSTCAssert([wrapped isKindOfClass:[FSTObjectValue class]], @"Unsupported value: %@", data);
  108. return (FSTObjectValue *)wrapped;
  109. }
  110. FSTDocumentKey *FSTTestDocKey(NSString *path) {
  111. return [FSTDocumentKey keyWithPathString:path];
  112. }
  113. FSTDocumentKeySet *FSTTestDocKeySet(NSArray<FSTDocumentKey *> *keys) {
  114. FSTDocumentKeySet *result = [FSTDocumentKeySet keySet];
  115. for (FSTDocumentKey *key in keys) {
  116. result = [result setByAddingObject:key];
  117. }
  118. return result;
  119. }
  120. FSTSnapshotVersion *FSTTestVersion(FSTTestSnapshotVersion versionMicroseconds) {
  121. int64_t seconds = versionMicroseconds / kMicrosPerSec;
  122. int32_t nanos = (int32_t)(versionMicroseconds % kMicrosPerSec) * kMillisPerSec;
  123. FIRTimestamp *timestamp = [[FIRTimestamp alloc] initWithSeconds:seconds nanoseconds:nanos];
  124. return [FSTSnapshotVersion versionWithTimestamp:timestamp];
  125. }
  126. FSTDocument *FSTTestDoc(NSString *path,
  127. FSTTestSnapshotVersion version,
  128. NSDictionary<NSString *, id> *data,
  129. BOOL hasMutations) {
  130. FSTDocumentKey *key = FSTTestDocKey(path);
  131. return [FSTDocument documentWithData:FSTTestObjectValue(data)
  132. key:key
  133. version:FSTTestVersion(version)
  134. hasLocalMutations:hasMutations];
  135. }
  136. FSTDeletedDocument *FSTTestDeletedDoc(NSString *path, FSTTestSnapshotVersion version) {
  137. FSTDocumentKey *key = FSTTestDocKey(path);
  138. return [FSTDeletedDocument documentWithKey:key version:FSTTestVersion(version)];
  139. }
  140. FSTDocumentKeyReference *FSTTestRef(const absl::string_view projectID,
  141. const absl::string_view database,
  142. NSString *path) {
  143. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  144. static std::list<DatabaseId> database_ids;
  145. database_ids.emplace_back(projectID, database);
  146. return [[FSTDocumentKeyReference alloc] initWithKey:FSTTestDocKey(path)
  147. databaseID:&database_ids.back()];
  148. }
  149. FSTQuery *FSTTestQuery(const absl::string_view path) {
  150. return [FSTQuery queryWithPath:testutil::Resource(path)];
  151. }
  152. id<FSTFilter> FSTTestFilter(const absl::string_view field, NSString *opString, id value) {
  153. const FieldPath path = testutil::Field(field);
  154. FSTRelationFilterOperator op;
  155. if ([opString isEqualToString:@"<"]) {
  156. op = FSTRelationFilterOperatorLessThan;
  157. } else if ([opString isEqualToString:@"<="]) {
  158. op = FSTRelationFilterOperatorLessThanOrEqual;
  159. } else if ([opString isEqualToString:@"=="]) {
  160. op = FSTRelationFilterOperatorEqual;
  161. } else if ([opString isEqualToString:@">="]) {
  162. op = FSTRelationFilterOperatorGreaterThanOrEqual;
  163. } else if ([opString isEqualToString:@">"]) {
  164. op = FSTRelationFilterOperatorGreaterThan;
  165. } else {
  166. FSTCFail(@"Unsupported operator type: %@", opString);
  167. }
  168. FSTFieldValue *data = FSTTestFieldValue(value);
  169. if ([data isEqual:[FSTDoubleValue nanValue]]) {
  170. FSTCAssert(op == FSTRelationFilterOperatorEqual, @"Must use == with NAN.");
  171. return [[FSTNanFilter alloc] initWithField:path];
  172. } else if ([data isEqual:[FSTNullValue nullValue]]) {
  173. FSTCAssert(op == FSTRelationFilterOperatorEqual, @"Must use == with Null.");
  174. return [[FSTNullFilter alloc] initWithField:path];
  175. } else {
  176. return [FSTRelationFilter filterWithField:path filterOperator:op value:data];
  177. }
  178. }
  179. FSTSortOrder *FSTTestOrderBy(const absl::string_view field, NSString *direction) {
  180. const FieldPath path = testutil::Field(field);
  181. BOOL ascending;
  182. if ([direction isEqualToString:@"asc"]) {
  183. ascending = YES;
  184. } else if ([direction isEqualToString:@"desc"]) {
  185. ascending = NO;
  186. } else {
  187. FSTCFail(@"Unsupported direction: %@", direction);
  188. }
  189. return [FSTSortOrder sortOrderWithFieldPath:path ascending:ascending];
  190. }
  191. NSComparator FSTTestDocComparator(const absl::string_view fieldPath) {
  192. FSTQuery *query = [FSTTestQuery("docs")
  193. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field(fieldPath)
  194. ascending:YES]];
  195. return [query comparator];
  196. }
  197. FSTDocumentSet *FSTTestDocSet(NSComparator comp, NSArray<FSTDocument *> *docs) {
  198. FSTDocumentSet *docSet = [FSTDocumentSet documentSetWithComparator:comp];
  199. for (FSTDocument *doc in docs) {
  200. docSet = [docSet documentSetByAddingDocument:doc];
  201. }
  202. return docSet;
  203. }
  204. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  205. return [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(path)
  206. value:FSTTestObjectValue(values)
  207. precondition:[FSTPrecondition none]];
  208. }
  209. FSTPatchMutation *FSTTestPatchMutation(const absl::string_view path,
  210. NSDictionary<NSString *, id> *values,
  211. const std::vector<FieldPath> &updateMask) {
  212. BOOL merge = !updateMask.empty();
  213. __block FSTObjectValue *objectValue = [FSTObjectValue objectValue];
  214. __block std::vector<FieldPath> fieldMaskPaths{};
  215. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  216. const FieldPath path = testutil::Field(util::MakeStringView(key));
  217. fieldMaskPaths.push_back(path);
  218. if (![value isEqual:kDeleteSentinel]) {
  219. FSTFieldValue *parsedValue = FSTTestFieldValue(value);
  220. objectValue = [objectValue objectBySettingValue:parsedValue forPath:path];
  221. }
  222. }];
  223. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:testutil::Resource(path)];
  224. FSTFieldMask *mask = [[FSTFieldMask alloc] initWithFields:merge ? updateMask : fieldMaskPaths];
  225. return [[FSTPatchMutation alloc] initWithKey:key
  226. fieldMask:mask
  227. value:objectValue
  228. precondition:[FSTPrecondition preconditionWithExists:YES]];
  229. }
  230. // For now this only creates TransformMutations with server timestamps.
  231. FSTTransformMutation *FSTTestTransformMutation(NSString *path,
  232. NSArray<NSString *> *serverTimestampFields) {
  233. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:testutil::Resource(util::MakeStringView(path))];
  234. NSMutableArray<FSTFieldTransform *> *fieldTransforms = [NSMutableArray array];
  235. for (NSString *field in serverTimestampFields) {
  236. const FieldPath fieldPath = testutil::Field(util::MakeStringView(field));
  237. id<FSTTransformOperation> transformOp = [FSTServerTimestampTransform serverTimestampTransform];
  238. FSTFieldTransform *transform =
  239. [[FSTFieldTransform alloc] initWithPath:fieldPath transform:transformOp];
  240. [fieldTransforms addObject:transform];
  241. }
  242. return [[FSTTransformMutation alloc] initWithKey:key fieldTransforms:fieldTransforms];
  243. }
  244. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path) {
  245. return [[FSTDeleteMutation alloc] initWithKey:FSTTestDocKey(path)
  246. precondition:[FSTPrecondition none]];
  247. }
  248. FSTMaybeDocumentDictionary *FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs) {
  249. FSTMaybeDocumentDictionary *updates = [FSTMaybeDocumentDictionary maybeDocumentDictionary];
  250. for (FSTMaybeDocument *doc in docs) {
  251. updates = [updates dictionaryBySettingObject:doc forKey:doc.key];
  252. }
  253. return updates;
  254. }
  255. FSTViewSnapshot *_Nullable FSTTestApplyChanges(FSTView *view,
  256. NSArray<FSTMaybeDocument *> *docs,
  257. FSTTargetChange *_Nullable targetChange) {
  258. return [view applyChangesToDocuments:[view computeChangesWithDocuments:FSTTestDocUpdates(docs)]
  259. targetChange:targetChange]
  260. .snapshot;
  261. }
  262. FSTRemoteEvent *FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
  263. NSArray<NSNumber *> *updatedInTargets,
  264. NSArray<NSNumber *> *removedFromTargets) {
  265. FSTDocumentWatchChange *change =
  266. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:updatedInTargets
  267. removedTargetIDs:removedFromTargets
  268. documentKey:doc.key
  269. document:doc];
  270. NSMutableDictionary<NSNumber *, FSTQueryData *> *listens = [NSMutableDictionary dictionary];
  271. FSTQueryData *dummyQueryData = [FSTQueryData alloc];
  272. for (NSNumber *targetID in updatedInTargets) {
  273. listens[targetID] = dummyQueryData;
  274. }
  275. for (NSNumber *targetID in removedFromTargets) {
  276. listens[targetID] = dummyQueryData;
  277. }
  278. NSMutableDictionary<NSNumber *, NSNumber *> *pending = [NSMutableDictionary dictionary];
  279. FSTWatchChangeAggregator *aggregator =
  280. [[FSTWatchChangeAggregator alloc] initWithSnapshotVersion:doc.version
  281. listenTargets:listens
  282. pendingTargetResponses:pending];
  283. [aggregator addWatchChange:change];
  284. return [aggregator remoteEvent];
  285. }
  286. /** Creates a resume token to match the given snapshot version. */
  287. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion snapshotVersion) {
  288. if (snapshotVersion == 0) {
  289. return nil;
  290. }
  291. NSString *snapshotString = [NSString stringWithFormat:@"snapshot-%" PRId64, snapshotVersion];
  292. return [snapshotString dataUsingEncoding:NSUTF8StringEncoding];
  293. }
  294. FSTLocalViewChanges *FSTTestViewChanges(FSTQuery *query,
  295. NSArray<NSString *> *addedKeys,
  296. NSArray<NSString *> *removedKeys) {
  297. FSTDocumentKeySet *added = [FSTDocumentKeySet keySet];
  298. for (NSString *keyPath in addedKeys) {
  299. FSTDocumentKey *key = FSTTestDocKey(keyPath);
  300. added = [added setByAddingObject:key];
  301. }
  302. FSTDocumentKeySet *removed = [FSTDocumentKeySet keySet];
  303. for (NSString *keyPath in removedKeys) {
  304. FSTDocumentKey *key = FSTTestDocKey(keyPath);
  305. removed = [removed setByAddingObject:key];
  306. }
  307. return [FSTLocalViewChanges changesForQuery:query addedKeys:added removedKeys:removed];
  308. }
  309. NS_ASSUME_NONNULL_END