FSTSerializerBetaTests.mm 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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/v1beta1/Common.pbobjc.h"
  27. #import "Firestore/Protos/objc/google/firestore/v1beta1/Document.pbobjc.h"
  28. #import "Firestore/Protos/objc/google/firestore/v1beta1/Firestore.pbobjc.h"
  29. #import "Firestore/Protos/objc/google/firestore/v1beta1/Query.pbobjc.h"
  30. #import "Firestore/Protos/objc/google/firestore/v1beta1/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",
  235. @{@"b" : @NO} ],
  236. @"o" : @{
  237. @"d" : @100,
  238. @"nested" : @{@"e" : @(LLONG_MIN)},
  239. },
  240. });
  241. GCFSValue *innerObject = [GCFSValue message];
  242. innerObject.mapValue.fields[@"b"] = [self.serializer encodedBool:NO];
  243. GCFSValue *middleArray = [GCFSValue message];
  244. [middleArray.arrayValue.valuesArray addObjectsFromArray:@[
  245. [self.serializer encodedInteger:2], [self.serializer encodedString:@"bar"], innerObject
  246. ]];
  247. innerObject = [GCFSValue message];
  248. innerObject.mapValue.fields[@"e"] = [self.serializer encodedInteger:LLONG_MIN];
  249. GCFSValue *middleObject = [GCFSValue message];
  250. [middleObject.mapValue.fields addEntriesFromDictionary:@{
  251. @"d" : [self.serializer encodedInteger:100],
  252. @"nested" : innerObject
  253. }];
  254. GCFSValue *proto = [GCFSValue message];
  255. [proto.mapValue.fields addEntriesFromDictionary:@{
  256. @"b" : [self.serializer encodedBool:YES],
  257. @"d" : [self.serializer encodedDouble:DBL_MAX],
  258. @"i" : [self.serializer encodedInteger:1],
  259. @"n" : [self.serializer encodedNull],
  260. @"s" : [self.serializer encodedString:@"foo"],
  261. @"a" : middleArray,
  262. @"o" : middleObject
  263. }];
  264. [self assertRoundTripForModel:model proto:proto type:GCFSValue_ValueType_OneOfCase_MapValue];
  265. }
  266. - (void)assertRoundTripForModel:(FSTFieldValue *)model
  267. proto:(GCFSValue *)value
  268. type:(GCFSValue_ValueType_OneOfCase)type {
  269. GCFSValue *actualProto = [self.serializer encodedFieldValue:model];
  270. XCTAssertEqual(actualProto.valueTypeOneOfCase, type);
  271. XCTAssertEqualObjects(actualProto, value);
  272. FSTFieldValue *actualModel = [self.serializer decodedFieldValue:value];
  273. XCTAssertEqualObjects(actualModel, model);
  274. }
  275. - (void)testEncodesSetMutation {
  276. FSTSetMutation *mutation = FSTTestSetMutation(@"docs/1", @{@"a" : @"b", @"num" : @1});
  277. GCFSWrite *proto = [GCFSWrite message];
  278. proto.update = [self.serializer encodedDocumentWithFields:mutation.value key:mutation.key];
  279. [self assertRoundTripForMutation:mutation proto:proto];
  280. }
  281. - (void)testEncodesPatchMutation {
  282. FSTPatchMutation *mutation =
  283. FSTTestPatchMutation("docs/1",
  284. @{@"a" : @"b",
  285. @"num" : @1,
  286. @"some.de\\\\ep.th\\ing'" : @2},
  287. {});
  288. GCFSWrite *proto = [GCFSWrite message];
  289. proto.update = [self.serializer encodedDocumentWithFields:mutation.value key:mutation.key];
  290. proto.updateMask = [self.serializer encodedFieldMask:mutation.fieldMask];
  291. proto.currentDocument.exists = YES;
  292. [self assertRoundTripForMutation:mutation proto:proto];
  293. }
  294. - (void)testEncodesDeleteMutation {
  295. FSTDeleteMutation *mutation = FSTTestDeleteMutation(@"docs/1");
  296. GCFSWrite *proto = [GCFSWrite message];
  297. proto.delete_p = @"projects/p/databases/d/documents/docs/1";
  298. [self assertRoundTripForMutation:mutation proto:proto];
  299. }
  300. - (void)testEncodesServerTimestampTransformMutation {
  301. FSTTransformMutation *mutation = FSTTestTransformMutation(@"docs/1", @{
  302. @"a" : [FIRFieldValue fieldValueForServerTimestamp],
  303. @"bar.baz" : [FIRFieldValue fieldValueForServerTimestamp]
  304. });
  305. GCFSWrite *proto = [GCFSWrite message];
  306. proto.transform = [GCFSDocumentTransform message];
  307. proto.transform.document = [self.serializer encodedDocumentKey:mutation.key];
  308. proto.transform.fieldTransformsArray =
  309. [self.serializer encodedFieldTransforms:mutation.fieldTransforms];
  310. proto.currentDocument.exists = YES;
  311. [self assertRoundTripForMutation:mutation proto:proto];
  312. }
  313. - (void)testEncodesArrayTransformMutations {
  314. FSTTransformMutation *mutation = FSTTestTransformMutation(@"docs/1", @{
  315. @"a" : [FIRFieldValue fieldValueForArrayUnion:@[ @"a", @2 ]],
  316. @"bar.baz" : [FIRFieldValue fieldValueForArrayRemove:@[
  317. @{@"x" : @1}
  318. ]]
  319. });
  320. GCFSWrite *proto = [GCFSWrite message];
  321. proto.transform = [GCFSDocumentTransform message];
  322. proto.transform.document = [self.serializer encodedDocumentKey:mutation.key];
  323. GCFSDocumentTransform_FieldTransform *arrayUnion = [GCFSDocumentTransform_FieldTransform message];
  324. arrayUnion.fieldPath = @"a";
  325. arrayUnion.appendMissingElements = [GCFSArrayValue message];
  326. NSMutableArray *unionElements = arrayUnion.appendMissingElements.valuesArray;
  327. [unionElements addObject:[self.serializer encodedFieldValue:FSTTestFieldValue(@"a")]];
  328. [unionElements addObject:[self.serializer encodedFieldValue:FSTTestFieldValue(@2)]];
  329. [proto.transform.fieldTransformsArray addObject:arrayUnion];
  330. GCFSDocumentTransform_FieldTransform *arrayRemove =
  331. [GCFSDocumentTransform_FieldTransform message];
  332. arrayRemove.fieldPath = @"bar.baz";
  333. arrayRemove.removeAllFromArray_p = [GCFSArrayValue message];
  334. NSMutableArray *removeElements = arrayRemove.removeAllFromArray_p.valuesArray;
  335. [removeElements addObject:[self.serializer encodedFieldValue:FSTTestFieldValue(@{@"x" : @1})]];
  336. [proto.transform.fieldTransformsArray addObject:arrayRemove];
  337. proto.currentDocument.exists = YES;
  338. [self assertRoundTripForMutation:mutation proto:proto];
  339. }
  340. - (void)testEncodesSetMutationWithPrecondition {
  341. FSTSetMutation *mutation =
  342. [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(@"foo/bar")
  343. value:FSTTestObjectValue(
  344. @{@"a" : @"b",
  345. @"num" : @1})
  346. precondition:Precondition::UpdateTime(testutil::Version(4))];
  347. GCFSWrite *proto = [GCFSWrite message];
  348. proto.update = [self.serializer encodedDocumentWithFields:mutation.value key:mutation.key];
  349. proto.currentDocument.updateTime = [self.serializer encodedTimestamp:Timestamp{0, 4000}];
  350. [self assertRoundTripForMutation:mutation proto:proto];
  351. }
  352. - (void)assertRoundTripForMutation:(FSTMutation *)mutation proto:(GCFSWrite *)proto {
  353. GCFSWrite *actualProto = [self.serializer encodedMutation:mutation];
  354. XCTAssertEqualObjects(actualProto, proto);
  355. FSTMutation *actualMutation = [self.serializer decodedMutation:proto];
  356. XCTAssertEqualObjects(actualMutation, mutation);
  357. }
  358. - (void)testDecodesMutationResult {
  359. SnapshotVersion commitVersion = testutil::Version(3000);
  360. SnapshotVersion updateVersion = testutil::Version(4000);
  361. GCFSWriteResult *proto = [GCFSWriteResult message];
  362. proto.updateTime = [self.serializer encodedTimestamp:updateVersion.timestamp()];
  363. [proto.transformResultsArray addObject:[self.serializer encodedString:@"result"]];
  364. FSTMutationResult *result =
  365. [self.serializer decodedMutationResult:proto commitVersion:commitVersion];
  366. XCTAssertEqual(result.version, updateVersion);
  367. XCTAssertEqualObjects(result.transformResults, @[ [FSTStringValue stringValue:@"result"] ]);
  368. }
  369. - (void)testDecodesDeleteMutationResult {
  370. GCFSWriteResult *proto = [GCFSWriteResult message];
  371. SnapshotVersion commitVersion = testutil::Version(4000);
  372. FSTMutationResult *result =
  373. [self.serializer decodedMutationResult:proto commitVersion:commitVersion];
  374. XCTAssertEqual(result.version, commitVersion);
  375. XCTAssertEqual(result.transformResults.count, 0);
  376. }
  377. - (void)testRoundTripSpecialFieldNames {
  378. FSTMutation *set = FSTTestSetMutation(@"collection/key", @{
  379. @"field" : [NSString stringWithFormat:@"field %d", 1],
  380. @"field.dot" : @2,
  381. @"field\\slash" : @3
  382. });
  383. GCFSWrite *encoded = [self.serializer encodedMutation:set];
  384. FSTMutation *decoded = [self.serializer decodedMutation:encoded];
  385. XCTAssertEqualObjects(set, decoded);
  386. }
  387. - (void)testEncodesListenRequestLabels {
  388. FSTQuery *query = FSTTestQuery("collection/key");
  389. FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
  390. targetID:2
  391. listenSequenceNumber:3
  392. purpose:FSTQueryPurposeListen];
  393. NSDictionary<NSString *, NSString *> *result =
  394. [self.serializer encodedListenRequestLabelsForQueryData:queryData];
  395. XCTAssertNil(result);
  396. queryData = [[FSTQueryData alloc] initWithQuery:query
  397. targetID:2
  398. listenSequenceNumber:3
  399. purpose:FSTQueryPurposeLimboResolution];
  400. result = [self.serializer encodedListenRequestLabelsForQueryData:queryData];
  401. XCTAssertEqualObjects(result, @{@"goog-listen-tags" : @"limbo-document"});
  402. queryData = [[FSTQueryData alloc] initWithQuery:query
  403. targetID:2
  404. listenSequenceNumber:3
  405. purpose:FSTQueryPurposeExistenceFilterMismatch];
  406. result = [self.serializer encodedListenRequestLabelsForQueryData:queryData];
  407. XCTAssertEqualObjects(result, @{@"goog-listen-tags" : @"existence-filter-mismatch"});
  408. }
  409. - (void)testEncodesRelationFilter {
  410. FSTRelationFilter *input = (FSTRelationFilter *)FSTTestFilter("item.part.top", @"==", @"food");
  411. GCFSStructuredQuery_Filter *actual = [self.serializer encodedRelationFilter:input];
  412. GCFSStructuredQuery_Filter *expected = [GCFSStructuredQuery_Filter message];
  413. GCFSStructuredQuery_FieldFilter *prop = expected.fieldFilter;
  414. prop.field.fieldPath = @"item.part.top";
  415. prop.op = GCFSStructuredQuery_FieldFilter_Operator_Equal;
  416. prop.value.stringValue = @"food";
  417. XCTAssertEqualObjects(actual, expected);
  418. }
  419. - (void)testEncodesArrayContainsFilter {
  420. FSTRelationFilter *input =
  421. (FSTRelationFilter *)FSTTestFilter("item.tags", @"array_contains", @"food");
  422. GCFSStructuredQuery_Filter *actual = [self.serializer encodedRelationFilter:input];
  423. GCFSStructuredQuery_Filter *expected = [GCFSStructuredQuery_Filter message];
  424. GCFSStructuredQuery_FieldFilter *prop = expected.fieldFilter;
  425. prop.field.fieldPath = @"item.tags";
  426. prop.op = GCFSStructuredQuery_FieldFilter_Operator_ArrayContains;
  427. prop.value.stringValue = @"food";
  428. XCTAssertEqualObjects(actual, expected);
  429. }
  430. #pragma mark - encodedQuery
  431. - (void)testEncodesFirstLevelKeyQueries {
  432. FSTQuery *q = FSTTestQuery("docs/1");
  433. FSTQueryData *model = [self queryDataForQuery:q];
  434. GCFSTarget *expected = [GCFSTarget message];
  435. [expected.documents.documentsArray addObject:@"projects/p/databases/d/documents/docs/1"];
  436. expected.targetId = 1;
  437. [self assertRoundTripForQueryData:model proto:expected];
  438. }
  439. - (void)testEncodesFirstLevelAncestorQueries {
  440. FSTQuery *q = FSTTestQuery("messages");
  441. FSTQueryData *model = [self queryDataForQuery:q];
  442. GCFSTarget *expected = [GCFSTarget message];
  443. expected.query.parent = @"projects/p/databases/d";
  444. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  445. from.collectionId = @"messages";
  446. [expected.query.structuredQuery.fromArray addObject:from];
  447. [expected.query.structuredQuery.orderByArray
  448. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  449. expected.targetId = 1;
  450. [self assertRoundTripForQueryData:model proto:expected];
  451. }
  452. - (void)testEncodesNestedAncestorQueries {
  453. FSTQuery *q = FSTTestQuery("rooms/1/messages/10/attachments");
  454. FSTQueryData *model = [self queryDataForQuery:q];
  455. GCFSTarget *expected = [GCFSTarget message];
  456. expected.query.parent = @"projects/p/databases/d/documents/rooms/1/messages/10";
  457. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  458. from.collectionId = @"attachments";
  459. [expected.query.structuredQuery.fromArray addObject:from];
  460. [expected.query.structuredQuery.orderByArray
  461. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  462. expected.targetId = 1;
  463. [self assertRoundTripForQueryData:model proto:expected];
  464. }
  465. - (void)testEncodesSingleFiltersAtFirstLevelCollections {
  466. FSTQuery *q = [FSTTestQuery("docs") queryByAddingFilter:FSTTestFilter("prop", @"<", @(42))];
  467. FSTQueryData *model = [self queryDataForQuery:q];
  468. GCFSTarget *expected = [GCFSTarget message];
  469. expected.query.parent = @"projects/p/databases/d";
  470. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  471. from.collectionId = @"docs";
  472. [expected.query.structuredQuery.fromArray addObject:from];
  473. [expected.query.structuredQuery.orderByArray
  474. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:YES]];
  475. [expected.query.structuredQuery.orderByArray
  476. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  477. GCFSStructuredQuery_FieldFilter *filter = expected.query.structuredQuery.where.fieldFilter;
  478. filter.field.fieldPath = @"prop";
  479. filter.op = GCFSStructuredQuery_FieldFilter_Operator_LessThan;
  480. filter.value.integerValue = 42;
  481. expected.targetId = 1;
  482. [self assertRoundTripForQueryData:model proto:expected];
  483. }
  484. - (void)testEncodesMultipleFiltersOnDeeperCollections {
  485. FSTQuery *q = [[[FSTTestQuery("rooms/1/messages/10/attachments")
  486. queryByAddingFilter:FSTTestFilter("prop", @">=", @(42))]
  487. queryByAddingFilter:FSTTestFilter("author", @"==", @"dimond")]
  488. queryByAddingFilter:FSTTestFilter("tags", @"array_contains", @"pending")];
  489. FSTQueryData *model = [self queryDataForQuery:q];
  490. GCFSTarget *expected = [GCFSTarget message];
  491. expected.query.parent = @"projects/p/databases/d/documents/rooms/1/messages/10";
  492. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  493. from.collectionId = @"attachments";
  494. [expected.query.structuredQuery.fromArray addObject:from];
  495. GCFSStructuredQuery_Filter *filter1 = [GCFSStructuredQuery_Filter message];
  496. GCFSStructuredQuery_FieldFilter *field1 = filter1.fieldFilter;
  497. field1.field.fieldPath = @"prop";
  498. field1.op = GCFSStructuredQuery_FieldFilter_Operator_GreaterThanOrEqual;
  499. field1.value.integerValue = 42;
  500. GCFSStructuredQuery_Filter *filter2 = [GCFSStructuredQuery_Filter message];
  501. GCFSStructuredQuery_FieldFilter *field2 = filter2.fieldFilter;
  502. field2.field.fieldPath = @"author";
  503. field2.op = GCFSStructuredQuery_FieldFilter_Operator_Equal;
  504. field2.value.stringValue = @"dimond";
  505. GCFSStructuredQuery_Filter *filter3 = [GCFSStructuredQuery_Filter message];
  506. GCFSStructuredQuery_FieldFilter *field3 = filter3.fieldFilter;
  507. field3.field.fieldPath = @"tags";
  508. field3.op = GCFSStructuredQuery_FieldFilter_Operator_ArrayContains;
  509. field3.value.stringValue = @"pending";
  510. GCFSStructuredQuery_CompositeFilter *composite =
  511. expected.query.structuredQuery.where.compositeFilter;
  512. composite.op = GCFSStructuredQuery_CompositeFilter_Operator_And;
  513. [composite.filtersArray addObject:filter1];
  514. [composite.filtersArray addObject:filter2];
  515. [composite.filtersArray addObject:filter3];
  516. [expected.query.structuredQuery.orderByArray
  517. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:YES]];
  518. [expected.query.structuredQuery.orderByArray
  519. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  520. expected.targetId = 1;
  521. [self assertRoundTripForQueryData:model proto:expected];
  522. }
  523. - (void)testEncodesNullFilter {
  524. [self unaryFilterTestWithValue:[NSNull null]
  525. expectedUnaryOperator:GCFSStructuredQuery_UnaryFilter_Operator_IsNull];
  526. }
  527. - (void)testEncodesNanFilter {
  528. [self unaryFilterTestWithValue:@(NAN)
  529. expectedUnaryOperator:GCFSStructuredQuery_UnaryFilter_Operator_IsNan];
  530. }
  531. - (void)unaryFilterTestWithValue:(id)value
  532. expectedUnaryOperator:(GCFSStructuredQuery_UnaryFilter_Operator)op {
  533. FSTQuery *q = [FSTTestQuery("docs") queryByAddingFilter:FSTTestFilter("prop", @"==", value)];
  534. FSTQueryData *model = [self queryDataForQuery:q];
  535. GCFSTarget *expected = [GCFSTarget message];
  536. expected.query.parent = @"projects/p/databases/d";
  537. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  538. from.collectionId = @"docs";
  539. [expected.query.structuredQuery.fromArray addObject:from];
  540. [expected.query.structuredQuery.orderByArray
  541. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  542. GCFSStructuredQuery_UnaryFilter *filter = expected.query.structuredQuery.where.unaryFilter;
  543. filter.field.fieldPath = @"prop";
  544. filter.op = op;
  545. expected.targetId = 1;
  546. [self assertRoundTripForQueryData:model proto:expected];
  547. }
  548. - (void)testEncodesSortOrders {
  549. FSTQuery *q = [FSTTestQuery("docs")
  550. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field("prop")
  551. ascending:YES]];
  552. FSTQueryData *model = [self queryDataForQuery:q];
  553. GCFSTarget *expected = [GCFSTarget message];
  554. expected.query.parent = @"projects/p/databases/d";
  555. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  556. from.collectionId = @"docs";
  557. [expected.query.structuredQuery.fromArray addObject:from];
  558. [expected.query.structuredQuery.orderByArray
  559. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:YES]];
  560. [expected.query.structuredQuery.orderByArray
  561. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  562. expected.targetId = 1;
  563. [self assertRoundTripForQueryData:model proto:expected];
  564. }
  565. - (void)testEncodesSortOrdersDescending {
  566. FSTQuery *q = [FSTTestQuery("rooms/1/messages/10/attachments")
  567. queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field("prop")
  568. ascending:NO]];
  569. FSTQueryData *model = [self queryDataForQuery:q];
  570. GCFSTarget *expected = [GCFSTarget message];
  571. expected.query.parent = @"projects/p/databases/d/documents/rooms/1/messages/10";
  572. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  573. from.collectionId = @"attachments";
  574. [expected.query.structuredQuery.fromArray addObject:from];
  575. [expected.query.structuredQuery.orderByArray
  576. addObject:[GCFSStructuredQuery_Order messageWithProperty:@"prop" ascending:NO]];
  577. [expected.query.structuredQuery.orderByArray
  578. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:NO]];
  579. expected.targetId = 1;
  580. [self assertRoundTripForQueryData:model proto:expected];
  581. }
  582. - (void)testEncodesLimits {
  583. FSTQuery *q = [FSTTestQuery("docs") queryBySettingLimit:26];
  584. FSTQueryData *model = [self queryDataForQuery:q];
  585. GCFSTarget *expected = [GCFSTarget message];
  586. expected.query.parent = @"projects/p/databases/d";
  587. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  588. from.collectionId = @"docs";
  589. [expected.query.structuredQuery.fromArray addObject:from];
  590. [expected.query.structuredQuery.orderByArray
  591. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  592. expected.query.structuredQuery.limit.value = 26;
  593. expected.targetId = 1;
  594. [self assertRoundTripForQueryData:model proto:expected];
  595. }
  596. - (void)testEncodesResumeTokens {
  597. FSTQuery *q = FSTTestQuery("docs");
  598. FSTQueryData *model = [[FSTQueryData alloc] initWithQuery:q
  599. targetID:1
  600. listenSequenceNumber:0
  601. purpose:FSTQueryPurposeListen
  602. snapshotVersion:SnapshotVersion::None()
  603. resumeToken:FSTTestData(1, 2, 3, -1)];
  604. GCFSTarget *expected = [GCFSTarget message];
  605. expected.query.parent = @"projects/p/databases/d";
  606. GCFSStructuredQuery_CollectionSelector *from = [GCFSStructuredQuery_CollectionSelector message];
  607. from.collectionId = @"docs";
  608. [expected.query.structuredQuery.fromArray addObject:from];
  609. [expected.query.structuredQuery.orderByArray
  610. addObject:[GCFSStructuredQuery_Order messageWithProperty:kDocumentKeyPath ascending:YES]];
  611. expected.targetId = 1;
  612. expected.resumeToken = FSTTestData(1, 2, 3, -1);
  613. [self assertRoundTripForQueryData:model proto:expected];
  614. }
  615. - (FSTQueryData *)queryDataForQuery:(FSTQuery *)query {
  616. return [[FSTQueryData alloc] initWithQuery:query
  617. targetID:1
  618. listenSequenceNumber:0
  619. purpose:FSTQueryPurposeListen
  620. snapshotVersion:SnapshotVersion::None()
  621. resumeToken:[NSData data]];
  622. }
  623. - (void)assertRoundTripForQueryData:(FSTQueryData *)queryData proto:(GCFSTarget *)proto {
  624. // Verify that the encoded FSTQueryData matches the target.
  625. GCFSTarget *actualProto = [self.serializer encodedTarget:queryData];
  626. XCTAssertEqualObjects(actualProto, proto);
  627. // We don't have deserialization logic for full targets since they're not used for RPC
  628. // interaction, but the query deserialization only *is* used for the local store.
  629. FSTQuery *actualModel;
  630. if (proto.targetTypeOneOfCase == GCFSTarget_TargetType_OneOfCase_Query) {
  631. actualModel = [self.serializer decodedQueryFromQueryTarget:proto.query];
  632. } else {
  633. actualModel = [self.serializer decodedQueryFromDocumentsTarget:proto.documents];
  634. }
  635. XCTAssertEqualObjects(actualModel, queryData.query);
  636. }
  637. - (void)testConvertsTargetChangeWithAdded {
  638. FSTWatchChange *expected =
  639. [[FSTWatchTargetChange alloc] initWithState:FSTWatchTargetChangeStateAdded
  640. targetIDs:@[ @1, @4 ]
  641. resumeToken:[NSData data]
  642. cause:nil];
  643. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  644. listenResponse.targetChange.targetChangeType = GCFSTargetChange_TargetChangeType_Add;
  645. [listenResponse.targetChange.targetIdsArray addValue:1];
  646. [listenResponse.targetChange.targetIdsArray addValue:4];
  647. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  648. XCTAssertEqualObjects(actual, expected);
  649. }
  650. - (void)testConvertsTargetChangeWithRemoved {
  651. FSTWatchChange *expected = [[FSTWatchTargetChange alloc]
  652. initWithState:FSTWatchTargetChangeStateRemoved
  653. targetIDs:@[ @1, @4 ]
  654. resumeToken:FSTTestData(0, 1, 2, -1)
  655. cause:[NSError errorWithDomain:FIRFirestoreErrorDomain
  656. code:FIRFirestoreErrorCodePermissionDenied
  657. userInfo:@{
  658. NSLocalizedDescriptionKey : @"Error message",
  659. }]];
  660. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  661. listenResponse.targetChange.targetChangeType = GCFSTargetChange_TargetChangeType_Remove;
  662. listenResponse.targetChange.cause.code = FIRFirestoreErrorCodePermissionDenied;
  663. listenResponse.targetChange.cause.message = @"Error message";
  664. listenResponse.targetChange.resumeToken = FSTTestData(0, 1, 2, -1);
  665. [listenResponse.targetChange.targetIdsArray addValue:1];
  666. [listenResponse.targetChange.targetIdsArray addValue:4];
  667. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  668. XCTAssertEqualObjects(actual, expected);
  669. }
  670. - (void)testConvertsTargetChangeWithNoChange {
  671. FSTWatchChange *expected =
  672. [[FSTWatchTargetChange alloc] initWithState:FSTWatchTargetChangeStateNoChange
  673. targetIDs:@[ @1, @4 ]
  674. resumeToken:[NSData data]
  675. cause:nil];
  676. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  677. listenResponse.targetChange.targetChangeType = GCFSTargetChange_TargetChangeType_NoChange;
  678. [listenResponse.targetChange.targetIdsArray addValue:1];
  679. [listenResponse.targetChange.targetIdsArray addValue:4];
  680. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  681. XCTAssertEqualObjects(actual, expected);
  682. }
  683. - (void)testConvertsDocumentChangeWithTargetIds {
  684. FSTWatchChange *expected = [[FSTDocumentWatchChange alloc]
  685. initWithUpdatedTargetIDs:@[ @1, @2 ]
  686. removedTargetIDs:@[]
  687. documentKey:FSTTestDocKey(@"coll/1")
  688. document:FSTTestDoc("coll/1", 5, @{@"foo" : @"bar"}, FSTDocumentStateSynced)];
  689. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  690. listenResponse.documentChange.document.name = @"projects/p/databases/d/documents/coll/1";
  691. listenResponse.documentChange.document.updateTime.nanos = 5000;
  692. GCFSValue *fooValue = [GCFSValue message];
  693. fooValue.stringValue = @"bar";
  694. [listenResponse.documentChange.document.fields setObject:fooValue forKey:@"foo"];
  695. [listenResponse.documentChange.targetIdsArray addValue:1];
  696. [listenResponse.documentChange.targetIdsArray addValue:2];
  697. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  698. XCTAssertEqualObjects(actual, expected);
  699. }
  700. - (void)testConvertsDocumentChangeWithRemovedTargetIds {
  701. FSTWatchChange *expected = [[FSTDocumentWatchChange alloc]
  702. initWithUpdatedTargetIDs:@[ @2 ]
  703. removedTargetIDs:@[ @1 ]
  704. documentKey:FSTTestDocKey(@"coll/1")
  705. document:FSTTestDoc("coll/1", 5, @{@"foo" : @"bar"}, FSTDocumentStateSynced)];
  706. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  707. listenResponse.documentChange.document.name = @"projects/p/databases/d/documents/coll/1";
  708. listenResponse.documentChange.document.updateTime.nanos = 5000;
  709. GCFSValue *fooValue = [GCFSValue message];
  710. fooValue.stringValue = @"bar";
  711. [listenResponse.documentChange.document.fields setObject:fooValue forKey:@"foo"];
  712. [listenResponse.documentChange.removedTargetIdsArray addValue:1];
  713. [listenResponse.documentChange.targetIdsArray addValue:2];
  714. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  715. XCTAssertEqualObjects(actual, expected);
  716. }
  717. - (void)testConvertsDocumentChangeWithDeletions {
  718. FSTWatchChange *expected =
  719. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:@[]
  720. removedTargetIDs:@[ @1, @2 ]
  721. documentKey:FSTTestDocKey(@"coll/1")
  722. document:FSTTestDeletedDoc("coll/1", 5, NO)];
  723. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  724. listenResponse.documentDelete.document = @"projects/p/databases/d/documents/coll/1";
  725. listenResponse.documentDelete.readTime.nanos = 5000;
  726. [listenResponse.documentDelete.removedTargetIdsArray addValue:1];
  727. [listenResponse.documentDelete.removedTargetIdsArray addValue:2];
  728. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  729. XCTAssertEqualObjects(actual, expected);
  730. }
  731. - (void)testConvertsDocumentChangeWithRemoves {
  732. FSTWatchChange *expected =
  733. [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:@[]
  734. removedTargetIDs:@[ @1, @2 ]
  735. documentKey:FSTTestDocKey(@"coll/1")
  736. document:nil];
  737. GCFSListenResponse *listenResponse = [GCFSListenResponse message];
  738. listenResponse.documentRemove.document = @"projects/p/databases/d/documents/coll/1";
  739. [listenResponse.documentRemove.removedTargetIdsArray addValue:1];
  740. [listenResponse.documentRemove.removedTargetIdsArray addValue:2];
  741. FSTWatchChange *actual = [self.serializer decodedWatchChange:listenResponse];
  742. XCTAssertEqualObjects(actual, expected);
  743. }
  744. @end
  745. NS_ASSUME_NONNULL_END