FSTHelpers.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 <Foundation/Foundation.h>
  17. #include <vector>
  18. #import "Firestore/Source/Core/FSTTypes.h"
  19. #import "Firestore/Source/Model/FSTDocumentDictionary.h"
  20. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  21. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  22. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  23. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  24. #include "absl/strings/string_view.h"
  25. @class FIRGeoPoint;
  26. @class FSTDeleteMutation;
  27. @class FSTDeletedDocument;
  28. @class FSTDocument;
  29. @class FSTDocumentKeyReference;
  30. @class FSTDocumentSet;
  31. @class FSTFieldValue;
  32. @class FSTFilter;
  33. @class FSTLocalViewChanges;
  34. @class FSTPatchMutation;
  35. @class FSTQuery;
  36. @class FSTRemoteEvent;
  37. @class FSTSetMutation;
  38. @class FSTSortOrder;
  39. @class FSTTargetChange;
  40. @class FIRTimestamp;
  41. @class FSTTransformMutation;
  42. @class FSTView;
  43. @class FSTViewSnapshot;
  44. @class FSTObjectValue;
  45. NS_ASSUME_NONNULL_BEGIN
  46. #if __cplusplus
  47. extern "C" {
  48. #endif
  49. #define FSTAssertIsKindOfClass(value, classType) \
  50. do { \
  51. XCTAssertEqualObjects([value class], [classType class]); \
  52. } while (0);
  53. /**
  54. * Asserts that the given NSSet of FSTDocumentKeys contains exactly the given expected keys.
  55. * This is a macro instead of a method so that the failure shows up on the right line.
  56. *
  57. * @param actualSet An NSSet of FSTDocumentKeys.
  58. * @param expectedArray A sorted array of keys that actualSet must be equal to (after converting
  59. * to an array and sorting).
  60. */
  61. #define FSTAssertEqualSets(actualSet, expectedArray) \
  62. do { \
  63. NSArray<FSTDocumentKey *> *actual = [(actualSet)allObjects]; \
  64. actual = [actual sortedArrayUsingSelector:@selector(compare:)]; \
  65. XCTAssertEqualObjects(actual, (expectedArray)); \
  66. } while (0)
  67. /**
  68. * Takes an array of "equality group" arrays and asserts that the compare: selector returns the
  69. * same as compare: on the indexes of the "equality groups" (NSOrderedSame for items in the same
  70. * group).
  71. */
  72. #define FSTAssertComparisons(values) \
  73. do { \
  74. for (NSUInteger i = 0; i < [values count]; i++) { \
  75. for (id left in values[i]) { \
  76. for (NSUInteger j = 0; j < [values count]; j++) { \
  77. for (id right in values[j]) { \
  78. NSComparisonResult expected = [@(i) compare:@(j)]; \
  79. NSComparisonResult result = [left compare:right]; \
  80. NSComparisonResult inverseResult = [right compare:left]; \
  81. XCTAssertEqual(result, expected, @"comparing %@ with %@ at (%lu, %lu)", left, right, \
  82. i, j); \
  83. XCTAssertEqual(inverseResult, -expected, @"comparing %@ with %@ at (%lu, %lu)", right, \
  84. left, j, i); \
  85. } \
  86. } \
  87. } \
  88. } \
  89. } while (0)
  90. /**
  91. * Takes an array of "equality group" arrays and asserts that the isEqual: selector returns TRUE
  92. * if-and-only-if items are in the same group.
  93. *
  94. * Additionally checks that the hash: selector returns the same value for items in the same group.
  95. */
  96. #define FSTAssertEqualityGroups(values) \
  97. do { \
  98. for (NSUInteger i = 0; i < [values count]; i++) { \
  99. for (id left in values[i]) { \
  100. for (NSUInteger j = 0; j < [values count]; j++) { \
  101. for (id right in values[j]) { \
  102. if (i == j) { \
  103. XCTAssertEqualObjects(left, right); \
  104. XCTAssertEqual([left hash], [right hash], @"comparing hash of %@ with hash of %@", \
  105. left, right); \
  106. } else { \
  107. XCTAssertNotEqualObjects(left, right); \
  108. } \
  109. } \
  110. } \
  111. } \
  112. } \
  113. } while (0)
  114. static NSString *kExceptionPrefix = @"FIRESTORE INTERNAL ASSERTION FAILED: ";
  115. // Remove possible exception-prefix.
  116. inline NSString *FSTRemoveExceptionPrefix(NSString *exception) {
  117. if ([exception hasPrefix:kExceptionPrefix]) {
  118. return [exception substringFromIndex:kExceptionPrefix.length];
  119. } else {
  120. return exception;
  121. }
  122. }
  123. // Helper for validating API exceptions.
  124. #define FSTAssertThrows(expression, exceptionReason, ...) \
  125. do { \
  126. BOOL didThrow = NO; \
  127. @try { \
  128. (void)(expression); \
  129. } @catch (NSException * exception) { \
  130. didThrow = YES; \
  131. XCTAssertEqualObjects(FSTRemoveExceptionPrefix(exception.reason), \
  132. FSTRemoveExceptionPrefix(exceptionReason)); \
  133. } \
  134. XCTAssertTrue(didThrow, ##__VA_ARGS__); \
  135. } while (0)
  136. /**
  137. * An implementation of FSTTargetMetadataProvider that provides controlled access to the
  138. * `FSTTargetMetadataProvider` callbacks. Any target accessed via these callbacks must be
  139. * registered beforehand via the factory methods or via `setSyncedKeys:forQueryData:`.
  140. */
  141. @interface FSTTestTargetMetadataProvider : NSObject <FSTTargetMetadataProvider>
  142. /**
  143. * Creates an FSTTestTargetMetadataProvider that behaves as if there's an established listen for
  144. * each of the given targets, where each target has previously seen query results containing just
  145. * the given documentKey.
  146. *
  147. * Internally this means that the `remoteKeysForTarget` callback for these targets will return just
  148. * the documentKey and that the provided targets will be returned as active from the
  149. * `queryDataForTarget` target.
  150. */
  151. + (instancetype)providerWithSingleResultForKey:(firebase::firestore::model::DocumentKey)documentKey
  152. targets:(NSArray<FSTBoxedTargetID *> *)targets;
  153. + (instancetype)providerWithSingleResultForKey:(firebase::firestore::model::DocumentKey)documentKey
  154. listenTargets:(NSArray<FSTBoxedTargetID *> *)listenTargets
  155. limboTargets:(NSArray<FSTBoxedTargetID *> *)limboTargets;
  156. /**
  157. * Creates an FSTTestTargetMetadataProvider that behaves as if there's an established listen for
  158. * each of the given targets, where each target has not seen any previous document.
  159. *
  160. * Internally this means that the `remoteKeysForTarget` callback for these targets will return an
  161. * empty set of document keys and that the provided targets will be returned as active from the
  162. * `queryDataForTarget` target.
  163. */
  164. + (instancetype)providerWithEmptyResultForKey:(firebase::firestore::model::DocumentKey)documentKey
  165. targets:(NSArray<FSTBoxedTargetID *> *)targets;
  166. /** Sets or replaces the local state for the provided query data. */
  167. - (void)setSyncedKeys:(firebase::firestore::model::DocumentKeySet)keys
  168. forQueryData:(FSTQueryData *)queryData;
  169. @end
  170. /** Creates a new FIRTimestamp from components. Note that year, month, and day are all one-based. */
  171. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second);
  172. /** Creates a new NSDate from components. Note that year, month, and day are all one-based. */
  173. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second);
  174. /**
  175. * Creates a new NSData from the var args of bytes, must be terminated with a negative byte
  176. */
  177. NSData *FSTTestData(int bytes, ...);
  178. // Note that FIRGeoPoint is a model class in addition to an API class, so we put this helper here
  179. // instead of FSTAPIHelpers.h
  180. /** Creates a new GeoPoint from the latitude and longitude values */
  181. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude);
  182. /**
  183. * Creates a new NSDateComponents from components. Note that year, month, and day are all
  184. * one-based.
  185. */
  186. NSDateComponents *FSTTestDateComponents(
  187. int year, int month, int day, int hour, int minute, int second);
  188. /** Wraps a plain value into an FSTFieldValue instance. */
  189. FSTFieldValue *FSTTestFieldValue(id _Nullable value);
  190. /** Wraps a NSDictionary value into an FSTObjectValue instance. */
  191. FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data);
  192. /** A convenience method for creating document keys for tests. */
  193. FSTDocumentKey *FSTTestDocKey(NSString *path);
  194. /** Allow tests to just use an int literal for versions. */
  195. typedef int64_t FSTTestSnapshotVersion;
  196. /** A convenience method for creating docs for tests. */
  197. FSTDocument *FSTTestDoc(const absl::string_view path,
  198. FSTTestSnapshotVersion version,
  199. NSDictionary<NSString *, id> *data,
  200. BOOL hasMutations);
  201. /** A convenience method for creating deleted docs for tests. */
  202. FSTDeletedDocument *FSTTestDeletedDoc(const absl::string_view path, FSTTestSnapshotVersion version);
  203. /**
  204. * A convenience method for creating a document reference from a path string.
  205. */
  206. FSTDocumentKeyReference *FSTTestRef(const absl::string_view projectID,
  207. const absl::string_view databaseID,
  208. NSString *path);
  209. /** A convenience method for creating a query for the given path (without any other filters). */
  210. FSTQuery *FSTTestQuery(const absl::string_view path);
  211. /**
  212. * A convenience method to create a FSTFilter using a string representation for both field
  213. * and operator (<, <=, ==, >=, >, array_contains).
  214. */
  215. FSTFilter *FSTTestFilter(const absl::string_view field, NSString *op, id value);
  216. /** A convenience method for creating sort orders. */
  217. FSTSortOrder *FSTTestOrderBy(const absl::string_view field, NSString *direction);
  218. /**
  219. * Creates an NSComparator that will compare FSTDocuments by the given fieldPath string then by
  220. * key.
  221. */
  222. NSComparator FSTTestDocComparator(const absl::string_view fieldPath);
  223. /**
  224. * Creates a FSTDocumentSet based on the given comparator, initially containing the given
  225. * documents.
  226. */
  227. FSTDocumentSet *FSTTestDocSet(NSComparator comp, NSArray<FSTDocument *> *docs);
  228. /** Computes changes to the view with the docs and then applies them and returns the snapshot. */
  229. FSTViewSnapshot *_Nullable FSTTestApplyChanges(FSTView *view,
  230. NSArray<FSTMaybeDocument *> *docs,
  231. FSTTargetChange *_Nullable targetChange);
  232. /** Creates a set mutation for the document key at the given path. */
  233. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values);
  234. /** Creates a patch mutation for the document key at the given path. */
  235. FSTPatchMutation *FSTTestPatchMutation(
  236. const absl::string_view path,
  237. NSDictionary<NSString *, id> *values,
  238. const std::vector<firebase::firestore::model::FieldPath> &updateMask);
  239. /**
  240. * Creates a FSTTransformMutation by parsing any FIRFieldValue sentinels in the provided data. The
  241. * data is expected to use dotted-notation for nested fields (i.e.
  242. * @{ @"foo.bar": [FIRFieldValue ...] } and must not contain any non-sentinel data.
  243. */
  244. FSTTransformMutation *FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data);
  245. /** Creates a delete mutation for the document key at the given path. */
  246. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path);
  247. /** Converts a list of documents to a sorted map. */
  248. FSTMaybeDocumentDictionary *FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs);
  249. /** Creates a remote event that inserts a new document. */
  250. FSTRemoteEvent *FSTTestAddedRemoteEvent(FSTMaybeDocument *doc, NSArray<NSNumber *> *addedToTargets);
  251. /** Creates a remote event with changes to a document. */
  252. FSTRemoteEvent *FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
  253. NSArray<NSNumber *> *updatedInTargets,
  254. NSArray<NSNumber *> *removedFromTargets);
  255. /** Creates a remote event with changes to a document. Allows for identifying limbo targets */
  256. FSTRemoteEvent *FSTTestUpdateRemoteEventWithLimboTargets(FSTMaybeDocument *doc,
  257. NSArray<NSNumber *> *updatedInTargets,
  258. NSArray<NSNumber *> *removedFromTargets,
  259. NSArray<NSNumber *> *limboTargets);
  260. /** Creates a test view changes. */
  261. FSTLocalViewChanges *FSTTestViewChanges(FSTTargetID targetID,
  262. NSArray<NSString *> *addedKeys,
  263. NSArray<NSString *> *removedKeys);
  264. /** Creates a test target change that acks all 'docs' and marks the target as CURRENT */
  265. FSTTargetChange *FSTTestTargetChangeAckDocuments(firebase::firestore::model::DocumentKeySet docs);
  266. /** Creates a test target change that marks the target as CURRENT */
  267. FSTTargetChange *FSTTestTargetChangeMarkCurrent();
  268. /** Creates a test target change. */
  269. FSTTargetChange *FSTTestTargetChange(firebase::firestore::model::DocumentKeySet added,
  270. firebase::firestore::model::DocumentKeySet modified,
  271. firebase::firestore::model::DocumentKeySet removed,
  272. NSData *resumeToken,
  273. BOOL current);
  274. /** Creates a resume token to match the given snapshot version. */
  275. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion watchSnapshot);
  276. #if __cplusplus
  277. } // extern "C"
  278. #endif
  279. NS_ASSUME_NONNULL_END