FSTHelpers.h 15 KB

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