FSTHelpers.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 FSTLocalViewChanges;
  33. @class FSTPatchMutation;
  34. @class FSTQuery;
  35. @class FSTRemoteEvent;
  36. @class FSTSetMutation;
  37. @class FSTSortOrder;
  38. @class FSTTargetChange;
  39. @class FIRTimestamp;
  40. @class FSTTransformMutation;
  41. @class FSTView;
  42. @class FSTViewSnapshot;
  43. @class FSTObjectValue;
  44. @protocol FSTFilter;
  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. /**
  154. * Creates an FSTTestTargetMetadataProvider that behaves as if there's an established listen for
  155. * each of the given targets, where each target has not seen any previous document.
  156. *
  157. * Internally this means that the `remoteKeysForTarget` callback for these targets will return an
  158. * empty set of document keys and that the provided targets will be returned as active from the
  159. * `queryDataForTarget` target.
  160. */
  161. + (instancetype)providerWithEmptyResultForKey:(firebase::firestore::model::DocumentKey)documentKey
  162. targets:(NSArray<FSTBoxedTargetID *> *)targets;
  163. /** Sets or replaces the local state for the provided query data. */
  164. - (void)setSyncedKeys:(firebase::firestore::model::DocumentKeySet)keys
  165. forQueryData:(FSTQueryData *)queryData;
  166. @end
  167. /** Creates a new FIRTimestamp from components. Note that year, month, and day are all one-based. */
  168. FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second);
  169. /** Creates a new NSDate from components. Note that year, month, and day are all one-based. */
  170. NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second);
  171. /**
  172. * Creates a new NSData from the var args of bytes, must be terminated with a negative byte
  173. */
  174. NSData *FSTTestData(int bytes, ...);
  175. // Note that FIRGeoPoint is a model class in addition to an API class, so we put this helper here
  176. // instead of FSTAPIHelpers.h
  177. /** Creates a new GeoPoint from the latitude and longitude values */
  178. FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude);
  179. /**
  180. * Creates a new NSDateComponents from components. Note that year, month, and day are all
  181. * one-based.
  182. */
  183. NSDateComponents *FSTTestDateComponents(
  184. int year, int month, int day, int hour, int minute, int second);
  185. /** Wraps a plain value into an FSTFieldValue instance. */
  186. FSTFieldValue *FSTTestFieldValue(id _Nullable value);
  187. /** Wraps a NSDictionary value into an FSTObjectValue instance. */
  188. FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data);
  189. /** A convenience method for creating document keys for tests. */
  190. FSTDocumentKey *FSTTestDocKey(NSString *path);
  191. /** Allow tests to just use an int literal for versions. */
  192. typedef int64_t FSTTestSnapshotVersion;
  193. /** A convenience method for creating docs for tests. */
  194. FSTDocument *FSTTestDoc(const absl::string_view path,
  195. FSTTestSnapshotVersion version,
  196. NSDictionary<NSString *, id> *data,
  197. BOOL hasMutations);
  198. /** A convenience method for creating deleted docs for tests. */
  199. FSTDeletedDocument *FSTTestDeletedDoc(const absl::string_view path, FSTTestSnapshotVersion version);
  200. /**
  201. * A convenience method for creating a document reference from a path string.
  202. */
  203. FSTDocumentKeyReference *FSTTestRef(const absl::string_view projectID,
  204. const absl::string_view databaseID,
  205. NSString *path);
  206. /** A convenience method for creating a query for the given path (without any other filters). */
  207. FSTQuery *FSTTestQuery(const absl::string_view path);
  208. /**
  209. * A convenience method to create a FSTFilter using a string representation for both field
  210. * and operator (<, <=, ==, >=, >, array_contains).
  211. */
  212. id<FSTFilter> FSTTestFilter(const absl::string_view field, NSString *op, id value);
  213. /** A convenience method for creating sort orders. */
  214. FSTSortOrder *FSTTestOrderBy(const absl::string_view field, NSString *direction);
  215. /**
  216. * Creates an NSComparator that will compare FSTDocuments by the given fieldPath string then by
  217. * key.
  218. */
  219. NSComparator FSTTestDocComparator(const absl::string_view fieldPath);
  220. /**
  221. * Creates a FSTDocumentSet based on the given comparator, initially containing the given
  222. * documents.
  223. */
  224. FSTDocumentSet *FSTTestDocSet(NSComparator comp, NSArray<FSTDocument *> *docs);
  225. /** Computes changes to the view with the docs and then applies them and returns the snapshot. */
  226. FSTViewSnapshot *_Nullable FSTTestApplyChanges(FSTView *view,
  227. NSArray<FSTMaybeDocument *> *docs,
  228. FSTTargetChange *_Nullable targetChange);
  229. /** Creates a set mutation for the document key at the given path. */
  230. FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values);
  231. /** Creates a patch mutation for the document key at the given path. */
  232. FSTPatchMutation *FSTTestPatchMutation(
  233. const absl::string_view path,
  234. NSDictionary<NSString *, id> *values,
  235. const std::vector<firebase::firestore::model::FieldPath> &updateMask);
  236. /**
  237. * Creates a FSTTransformMutation by parsing any FIRFieldValue sentinels in the provided data. The
  238. * data is expected to use dotted-notation for nested fields (i.e.
  239. * @{ @"foo.bar": [FIRFieldValue ...] } and must not contain any non-sentinel data.
  240. */
  241. FSTTransformMutation *FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data);
  242. /** Creates a delete mutation for the document key at the given path. */
  243. FSTDeleteMutation *FSTTestDeleteMutation(NSString *path);
  244. /** Converts a list of documents to a sorted map. */
  245. FSTMaybeDocumentDictionary *FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs);
  246. /** Creates a remote event that inserts a new document. */
  247. FSTRemoteEvent *FSTTestAddedRemoteEvent(FSTMaybeDocument *doc, NSArray<NSNumber *> *addedToTargets);
  248. /** Creates a remote event with changes to a document. */
  249. FSTRemoteEvent *FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
  250. NSArray<NSNumber *> *updatedInTargets,
  251. NSArray<NSNumber *> *removedFromTargets);
  252. /** Creates a test view changes. */
  253. FSTLocalViewChanges *FSTTestViewChanges(FSTQuery *query,
  254. NSArray<NSString *> *addedKeys,
  255. NSArray<NSString *> *removedKeys);
  256. /** Creates a test target change that acks all 'docs' and marks the target as CURRENT */
  257. FSTTargetChange *FSTTestTargetChangeAckDocuments(firebase::firestore::model::DocumentKeySet docs);
  258. /** Creates a test target change that marks the target as CURRENT */
  259. FSTTargetChange *FSTTestTargetChangeMarkCurrent();
  260. /** Creates a test target change. */
  261. FSTTargetChange *FSTTestTargetChange(firebase::firestore::model::DocumentKeySet added,
  262. firebase::firestore::model::DocumentKeySet modified,
  263. firebase::firestore::model::DocumentKeySet removed,
  264. NSData *resumeToken,
  265. BOOL current);
  266. /** Creates a resume token to match the given snapshot version. */
  267. NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion watchSnapshot);
  268. #if __cplusplus
  269. } // extern "C"
  270. #endif
  271. NS_ASSUME_NONNULL_END