FSTHelpers.h 16 KB

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