FSTHelpers.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 <FirebaseFirestore/FIRTimestamp.h>
  20. #include <cinttypes>
  21. #include <list>
  22. #include <map>
  23. #include <utility>
  24. #include <vector>
  25. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  26. #import "Firestore/Source/API/FSTUserDataConverter.h"
  27. #import "Firestore/Source/Core/FSTQuery.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. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  40. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  41. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  42. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  43. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  44. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  45. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  46. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  47. #include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
  48. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  49. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  50. #include "absl/memory/memory.h"
  51. namespace util = firebase::firestore::util;
  52. namespace testutil = firebase::firestore::testutil;
  53. using firebase::firestore::model::DatabaseId;
  54. using firebase::firestore::model::DocumentKey;
  55. using firebase::firestore::model::FieldMask;
  56. using firebase::firestore::model::FieldPath;
  57. using firebase::firestore::model::FieldTransform;
  58. using firebase::firestore::model::FieldValue;
  59. using firebase::firestore::model::Precondition;
  60. using firebase::firestore::model::ResourcePath;
  61. using firebase::firestore::model::ServerTimestampTransform;
  62. using firebase::firestore::model::TransformOperation;
  63. using firebase::firestore::model::DocumentKeySet;
  64. NS_ASSUME_NONNULL_BEGIN
  65. /** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
  66. static NSString *const kDeleteSentinel = @"<DELETE>";
  67. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  68. NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  69. return [FIRTimestamp timestampWithDate:date];
  70. }
  71. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  72. NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  73. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  74. }
  75. NSData *FSTTestData(int bytes, ...) {
  76. va_list args;
  77. va_start(args, bytes); /* Initialize the argument list. */
  78. NSMutableData *data = [NSMutableData data];
  79. int next = bytes;
  80. while (next >= 0) {
  81. uint8_t byte = (uint8_t)next;
  82. [data appendBytes:&byte length:1];
  83. next = va_arg(args, int);
  84. }
  85. va_end(args);
  86. return [data copy];
  87. }
  88. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  89. return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
  90. }
  91. NSDateComponents *FSTTestDateComponents(
  92. int year, int month, int day, int hour, int minute, int second) {
  93. NSDateComponents *comps = [[NSDateComponents alloc] init];
  94. comps.year = year;
  95. comps.month = month;
  96. comps.day = day;
  97. comps.hour = hour;
  98. comps.minute = minute;
  99. comps.second = second;
  100. // Force time zone to UTC to avoid these values changing due to daylight saving.
  101. comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  102. return comps;
  103. }
  104. FSTUserDataConverter *FSTTestUserDataConverter() {
  105. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  106. static DatabaseId database_id{"project", DatabaseId::kDefault};
  107. FSTUserDataConverter *converter =
  108. [[FSTUserDataConverter alloc] initWithDatabaseID:&database_id
  109. preConverter:^id _Nullable(id _Nullable input) {
  110. return input;
  111. }];
  112. return converter;
  113. }
  114. FSTFieldValue *FSTTestFieldValue(id _Nullable value) {
  115. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  116. // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  117. // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  118. return [converter parsedQueryValue:value];
  119. }
  120. FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  121. FSTFieldValue *wrapped = FSTTestFieldValue(data);
  122. HARD_ASSERT([wrapped isKindOfClass:[FSTObjectValue class]], "Unsupported value: %s", data);
  123. return (FSTObjectValue *)wrapped;
  124. }
  125. FSTDocumentKey *FSTTestDocKey(NSString *path) {
  126. return [FSTDocumentKey keyWithPathString:path];
  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:testutil::Version(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:testutil::Version(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 if ([opString isEqualToString:@"array_contains"]) {
  169. op = FSTRelationFilterOperatorArrayContains;
  170. } else {
  171. HARD_FAIL("Unsupported operator type: %s", opString);
  172. }
  173. FSTFieldValue *data = FSTTestFieldValue(value);
  174. if ([data isEqual:[FSTDoubleValue nanValue]]) {
  175. HARD_ASSERT(op == FSTRelationFilterOperatorEqual, "Must use == with NAN.");
  176. return [[FSTNanFilter alloc] initWithField:path];
  177. } else if ([data isEqual:[FSTNullValue nullValue]]) {
  178. HARD_ASSERT(op == FSTRelationFilterOperatorEqual, "Must use == with Null.");
  179. return [[FSTNullFilter alloc] initWithField:path];
  180. } else {
  181. return [FSTRelationFilter filterWithField:path filterOperator:op value:data];
  182. }
  183. }
  184. FSTSortOrder *FSTTestOrderBy(const absl::string_view field, NSString *direction) {
  185. const FieldPath path = testutil::Field(field);
  186. BOOL ascending;
  187. if ([direction isEqualToString:@"asc"]) {
  188. ascending = YES;
  189. } else if ([direction isEqualToString:@"desc"]) {
  190. ascending = NO;
  191. } else {
  192. HARD_FAIL("Unsupported direction: %s", direction);
  193. }
  194. return [FSTSortOrder sortOrderWithFieldPath:path ascending:ascending];
  195. }
  196. NSComparator FSTTestDocComparator(const absl::string_view fieldPath) {
  197. FSTQuery *query = [FSTTestQuery("docs")
  198. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field(fieldPath)
  199. ascending:YES]];
  200. return [query comparator];
  201. }
  202. FSTDocumentSet *FSTTestDocSet(NSComparator comp, NSArray<FSTDocument *> *docs) {
  203. FSTDocumentSet *docSet = [FSTDocumentSet documentSetWithComparator:comp];
  204. for (FSTDocument *doc in docs) {
  205. docSet = [docSet documentSetByAddingDocument:doc];
  206. }
  207. return docSet;
  208. }
  209. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  210. return [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(path)
  211. value:FSTTestObjectValue(values)
  212. precondition:Precondition::None()];
  213. }
  214. FSTPatchMutation *FSTTestPatchMutation(const absl::string_view path,
  215. NSDictionary<NSString *, id> *values,
  216. const std::vector<FieldPath> &updateMask) {
  217. BOOL merge = !updateMask.empty();
  218. __block FSTObjectValue *objectValue = [FSTObjectValue objectValue];
  219. __block std::vector<FieldPath> fieldMaskPaths;
  220. [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  221. const FieldPath path = testutil::Field(util::MakeStringView(key));
  222. fieldMaskPaths.push_back(path);
  223. if (![value isEqual:kDeleteSentinel]) {
  224. FSTFieldValue *parsedValue = FSTTestFieldValue(value);
  225. objectValue = [objectValue objectBySettingValue:parsedValue forPath:path];
  226. }
  227. }];
  228. DocumentKey key = testutil::Key(path);
  229. FieldMask mask(merge ? updateMask : fieldMaskPaths);
  230. return [[FSTPatchMutation alloc] initWithKey:key
  231. fieldMask:mask
  232. value:objectValue
  233. precondition:Precondition::Exists(true)];
  234. }
  235. FSTTransformMutation *FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data) {
  236. FSTDocumentKey *key = [FSTDocumentKey keyWithPath:testutil::Resource(util::MakeStringView(path))];
  237. FSTUserDataConverter *converter = FSTTestUserDataConverter();
  238. FSTParsedUpdateData *result = [converter parsedUpdateData:data];
  239. HARD_ASSERT(result.data.value.count == 0,
  240. "FSTTestTransformMutation() only expects transforms; no other data");
  241. return [[FSTTransformMutation alloc] initWithKey:key
  242. fieldTransforms:std::move(result.fieldTransforms)];
  243. }
  244. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path) {
  245. return
  246. [[FSTDeleteMutation alloc] initWithKey:FSTTestDocKey(path) precondition:Precondition::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. DocumentKeySet added;
  298. for (NSString *keyPath in addedKeys) {
  299. added = added.insert(testutil::Key(util::MakeStringView(keyPath)));
  300. }
  301. DocumentKeySet removed;
  302. for (NSString *keyPath in removedKeys) {
  303. removed = removed.insert(testutil::Key(util::MakeStringView(keyPath)));
  304. }
  305. return [FSTLocalViewChanges changesForQuery:query
  306. addedKeys:std::move(added)
  307. removedKeys:std::move(removed)];
  308. }
  309. NS_ASSUME_NONNULL_END