FSTHelpers.h 16 KB

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