FSTHelpers.h 16 KB

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