FSTSerializerBetaTests.mm 36 KB

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