FSTHelpers.h 16 KB

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