FSTHelpers.m 14 KB

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