FSTHelpers.mm 15 KB

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