FSTSerializerBetaTests.mm 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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 "Firestore/Source/Remote/FSTSerializerBeta.h"
  17. #import <FirebaseFirestore/FIRFieldPath.h>
  18. #import <FirebaseFirestore/FIRFieldValue.h>
  19. #import <FirebaseFirestore/FIRFirestoreErrors.h>
  20. #import <FirebaseFirestore/FIRGeoPoint.h>
  21. #import <FirebaseFirestore/FIRTimestamp.h>
  22. #import <XCTest/XCTest.h>
  23. #include <memory>
  24. #include <vector>
  25. #import "Firestore/Protos/objc/firestore/local/MaybeDocument.pbobjc.h"
  26. #import "Firestore/Protos/objc/firestore/local/Mutation.pbobjc.h"
  27. #import "Firestore/Protos/objc/google/firestore/v1/Common.pbobjc.h"
  28. #import "Firestore/Protos/objc/google/firestore/v1/Document.pbobjc.h"
  29. #import "Firestore/Protos/objc/google/firestore/v1/Firestore.pbobjc.h"
  30. #import "Firestore/Protos/objc/google/firestore/v1/Query.pbobjc.h"
  31. #import "Firestore/Protos/objc/google/firestore/v1/Write.pbobjc.h"
  32. #import "Firestore/Protos/objc/google/rpc/Status.pbobjc.h"
  33. #import "Firestore/Protos/objc/google/type/Latlng.pbobjc.h"
  34. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  35. #import "Firestore/Source/Core/FSTQuery.h"
  36. #import "Firestore/Source/Local/FSTQueryData.h"
  37. #import "Firestore/Source/Model/FSTDocument.h"
  38. #import "Firestore/Source/Model/FSTDocumentKey.h"
  39. #import "Firestore/Source/Model/FSTFieldValue.h"
  40. #import "Firestore/Source/Model/FSTMutation.h"
  41. #import "Firestore/Source/Model/FSTMutationBatch.h"
  42. #import "Firestore/Example/Tests/API/FSTAPIHelpers.h"
  43. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  44. #include "Firestore/core/include/firebase/firestore/firestore_errors.h"
  45. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  46. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  47. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  48. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  49. #include "Firestore/core/src/firebase/firestore/remote/watch_change.h"
  50. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  51. #include "Firestore/core/src/firebase/firestore/util/status.h"
  52. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  53. #include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
  54. namespace testutil = firebase::firestore::testutil;
  55. namespace util = firebase::firestore::util;
  56. using firebase::Timestamp;
  57. using firebase::firestore::FirestoreErrorCode;
  58. using firebase::firestore::model::DatabaseId;
  59. using firebase::firestore::model::FieldMask;
  60. using firebase::firestore::model::FieldTransform;
  61. using firebase::firestore::model::Precondition;
  62. using firebase::firestore::model::SnapshotVersion;
  63. using firebase::firestore::remote::DocumentWatchChange;
  64. using firebase::firestore::remote::ExistenceFilterWatchChange;
  65. using firebase::firestore::remote::WatchChange;
  66. using firebase::firestore::remote::WatchTargetChange;
  67. using firebase::firestore::remote::WatchTargetChangeState;
  68. using firebase::firestore::util::Status;
  69. namespace {
  70. template <typename T>
  71. bool Equals(const WatchChange &lhs, const WatchChange &rhs) {
  72. return static_cast<const T &>(lhs) == static_cast<const T &>(rhs);
  73. }
  74. // Compares two `WatchChange`s taking into account their actual derived type.
  75. bool IsWatchChangeEqual(const WatchChange &lhs, const WatchChange &rhs) {
  76. if (lhs.type() != rhs.type()) {
  77. return false;
  78. }
  79. switch (lhs.type()) {
  80. case WatchChange::Type::Document:
  81. return Equals<DocumentWatchChange>(lhs, rhs);
  82. case WatchChange::Type::ExistenceFilter:
  83. return Equals<ExistenceFilterWatchChange>(lhs, rhs);
  84. case WatchChange::Type::TargetChange:
  85. return Equals<WatchTargetChange>(lhs, rhs);
  86. }
  87. UNREACHABLE();
  88. }
  89. } // namespace
  90. NS_ASSUME_NONNULL_BEGIN
  91. @interface FSTSerializerBeta (Test)
  92. - (GCFSValue *)encodedNull;
  93. - (GCFSValue *)encodedBool:(BOOL)value;
  94. - (GCFSValue *)encodedDouble:(double)value;
  95. - (GCFSValue *)encodedInteger:(int64_t)value;
  96. - (GCFSValue *)encodedString:(NSString *)value;
  97. - (GCFSValue *)encodedDate:(NSDate *)value;
  98. - (GCFSDocumentMask *)encodedFieldMask:(const FieldMask &)fieldMask;
  99. - (NSMutableArray<GCFSDocumentTransform_FieldTransform *> *)encodedFieldTransforms:
  100. (const std::vector<FieldTransform> &)fieldTransforms;
  101. - (GCFSStructuredQuery_Filter *)encodedRelationFilter:(FSTRelationFilter *)filter;
  102. @end
  103. @interface GCFSStructuredQuery_Order (Test)
  104. + (instancetype)messageWithProperty:(NSString *)property ascending:(BOOL)ascending;
  105. @end
  106. @implementation GCFSStructuredQuery_Order (Test)
  107. + (instancetype)messageWithProperty:(NSString *)property ascending:(BOOL)ascending {
  108. GCFSStructuredQuery_Order *order = [GCFSStructuredQuery_Order message];
  109. order.field.fieldPath = property;
  110. order.direction = ascending ? GCFSStructuredQuery_Direction_Ascending
  111. : GCFSStructuredQuery_Direction_Descending;
  112. return order;
  113. }
  114. @end
  115. @interface FSTSerializerBetaTests : XCTestCase {
  116. DatabaseId _databaseId;
  117. }
  118. @property(nonatomic, strong) FSTSerializerBeta *serializer;
  119. @end
  120. @implementation FSTSerializerBetaTests
  121. - (void)setUp {
  122. _databaseId = DatabaseId("p", "d");
  123. self.serializer = [[FSTSerializerBeta alloc] initWithDatabaseID:&_databaseId];
  124. }
  125. - (void)testEncodesNull {
  126. FSTFieldValue *model = [FSTNullValue nullValue];
  127. GCFSValue *proto = [GCFSValue message];
  128. proto.nullValue = GPBNullValue_NullValue;
  129. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_NullValue];
  130. }
  131. - (void)testEncodesBool {
  132. NSArray<NSNumber *> *examples = @[ @YES, @NO ];
  133. for (NSNumber *example in examples) {
  134. FSTFieldValue *model = FSTTestFieldValue(example);
  135. GCFSValue *proto = [GCFSValue message];
  136. proto.booleanValue = [example boolValue];
  137. [self assertRoundTripForModel:model
  138. proto:proto
  139. type:GCFSValue_ValueType_OneOfCase_BooleanValue];
  140. }
  141. }
  142. - (void)testEncodesIntegers {
  143. NSArray<NSNumber *> *examples = @[ @(LLONG_MIN), @(-100), @(-1), @0, @1, @100, @(LLONG_MAX) ];
  144. for (NSNumber *example in examples) {
  145. FSTFieldValue *model = FSTTestFieldValue(example);
  146. GCFSValue *proto = [GCFSValue message];
  147. proto.integerValue = [example longLongValue];
  148. [self assertRoundTripForModel:model
  149. proto:proto
  150. type:GCFSValue_ValueType_OneOfCase_IntegerValue];
  151. }
  152. }
  153. - (void)testEncodesDoubles {
  154. NSArray<NSNumber *> *examples = @[
  155. // normal negative numbers.
  156. @(-INFINITY), @(-DBL_MAX), @(LLONG_MIN * 1.0 - 1.0), @(-2.0), @(-1.1), @(-1.0), @(-DBL_MIN),
  157. // negative smallest subnormal, zeroes, positive smallest subnormal
  158. @(-0x1.0p-1074), @(-0.0), @(0.0), @(0x1.0p-1074),
  159. // and the rest
  160. @(DBL_MIN), @0.1, @1.1, @(LLONG_MAX * 1.0), @(DBL_MAX), @(INFINITY),
  161. // NaN.
  162. @(0.0 / 0.0)
  163. ];
  164. for (NSNumber *example in examples) {
  165. FSTFieldValue *model = FSTTestFieldValue(example);
  166. GCFSValue *proto = [GCFSValue message];
  167. proto.doubleValue = [example doubleValue];
  168. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_DoubleValue];
  169. }
  170. }
  171. - (void)testEncodesStrings {
  172. NSArray<NSString *> *examples = @[
  173. @"",
  174. @"a",
  175. @"abc def",
  176. @"æ",
  177. @"\0\ud7ff\ue000\uffff",
  178. @"(╯°□°)╯︵ ┻━┻",
  179. ];
  180. for (NSString *example in examples) {
  181. FSTFieldValue *model = FSTTestFieldValue(example);
  182. GCFSValue *proto = [GCFSValue message];
  183. proto.stringValue = example;
  184. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_StringValue];
  185. }
  186. }
  187. - (void)testEncodesDates {
  188. NSDateComponents *dateWithNanos = FSTTestDateComponents(2016, 1, 2, 10, 20, 50);
  189. dateWithNanos.nanosecond = 500000000;
  190. NSArray<NSDate *> *examples = @[
  191. [[NSCalendar currentCalendar] dateFromComponents:dateWithNanos],
  192. FSTTestDate(2016, 6, 17, 10, 50, 15)
  193. ];
  194. GCFSValue *timestamp1 = [GCFSValue message];
  195. timestamp1.timestampValue.seconds = 1451730050;
  196. timestamp1.timestampValue.nanos = 500000000;
  197. GCFSValue *timestamp2 = [GCFSValue message];
  198. timestamp2.timestampValue.seconds = 1466160615;
  199. timestamp2.timestampValue.nanos = 0;
  200. NSArray<GCFSValue *> *expectedTimestamps = @[ timestamp1, timestamp2 ];
  201. for (NSUInteger i = 0; i < [examples count]; i++) {
  202. [self assertRoundTripForModel:FSTTestFieldValue(examples[i])
  203. proto:expectedTimestamps[i]
  204. type:GCFSValue_ValueType_OneOfCase_TimestampValue];
  205. }
  206. }
  207. - (void)testEncodesGeoPoints {
  208. NSArray<FIRGeoPoint *> *examples =
  209. @[ FSTTestGeoPoint(0, 0), FSTTestGeoPoint(1.24, 4.56), FSTTestGeoPoint(-90, 180) ];
  210. for (FIRGeoPoint *example in examples) {
  211. FSTFieldValue *model = FSTTestFieldValue(example);
  212. GCFSValue *proto = [GCFSValue message];
  213. proto.geoPointValue = [GTPLatLng message];
  214. proto.geoPointValue.latitude = example.latitude;
  215. proto.geoPointValue.longitude = example.longitude;
  216. [self assertRoundTripForModel:model
  217. proto:proto
  218. type:GCFSValue_ValueType_OneOfCase_GeoPointValue];
  219. }
  220. }
  221. - (void)testEncodesBlobs {
  222. NSArray<NSData *> *examples = @[
  223. FSTTestData(-1),
  224. FSTTestData(0, -1),
  225. FSTTestData(0, 1, 2, -1),
  226. FSTTestData(255, -1),
  227. FSTTestData(0, 1, 255, -1),
  228. ];
  229. for (NSData *example in examples) {
  230. FSTFieldValue *model = FSTTestFieldValue(example);
  231. GCFSValue *proto = [GCFSValue message];
  232. proto.bytesValue = example;
  233. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_BytesValue];
  234. }
  235. }
  236. - (void)testEncodesResourceNames {
  237. FSTDocumentKeyReference *reference = FSTTestRef("project", DatabaseId::kDefault, @"foo/bar");
  238. _databaseId = DatabaseId("project", DatabaseId::kDefault);
  239. GCFSValue *proto = [GCFSValue message];
  240. proto.referenceValue = @"projects/project/databases/(default)/documents/foo/bar";
  241. [self assertRoundTripForModel:FSTTestFieldValue(reference)
  242. proto:proto
  243. type:GCFSValue_ValueType_OneOfCase_ReferenceValue];
  244. }
  245. - (void)testEncodesArrays {
  246. FSTFieldValue *model = FSTTestFieldValue(@[ @YES, @"foo" ]);
  247. GCFSValue *proto = [GCFSValue message];
  248. [proto.arrayValue.valuesArray addObjectsFromArray:@[
  249. [self.serializer encodedBool:YES], [self.serializer encodedString:@"foo"]
  250. ]];
  251. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_ArrayValue];
  252. }
  253. - (void)testEncodesEmptyMap {
  254. FSTFieldValue *model = [FSTObjectValue objectValue];
  255. GCFSValue *proto = [GCFSValue message];
  256. proto.mapValue = [GCFSMapValue message];
  257. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_MapValue];
  258. }
  259. - (void)testEncodesNestedObjects {
  260. FSTFieldValue *model = FSTTestFieldValue(@{
  261. @"b" : @YES,
  262. @"d" : @(DBL_MAX),
  263. @"i" : @1,
  264. @"n" : [NSNull null],
  265. @"s" : @"foo",
  266. @"a" : @[ @2, @"bar", @{@"b" : @NO} ],
  267. @"o" : @{
  268. @"d" : @100,
  269. @"nested" : @{@"e" : @(LLONG_MIN)},
  270. },
  271. });
  272. GCFSValue *innerObject = [GCFSValue message];
  273. innerObject.mapValue.fields[@"b"] = [self.serializer encodedBool:NO];
  274. GCFSValue *middleArray = [GCFSValue message];
  275. [middleArray.arrayValue.valuesArray addObjectsFromArray:@[
  276. [self.serializer encodedInteger:2], [self.serializer encodedString:@"bar"], innerObject
  277. ]];
  278. innerObject = [GCFSValue message];
  279. innerObject.mapValue.fields[@"e"] = [self.serializer encodedInteger:LLONG_MIN];
  280. GCFSValue *middleObject = [GCFSValue message];
  281. [middleObject.mapValue.fields addEntriesFromDictionary:@{
  282. @"d" : [self.serializer encodedInteger:100],
  283. @"nested" : innerObject
  284. }];
  285. GCFSValue *proto = [GCFSValue message];
  286. [proto.mapValue.fields addEntriesFromDictionary:@{
  287. @"b" : [self.serializer encodedBool:YES],
  288. @"d" : [self.serializer encodedDouble:DBL_MAX],
  289. @"i" : [self.serializer encodedInteger:1],
  290. @"n" : [self.serializer encodedNull],
  291. @"s" : [self.serializer encodedString:@"foo"],
  292. @"a" : middleArray,
  293. @"o" : middleObject
  294. }];
  295. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_MapValue];
  296. }
  297. - (void)assertRoundTripForModel:(FSTFieldValue *)model
  298. proto:(GCFSValue *)value
  299. type:(GCFSValue_ValueType_OneOfCase)type {
  300. GCFSValue *actualProto = [self.serializer encodedFieldValue:model];
  301. XCTAssertEqual(actualProto.valueTypeOneOfCase, type);
  302. XCTAssertEqualObjects(actualProto, value);
  303. FSTFieldValue *actualModel = [self.serializer decodedFieldValue:value];
  304. XCTAssertEqualObjects(actualModel, model);
  305. }
  306. - (void)testEncodesSetMutation {
  307. FSTSetMutation *mutation = FSTTestSetMutation(@"docs/1", @{@"a" : @"b", @"num" : @1});
  308. GCFSWrite *proto = [GCFSWrite message];
  309. proto.update = [self.serializer encodedDocumentWithFields:mutation.value key:mutation.key];
  310. [self assertRoundTripForMutation:mutation proto:proto];
  311. }
  312. - (void)testEncodesPatchMutation {
  313. FSTPatchMutation *mutation = FSTTestPatchMutation(
  314. "docs/1", @{@"a" : @"b", @"num" : @1, @"some.de\\\\ep.th\\ing'" : @2}, {});
  315. GCFSWrite *proto = [GCFSWrite message];
  316. proto.update = [self.serializer encodedDocumentWithFields:mutation.value key:mutation.key];
  317. proto.updateMask = [self.serializer encodedFieldMask:mutation.fieldMask];
  318. proto.currentDocument.exists = YES;
  319. [self assertRoundTripForMutation:mutation proto:proto];
  320. }
  321. - (void)testEncodesDeleteMutation {
  322. FSTDeleteMutation *mutation = FSTTestDeleteMutation(@"docs/1");
  323. GCFSWrite *proto = [GCFSWrite message];
  324. proto.delete_p = @"projects/p/databases/d/documents/docs/1";
  325. [self assertRoundTripForMutation:mutation proto:proto];
  326. }
  327. - (void)testEncodesServerTimestampTransformMutation {
  328. FSTTransformMutation *mutation = FSTTestTransformMutation(@"docs/1", @{
  329. @"a" : [FIRFieldValue fieldValueForServerTimestamp],
  330. @"bar.baz" : [FIRFieldValue fieldValueForServerTimestamp]
  331. });
  332. GCFSWrite *proto = [GCFSWrite message];
  333. proto.transform = [GCFSDocumentTransform message];
  334. proto.transform.document = [self.serializer encodedDocumentKey:mutation.key];
  335. proto.transform.fieldTransformsArray =
  336. [self.serializer encodedFieldTransforms:mutation.fieldTransforms];
  337. proto.currentDocument.exists = YES;
  338. [self assertRoundTripForMutation:mutation proto:proto];
  339. }
  340. - (void)testEncodesArrayTransformMutations {
  341. FSTTransformMutation *mutation = FSTTestTransformMutation(@"docs/1", @{
  342. @"a" : [FIRFieldValue fieldValueForArrayUnion:@[ @"a", @2 ]],
  343. @"bar.baz" : [FIRFieldValue fieldValueForArrayRemove:@[ @{@"x" : @1} ]]
  344. });
  345. GCFSWrite *proto = [GCFSWrite message];
  346. proto.transform = [GCFSDocumentTransform message];
  347. proto.transform.document = [self.serializer encodedDocumentKey:mutation.key];
  348. GCFSDocumentTransform_FieldTransform *arrayUnion = [GCFSDocumentTransform_FieldTransform message];
  349. arrayUnion.fieldPath = @"a";
  350. arrayUnion.appendMissingElements = [GCFSArrayValue message];
  351. NSMutableArray *unionElements = arrayUnion.appendMissingElements.valuesArray;
  352. [unionElements addObject:[self.serializer encodedFieldValue:FSTTestFieldValue(@"a")]];
  353. [unionElements addObject:[self.serializer encodedFieldValue:FSTTestFieldValue(@2)]];
  354. [proto.transform.fieldTransformsArray addObject:arrayUnion];
  355. GCFSDocumentTransform_FieldTransform *arrayRemove =
  356. [GCFSDocumentTransform_FieldTransform message];
  357. arrayRemove.fieldPath = @"bar.baz";
  358. arrayRemove.removeAllFromArray_p = [GCFSArrayValue message];
  359. NSMutableArray *removeElements = arrayRemove.removeAllFromArray_p.valuesArray;
  360. [removeElements addObject:[self.serializer encodedFieldValue:FSTTestFieldValue(@{@"x" : @1})]];
  361. [proto.transform.fieldTransformsArray addObject:arrayRemove];
  362. proto.currentDocument.exists = YES;
  363. [self assertRoundTripForMutation:mutation proto:proto];
  364. }
  365. - (void)testEncodesSetMutationWithPrecondition {
  366. FSTSetMutation *mutation =
  367. [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(@"foo/bar")
  368. value:FSTTestObjectValue(@{@"a" : @"b", @"num" : @1})
  369. precondition:Precondition::UpdateTime(testutil::Version(4))];
  370. GCFSWrite *proto = [GCFSWrite message];
  371. proto.update = [self.serializer encodedDocumentWithFields:mutation.value key:mutation.key];
  372. proto.currentDocument.updateTime = [self.serializer encodedTimestamp:Timestamp{0, 4000}];
  373. [self assertRoundTripForMutation:mutation proto:proto];
  374. }
  375. - (void)assertRoundTripForMutation:(FSTMutation *)mutation proto:(GCFSWrite *)proto {
  376. GCFSWrite *actualProto = [self.serializer encodedMutation:mutation];
  377. XCTAssertEqualObjects(actualProto, proto);
  378. FSTMutation *actualMutation = [self.serializer decodedMutation:proto];
  379. XCTAssertEqualObjects(actualMutation, mutation);
  380. }
  381. - (void)testDecodesMutationResult {
  382. SnapshotVersion commitVersion = testutil::Version(3000);
  383. SnapshotVersion updateVersion = testutil::Version(4000);
  384. GCFSWriteResult *proto = [GCFSWriteResult message];
  385. proto.updateTime = [self.serializer encodedTimestamp:updateVersion.timestamp()];
  386. [proto.transformResultsArray addObject:[self.serializer encodedString:@"result"]];
  387. FSTMutationResult *result = [self.serializer decodedMutationResult:proto
  388. commitVersion:commitVersion];
  389. XCTAssertEqual(result.version, updateVersion);
  390. XCTAssertEqualObjects(result.transformResults, @[ [FSTStringValue stringValue:@"result"] ]);
  391. }
  392. - (void)testDecodesDeleteMutationResult {
  393. GCFSWriteResult *proto = [GCFSWriteResult message];
  394. SnapshotVersion commitVersion = testutil::Version(4000);
  395. FSTMutationResult *result = [self.serializer decodedMutationResult:proto
  396. commitVersion:commitVersion];
  397. XCTAssertEqual(result.version, commitVersion);
  398. XCTAssertEqual(result.transformResults.count, 0);
  399. }
  400. - (void)testRoundTripSpecialFieldNames {
  401. FSTMutation *set = FSTTestSetMutation(@"collection/key", @{
  402. @"field" : [NSString stringWithFormat:@"field %d", 1],
  403. @"field.dot" : @2,
  404. @"field\\slash" : @3
  405. });
  406. GCFSWrite *encoded = [self.serializer encodedMutation:set];
  407. FSTMutation *decoded = [self.serializer decodedMutation:encoded];
  408. XCTAssertEqualObjects(set, decoded);
  409. }
  410. - (void)testEncodesListenRequestLabels {
  411. FSTQuery *query = FSTTestQuery("collection/key");
  412. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  413. targetID:2
  414. listenSequenceNumber:3
  415. purpose:FSTQueryPurposeListen];
  416. NSDictionary<NSString *, NSString *> *result =
  417. [self.serializer encodedListenRequestLabelsForQueryData:queryData];
  418. XCTAssertNil(result);
  419. queryData = [[FSTQueryData alloc] initWithQuery:query
  420. targetID:2
  421. listenSequenceNumber:3
  422. purpose:FSTQueryPurposeLimboResolution];
  423. result = [self.serializer encodedListenRequestLabelsForQueryData:queryData];
  424. XCTAssertEqualObjects(result, @{@"goog-listen-tags" : @"limbo-document"});
  425. queryData = [[FSTQueryData alloc] initWithQuery:query
  426. targetID:2
  427. listenSequenceNumber:3
  428. purpose:FSTQueryPurposeExistenceFilterMismatch];
  429. result = [self.serializer encodedListenRequestLabelsForQueryData:queryData];
  430. XCTAssertEqualObjects(result, @{@"goog-listen-tags" : @"existence-filter-mismatch"});
  431. }
  432. - (void)testEncodesRelationFilter {
  433. FSTRelationFilter *input = (FSTRelationFilter *)FSTTestFilter("item.part.top", @"==", @"food");
  434. GCFSStructuredQuery_Filter *actual = [self.serializer encodedRelationFilter:input];
  435. GCFSStructuredQuery_Filter *expected = [GCFSStructuredQuery_Filter message];
  436. GCFSStructuredQuery_FieldFilter *prop = expected.fieldFilter;
  437. prop.field.fieldPath = @"item.part.top";
  438. prop.op = GCFSStructuredQuery_FieldFilter_Operator_Equal;
  439. prop.value.stringValue = @"food";
  440. XCTAssertEqualObjects(actual, expected);
  441. }
  442. - (void)testEncodesArrayContainsFilter {
  443. FSTRelationFilter *input =
  444. (FSTRelationFilter *)FSTTestFilter("item.tags", @"array_contains", @"food");
  445. GCFSStructuredQuery_Filter *actual = [self.serializer encodedRelationFilter:input];
  446. GCFSStructuredQuery_Filter *expected = [GCFSStructuredQuery_Filter message];
  447. GCFSStructuredQuery_FieldFilter *prop = expected.fieldFilter;
  448. prop.field.fieldPath = @"item.tags";
  449. prop.op = GCFSStructuredQuery_FieldFilter_Operator_ArrayContains;
  450. prop.value.stringValue = @"food";
  451. XCTAssertEqualObjects(actual, expected);
  452. }
  453. #pragma mark - encodedQuery
  454. - (void)testEncodesFirstLevelKeyQueries {
  455. FSTQuery *q = FSTTestQuery("docs/1");
  456. FSTQueryData *model = [self queryDataForQuery:q];
  457. GCFSTarget *expected = [GCFSTarget message];
  458. [expected.documents.documentsArray addObject:@"projects/p/databases/d/documents/docs/1"];
  459. expected.targetId = 1;
  460. [self assertRoundTripForQueryData:model proto:expected];
  461. }
  462. - (void)testEncodesFirstLevelAncestorQueries {
  463. FSTQuery *q = FSTTestQuery("messages");
  464. FSTQueryData *model = [self queryDataForQuery:q];
  465. GCFSTarget *expected = [GCFSTarget message];
  466. expected.query.parent = @"projects/p/databases/d/documents";
  467. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  468. from.collectionId = @"messages";
  469. [expected.query.structuredQuery.fromArray addObject:from];
  470. [expected.query.structuredQuery.orderByArray
  471. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  472. expected.targetId = 1;
  473. [self assertRoundTripForQueryData:model proto:expected];
  474. }
  475. - (void)testEncodesNestedAncestorQueries {
  476. FSTQuery *q = FSTTestQuery("rooms/1/messages/10/attachments");
  477. FSTQueryData *model = [self queryDataForQuery:q];
  478. GCFSTarget *expected = [GCFSTarget message];
  479. expected.query.parent = @"projects/p/databases/d/documents/rooms/1/messages/10";
  480. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  481. from.collectionId = @"attachments";
  482. [expected.query.structuredQuery.fromArray addObject:from];
  483. [expected.query.structuredQuery.orderByArray
  484. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  485. expected.targetId = 1;
  486. [self assertRoundTripForQueryData:model proto:expected];
  487. }
  488. - (void)testEncodesSingleFiltersAtFirstLevelCollections {
  489. FSTQuery *q = [FSTTestQuery("docs") queryByAddingFilter:FSTTestFilter("prop", @"<", @(42))];
  490. FSTQueryData *model = [self queryDataForQuery:q];
  491. GCFSTarget *expected = [GCFSTarget message];
  492. expected.query.parent = @"projects/p/databases/d/documents";
  493. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  494. from.collectionId = @"docs";
  495. [expected.query.structuredQuery.fromArray addObject:from];
  496. [expected.query.structuredQuery.orderByArray
  497. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:YES]];
  498. [expected.query.structuredQuery.orderByArray
  499. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  500. GCFSStructuredQuery_FieldFilter *filter = expected.query.structuredQuery.where.fieldFilter;
  501. filter.field.fieldPath = @"prop";
  502. filter.op = GCFSStructuredQuery_FieldFilter_Operator_LessThan;
  503. filter.value.integerValue = 42;
  504. expected.targetId = 1;
  505. [self assertRoundTripForQueryData:model proto:expected];
  506. }
  507. - (void)testEncodesMultipleFiltersOnDeeperCollections {
  508. FSTQuery *q = [[[FSTTestQuery("rooms/1/messages/10/attachments")
  509. queryByAddingFilter:FSTTestFilter("prop", @">=", @(42))]
  510. queryByAddingFilter:FSTTestFilter("author", @"==", @"dimond")]
  511. queryByAddingFilter:FSTTestFilter("tags", @"array_contains", @"pending")];
  512. FSTQueryData *model = [self queryDataForQuery:q];
  513. GCFSTarget *expected = [GCFSTarget message];
  514. expected.query.parent = @"projects/p/databases/d/documents/rooms/1/messages/10";
  515. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  516. from.collectionId = @"attachments";
  517. [expected.query.structuredQuery.fromArray addObject:from];
  518. GCFSStructuredQuery_Filter *filter1 = [GCFSStructuredQuery_Filter message];
  519. GCFSStructuredQuery_FieldFilter *field1 = filter1.fieldFilter;
  520. field1.field.fieldPath = @"prop";
  521. field1.op = GCFSStructuredQuery_FieldFilter_Operator_GreaterThanOrEqual;
  522. field1.value.integerValue = 42;
  523. GCFSStructuredQuery_Filter *filter2 = [GCFSStructuredQuery_Filter message];
  524. GCFSStructuredQuery_FieldFilter *field2 = filter2.fieldFilter;
  525. field2.field.fieldPath = @"author";
  526. field2.op = GCFSStructuredQuery_FieldFilter_Operator_Equal;
  527. field2.value.stringValue = @"dimond";
  528. GCFSStructuredQuery_Filter *filter3 = [GCFSStructuredQuery_Filter message];
  529. GCFSStructuredQuery_FieldFilter *field3 = filter3.fieldFilter;
  530. field3.field.fieldPath = @"tags";
  531. field3.op = GCFSStructuredQuery_FieldFilter_Operator_ArrayContains;
  532. field3.value.stringValue = @"pending";
  533. GCFSStructuredQuery_CompositeFilter *composite =
  534. expected.query.structuredQuery.where.compositeFilter;
  535. composite.op = GCFSStructuredQuery_CompositeFilter_Operator_And;
  536. [composite.filtersArray addObject:filter1];
  537. [composite.filtersArray addObject:filter2];
  538. [composite.filtersArray addObject:filter3];
  539. [expected.query.structuredQuery.orderByArray
  540. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:YES]];
  541. [expected.query.structuredQuery.orderByArray
  542. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  543. expected.targetId = 1;
  544. [self assertRoundTripForQueryData:model proto:expected];
  545. }
  546. - (void)testEncodesNullFilter {
  547. [self unaryFilterTestWithValue:[NSNull null]
  548. expectedUnaryOperator:GCFSStructuredQuery_UnaryFilter_Operator_IsNull];
  549. }
  550. - (void)testEncodesNanFilter {
  551. [self unaryFilterTestWithValue:@(NAN)
  552. expectedUnaryOperator:GCFSStructuredQuery_UnaryFilter_Operator_IsNan];
  553. }
  554. - (void)unaryFilterTestWithValue:(id)value
  555. expectedUnaryOperator:(GCFSStructuredQuery_UnaryFilter_Operator)op {
  556. FSTQuery *q = [FSTTestQuery("docs") queryByAddingFilter:FSTTestFilter("prop", @"==", value)];
  557. FSTQueryData *model = [self queryDataForQuery:q];
  558. GCFSTarget *expected = [GCFSTarget message];
  559. expected.query.parent = @"projects/p/databases/d/documents";
  560. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  561. from.collectionId = @"docs";
  562. [expected.query.structuredQuery.fromArray addObject:from];
  563. [expected.query.structuredQuery.orderByArray
  564. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  565. GCFSStructuredQuery_UnaryFilter *filter = expected.query.structuredQuery.where.unaryFilter;
  566. filter.field.fieldPath = @"prop";
  567. filter.op = op;
  568. expected.targetId = 1;
  569. [self assertRoundTripForQueryData:model proto:expected];
  570. }
  571. - (void)testEncodesSortOrders {
  572. FSTQuery *q = [FSTTestQuery("docs")
  573. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field("prop")
  574. ascending:YES]];
  575. FSTQueryData *model = [self queryDataForQuery:q];
  576. GCFSTarget *expected = [GCFSTarget message];
  577. expected.query.parent = @"projects/p/databases/d/documents";
  578. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  579. from.collectionId = @"docs";
  580. [expected.query.structuredQuery.fromArray addObject:from];
  581. [expected.query.structuredQuery.orderByArray
  582. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:YES]];
  583. [expected.query.structuredQuery.orderByArray
  584. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  585. expected.targetId = 1;
  586. [self assertRoundTripForQueryData:model proto:expected];
  587. }
  588. - (void)testEncodesSortOrdersDescending {
  589. FSTQuery *q = [FSTTestQuery("rooms/1/messages/10/attachments")
  590. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field("prop")
  591. ascending:NO]];
  592. FSTQueryData *model = [self queryDataForQuery:q];
  593. GCFSTarget *expected = [GCFSTarget message];
  594. expected.query.parent = @"projects/p/databases/d/documents/rooms/1/messages/10";
  595. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  596. from.collectionId = @"attachments";
  597. [expected.query.structuredQuery.fromArray addObject:from];
  598. [expected.query.structuredQuery.orderByArray
  599. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:NO]];
  600. [expected.query.structuredQuery.orderByArray
  601. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:NO]];
  602. expected.targetId = 1;
  603. [self assertRoundTripForQueryData:model proto:expected];
  604. }
  605. - (void)testEncodesLimits {
  606. FSTQuery *q = [FSTTestQuery("docs") queryBySettingLimit:26];
  607. FSTQueryData *model = [self queryDataForQuery:q];
  608. GCFSTarget *expected = [GCFSTarget message];
  609. expected.query.parent = @"projects/p/databases/d/documents";
  610. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  611. from.collectionId = @"docs";
  612. [expected.query.structuredQuery.fromArray addObject:from];
  613. [expected.query.structuredQuery.orderByArray
  614. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  615. expected.query.structuredQuery.limit.value = 26;
  616. expected.targetId = 1;
  617. [self assertRoundTripForQueryData:model proto:expected];
  618. }
  619. - (void)testEncodesResumeTokens {
  620. FSTQuery *q = FSTTestQuery("docs");
  621. FSTQueryData *model = [[FSTQueryData alloc] initWithQuery:q
  622. targetID:1
  623. listenSequenceNumber:0
  624. purpose:FSTQueryPurposeListen
  625. snapshotVersion:SnapshotVersion::None()
  626. resumeToken:FSTTestData(1, 2, 3, -1)];
  627. GCFSTarget *expected = [GCFSTarget message];
  628. expected.query.parent = @"projects/p/databases/d/documents";
  629. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  630. from.collectionId = @"docs";
  631. [expected.query.structuredQuery.fromArray addObject:from];
  632. [expected.query.structuredQuery.orderByArray
  633. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  634. expected.targetId = 1;
  635. expected.resumeToken = FSTTestData(1, 2, 3, -1);
  636. [self assertRoundTripForQueryData:model proto:expected];
  637. }
  638. - (FSTQueryData *)queryDataForQuery:(FSTQuery *)query {
  639. return [[FSTQueryData alloc] initWithQuery:query
  640. targetID:1
  641. listenSequenceNumber:0
  642. purpose:FSTQueryPurposeListen
  643. snapshotVersion:SnapshotVersion::None()
  644. resumeToken:[NSData data]];
  645. }
  646. - (void)assertRoundTripForQueryData:(FSTQueryData *)queryData proto:(GCFSTarget *)proto {
  647. // Verify that the encoded FSTQueryData matches the target.
  648. GCFSTarget *actualProto = [self.serializer encodedTarget:queryData];
  649. XCTAssertEqualObjects(actualProto, proto);
  650. // We don't have deserialization logic for full targets since they're not used for RPC
  651. // interaction, but the query deserialization only *is* used for the local store.
  652. FSTQuery *actualModel;
  653. if (proto.targetTypeOneOfCase == GCFSTarget_TargetType_OneOfCase_Query) {
  654. actualModel = [self.serializer decodedQueryFromQueryTarget:proto.query];
  655. } else {
  656. actualModel = [self.serializer decodedQueryFromDocumentsTarget:proto.documents];
  657. }
  658. XCTAssertEqualObjects(actualModel, queryData.query);
  659. }
  660. - (void)testConvertsTargetChangeWithAdded {
  661. WatchTargetChange expected{WatchTargetChangeState::Added, {1, 4}};
  662. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  663. listenResponse.targetChange.targetChangeType = GCFSTargetChange_TargetChangeType_Add;
  664. [listenResponse.targetChange.targetIdsArray addValue:1];
  665. [listenResponse.targetChange.targetIdsArray addValue:4];
  666. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  667. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  668. }
  669. - (void)testConvertsTargetChangeWithRemoved {
  670. WatchTargetChange expected{WatchTargetChangeState::Removed,
  671. {1, 4},
  672. FSTTestData(0, 1, 2, -1),
  673. Status{FirestoreErrorCode::PermissionDenied, "Error message"}};
  674. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  675. listenResponse.targetChange.targetChangeType = GCFSTargetChange_TargetChangeType_Remove;
  676. listenResponse.targetChange.cause.code = FIRFirestoreErrorCodePermissionDenied;
  677. listenResponse.targetChange.cause.message = @"Error message";
  678. listenResponse.targetChange.resumeToken = FSTTestData(0, 1, 2, -1);
  679. [listenResponse.targetChange.targetIdsArray addValue:1];
  680. [listenResponse.targetChange.targetIdsArray addValue:4];
  681. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  682. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  683. }
  684. - (void)testConvertsTargetChangeWithNoChange {
  685. WatchTargetChange expected{WatchTargetChangeState::NoChange, {1, 4}};
  686. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  687. listenResponse.targetChange.targetChangeType = GCFSTargetChange_TargetChangeType_NoChange;
  688. [listenResponse.targetChange.targetIdsArray addValue:1];
  689. [listenResponse.targetChange.targetIdsArray addValue:4];
  690. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  691. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  692. }
  693. - (void)testConvertsDocumentChangeWithTargetIds {
  694. DocumentWatchChange expected {
  695. {1, 2}, {}, FSTTestDocKey(@"coll/1"),
  696. FSTTestDoc("coll/1", 5, @{@"foo" : @"bar"}, FSTDocumentStateSynced)
  697. };
  698. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  699. listenResponse.documentChange.document.name = @"projects/p/databases/d/documents/coll/1";
  700. listenResponse.documentChange.document.updateTime.nanos = 5000;
  701. GCFSValue *fooValue = [GCFSValue message];
  702. fooValue.stringValue = @"bar";
  703. [listenResponse.documentChange.document.fields setObject:fooValue forKey:@"foo"];
  704. [listenResponse.documentChange.targetIdsArray addValue:1];
  705. [listenResponse.documentChange.targetIdsArray addValue:2];
  706. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  707. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  708. }
  709. - (void)testConvertsDocumentChangeWithRemovedTargetIds {
  710. DocumentWatchChange expected {
  711. {2}, {1}, FSTTestDocKey(@"coll/1"),
  712. FSTTestDoc("coll/1", 5, @{@"foo" : @"bar"}, FSTDocumentStateSynced)
  713. };
  714. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  715. listenResponse.documentChange.document.name = @"projects/p/databases/d/documents/coll/1";
  716. listenResponse.documentChange.document.updateTime.nanos = 5000;
  717. GCFSValue *fooValue = [GCFSValue message];
  718. fooValue.stringValue = @"bar";
  719. [listenResponse.documentChange.document.fields setObject:fooValue forKey:@"foo"];
  720. [listenResponse.documentChange.removedTargetIdsArray addValue:1];
  721. [listenResponse.documentChange.targetIdsArray addValue:2];
  722. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  723. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  724. }
  725. - (void)testConvertsDocumentChangeWithDeletions {
  726. DocumentWatchChange expected{
  727. {}, {1, 2}, FSTTestDocKey(@"coll/1"), FSTTestDeletedDoc("coll/1", 5, NO)};
  728. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  729. listenResponse.documentDelete.document = @"projects/p/databases/d/documents/coll/1";
  730. listenResponse.documentDelete.readTime.nanos = 5000;
  731. [listenResponse.documentDelete.removedTargetIdsArray addValue:1];
  732. [listenResponse.documentDelete.removedTargetIdsArray addValue:2];
  733. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  734. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  735. }
  736. - (void)testConvertsDocumentChangeWithRemoves {
  737. DocumentWatchChange expected{{}, {1, 2}, FSTTestDocKey(@"coll/1"), nil};
  738. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  739. listenResponse.documentRemove.document = @"projects/p/databases/d/documents/coll/1";
  740. [listenResponse.documentRemove.removedTargetIdsArray addValue:1];
  741. [listenResponse.documentRemove.removedTargetIdsArray addValue:2];
  742. std::unique_ptr<WatchChange> actual = [self.serializer decodedWatchChange:listenResponse];
  743. XCTAssertTrue(IsWatchChangeEqual(*actual, expected));
  744. }
  745. @end
  746. NS_ASSUME_NONNULL_END