FSTHelpers.h 16 KB

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