FSTHelpers.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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/document_key.h"
  42. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  43. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  44. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  45. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  46. namespace util = firebase::firestore::util;
  47. namespace testutil = firebase::firestore::testutil;
  48. using firebase::firestore::model::DatabaseId;
  49. using firebase::firestore::model::DocumentKey;
  50. using firebase::firestore::model::FieldPath;
  51. using firebase::firestore::model::FieldValue;
  52. using firebase::firestore::model::ResourcePath;
  53. NS_ASSUME_NONNULL_BEGIN
  54. /** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
  55. static NSString *const kDeleteSentinel = @"<DELETE>";
  56. static const int kMicrosPerSec = 1000000;
  57. static const int kMillisPerSec = 1000;
  58. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  59. NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  60. return [FIRTimestamp timestampWithDate:date];
  61. }
  62. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  63. NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  64. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  65. }
  66. NSData *FSTTestData(int bytes, ...) {
  67. va_list args;
  68. va_start(args, bytes); /* Initialize the argument list. */
  69. NSMutableData *data = [NSMutableData data];
  70. int next = bytes;
  71. while (next >= 0) {
  72. uint8_t byte = (uint8_t)next;
  73. [data appendBytes:&byte length:1];
  74. next = va_arg(args, int);
  75. }
  76. va_end(args);
  77. return [data copy];
  78. }
  79. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  80. return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
  81. }
  82. NSDateComponents *FSTTestDateComponents(
  83. int year, int month, int day, int hour, int minute, int second) {
  84. NSDateComponents *comps = [[NSDateComponents alloc] init];
  85. comps.year = year;
  86. comps.month = month;
  87. comps.day = day;
  88. comps.hour = hour;
  89. comps.minute = minute;
  90. comps.second = second;
  91. // Force time zone to UTC to avoid these values changing due to daylight saving.
  92. comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  93. return comps;
  94. }
  95. FSTFieldValue *FSTTestFieldValue(id _Nullable value) {
  96. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  97. static DatabaseId database_id{"project", DatabaseId::kDefault};
  98. FSTUserDataConverter *converter =
  99. [[FSTUserDataConverter alloc] initWithDatabaseID:&database_id
  100. preConverter:^id _Nullable(id _Nullable input) {
  101. return input;
  102. }];
  103. // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  104. // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  105. return [converter parsedQueryValue:value];
  106. }
  107. FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  108. FSTFieldValue *wrapped = FSTTestFieldValue(data);
  109. FSTCAssert([wrapped isKindOfClass:[FSTObjectValue class]], @"Unsupported value: %@", data);
  110. return (FSTObjectValue *)wrapped;
  111. }
  112. FSTDocumentKey *FSTTestDocKey(NSString *path) {
  113. return [FSTDocumentKey keyWithPathString:path];
  114. }
  115. FSTDocumentKeySet *FSTTestDocKeySet(NSArray<FSTDocumentKey *> *keys) {
  116. FSTDocumentKeySet *result = [FSTDocumentKeySet keySet];
  117. for (FSTDocumentKey *key in keys) {
  118. result = [result setByAddingObject:key];
  119. }
  120. return result;
  121. }
  122. FSTSnapshotVersion *FSTTestVersion(FSTTestSnapshotVersion versionMicroseconds) {
  123. int64_t seconds = versionMicroseconds / kMicrosPerSec;
  124. int32_t nanos = (int32_t)(versionMicroseconds % kMicrosPerSec) * kMillisPerSec;
  125. FIRTimestamp *timestamp = [[FIRTimestamp alloc] initWithSeconds:seconds nanoseconds:nanos];
  126. return [FSTSnapshotVersion versionWithTimestamp:timestamp];
  127. }
  128. FSTDocument *FSTTestDoc(const absl::string_view path,
  129. FSTTestSnapshotVersion version,
  130. NSDictionary<NSString *, id> *data,
  131. BOOL hasMutations) {
  132. DocumentKey key = testutil::Key(path);
  133. return [FSTDocument documentWithData:FSTTestObjectValue(data)
  134. key:key
  135. version:FSTTestVersion(version)
  136. hasLocalMutations:hasMutations];
  137. }
  138. FSTDeletedDocument *FSTTestDeletedDoc(const absl::string_view path,
  139. FSTTestSnapshotVersion version) {
  140. DocumentKey key = testutil::Key(path);
  141. return [FSTDeletedDocument documentWithKey:key version:FSTTestVersion(version)];
  142. }
  143. FSTDocumentKeyReference *FSTTestRef(const absl::string_view projectID,
  144. const absl::string_view database,
  145. NSString *path) {
  146. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  147. static std::list<DatabaseId> database_ids;
  148. database_ids.emplace_back(projectID, database);
  149. return [[FSTDocumentKeyReference alloc] initWithKey:FSTTestDocKey(path)
  150. databaseID:&database_ids.back()];
  151. }
  152. FSTQuery *FSTTestQuery(const absl::string_view path) {
  153. return [FSTQuery queryWithPath:testutil::Resource(path)];
  154. }
  155. id<FSTFilter> FSTTestFilter(const absl::string_view field, NSString *opString, id value) {
  156. const FieldPath path = testutil::Field(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(const absl::string_view field, NSString *direction) {
  183. const FieldPath path = testutil::Field(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(const absl::string_view fieldPath) {
  195. FSTQuery *query = [FSTTestQuery("docs")
  196. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field(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(const absl::string_view path,
  213. NSDictionary<NSString *, id> *values,
  214. const std::vector<FieldPath> &updateMask) {
  215. BOOL merge = !updateMask.empty();
  216. __block FSTObjectValue *objectValue = [FSTObjectValue objectValue];
  217. __block std::vector<FieldPath> fieldMaskPaths{};
  218. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  219. const FieldPath path = testutil::Field(util::MakeStringView(key));
  220. fieldMaskPaths.push_back(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:testutil::Resource(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:testutil::Resource(util::MakeStringView(path))];
  237. NSMutableArray<FSTFieldTransform *> *fieldTransforms = [NSMutableArray array];
  238. for (NSString *field in serverTimestampFields) {
  239. const FieldPath fieldPath = testutil::Field(util::MakeStringView(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