FSTHelpers.h 16 KB

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