FSTSerializerBetaTests.mm 37 KB

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