FSTHelpers.mm 15 KB

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