FSTSerializerBetaTests.mm 37 KB

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