protocol_core_test.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "protocol_core.h"
  5. #include <memory>
  6. #include "cbor.h"
  7. #include "maybe.h"
  8. #include "status_test_support.h"
  9. #include "test_platform.h"
  10. #include "test_string_traits.h"
  11. namespace crdtp {
  12. namespace {
  13. using ::testing::Eq;
  14. template <typename TResult, typename TArg>
  15. std::unique_ptr<TResult> RoundtripToType(const TArg& obj) {
  16. std::vector<uint8_t> bytes;
  17. obj.AppendSerialized(&bytes);
  18. StatusOr<std::unique_ptr<TResult>> result =
  19. TResult::ReadFrom(std::move(bytes));
  20. return std::move(result).value();
  21. }
  22. template <typename T>
  23. std::unique_ptr<T> Roundtrip(const T& obj) {
  24. return RoundtripToType<T, T>(obj);
  25. }
  26. // These TestTypeFOO classes below would normally be generated
  27. // by the protocol generator.
  28. class TestTypeBasic : public ProtocolObject<TestTypeBasic> {
  29. public:
  30. TestTypeBasic() = default;
  31. const std::string& GetValue() const { return value_; }
  32. void SetValue(std::string value) { value_ = std::move(value); }
  33. private:
  34. DECLARE_SERIALIZATION_SUPPORT();
  35. std::string value_;
  36. };
  37. // clang-format off
  38. CRDTP_BEGIN_DESERIALIZER(TestTypeBasic)
  39. CRDTP_DESERIALIZE_FIELD("value", value_)
  40. CRDTP_END_DESERIALIZER()
  41. CRDTP_BEGIN_SERIALIZER(TestTypeBasic)
  42. CRDTP_SERIALIZE_FIELD("value", value_);
  43. CRDTP_END_SERIALIZER();
  44. // clang-format on
  45. TEST(ProtocolCoreTest, Basic) {
  46. TestTypeBasic obj1;
  47. obj1.SetValue("foo");
  48. auto obj2 = Roundtrip(obj1);
  49. ASSERT_THAT(obj2, Not(testing::IsNull()));
  50. EXPECT_THAT(obj2->GetValue(), Eq("foo"));
  51. }
  52. TEST(ProtocolCoreTest, FailedToDeserializeTestTypeBasic) {
  53. std::vector<uint8_t> garbage = {'g', 'a', 'r', 'b', 'a', 'g', 'e'};
  54. StatusOr<std::unique_ptr<TestTypeBasic>> result =
  55. TestTypeBasic::ReadFrom(std::move(garbage));
  56. EXPECT_THAT(result.status(), StatusIs(Error::CBOR_INVALID_STRING8, 0));
  57. }
  58. class TestTypeBasicDouble : public ProtocolObject<TestTypeBasicDouble> {
  59. public:
  60. TestTypeBasicDouble() = default;
  61. double GetValue() const { return value_; }
  62. void SetValue(double value) { value_ = value; }
  63. private:
  64. DECLARE_SERIALIZATION_SUPPORT();
  65. double value_;
  66. };
  67. // clang-format off
  68. CRDTP_BEGIN_DESERIALIZER(TestTypeBasicDouble)
  69. CRDTP_DESERIALIZE_FIELD("value", value_)
  70. CRDTP_END_DESERIALIZER()
  71. CRDTP_BEGIN_SERIALIZER(TestTypeBasicDouble)
  72. CRDTP_SERIALIZE_FIELD("value", value_);
  73. CRDTP_END_SERIALIZER();
  74. // clang-format on
  75. TEST(TestBasicDouble, ParserAllowsAllowsDoubleEncodedAsInt) {
  76. // We allow double's encoded as INT32, because this is what a roundtrip via
  77. // JSON would produce.
  78. std::vector<uint8_t> encoded;
  79. crdtp::cbor::EnvelopeEncoder envelope;
  80. envelope.EncodeStart(&encoded);
  81. encoded.push_back(crdtp::cbor::EncodeIndefiniteLengthMapStart());
  82. crdtp::cbor::EncodeString8(crdtp::SpanFrom("value"), &encoded);
  83. crdtp::cbor::EncodeInt32(
  84. 42, &encoded); // It's a double field, but we encode an int.
  85. encoded.push_back(crdtp::cbor::EncodeStop());
  86. envelope.EncodeStop(&encoded);
  87. auto obj = TestTypeBasicDouble::ReadFrom(encoded).value();
  88. ASSERT_THAT(obj, Not(testing::IsNull()));
  89. EXPECT_THAT(obj->GetValue(), Eq(42));
  90. }
  91. class TestTypeComposite : public ProtocolObject<TestTypeComposite> {
  92. public:
  93. bool GetBoolField() const { return bool_field_; }
  94. void SetBoolField(bool value) { bool_field_ = value; }
  95. int GetIntField() const { return int_field_; }
  96. void SetIntField(int value) { int_field_ = value; }
  97. double GetDoubleField() const { return double_field_; }
  98. void SetDoubleField(double value) { double_field_ = value; }
  99. const std::string& GetStrField() const { return str_field_; }
  100. void SetStrField(std::string value) { str_field_ = std::move(value); }
  101. const TestTypeBasic* GetTestTypeBasicField() {
  102. return test_type1_field_.get();
  103. }
  104. void SetTestTypeBasicField(std::unique_ptr<TestTypeBasic> value) {
  105. test_type1_field_ = std::move(value);
  106. }
  107. private:
  108. DECLARE_SERIALIZATION_SUPPORT();
  109. bool bool_field_ = false;
  110. int int_field_ = 0;
  111. double double_field_ = 0.0;
  112. std::string str_field_;
  113. std::unique_ptr<TestTypeBasic> test_type1_field_;
  114. };
  115. // clang-format off
  116. CRDTP_BEGIN_DESERIALIZER(TestTypeComposite)
  117. CRDTP_DESERIALIZE_FIELD("bool_field", bool_field_),
  118. CRDTP_DESERIALIZE_FIELD("double_field", double_field_),
  119. CRDTP_DESERIALIZE_FIELD("int_field", int_field_),
  120. CRDTP_DESERIALIZE_FIELD("str_field", str_field_),
  121. CRDTP_DESERIALIZE_FIELD("test_type1_field", test_type1_field_),
  122. CRDTP_END_DESERIALIZER()
  123. CRDTP_BEGIN_SERIALIZER(TestTypeComposite)
  124. CRDTP_SERIALIZE_FIELD("bool_field", bool_field_),
  125. CRDTP_SERIALIZE_FIELD("double_field", double_field_),
  126. CRDTP_SERIALIZE_FIELD("int_field", int_field_),
  127. CRDTP_SERIALIZE_FIELD("str_field", str_field_),
  128. CRDTP_SERIALIZE_FIELD("test_type1_field", test_type1_field_),
  129. CRDTP_END_SERIALIZER();
  130. // clang-format on
  131. TEST(ProtocolCoreTest, Composite) {
  132. TestTypeComposite obj1;
  133. obj1.SetBoolField(true);
  134. obj1.SetIntField(42);
  135. obj1.SetDoubleField(2.718281828);
  136. obj1.SetStrField("bar");
  137. auto val1 = std::make_unique<TestTypeBasic>();
  138. val1->SetValue("bazzzz");
  139. obj1.SetTestTypeBasicField(std::move(val1));
  140. auto obj2 = Roundtrip(obj1);
  141. ASSERT_THAT(obj2, Not(testing::IsNull()));
  142. EXPECT_THAT(obj2->GetBoolField(), Eq(true));
  143. EXPECT_THAT(obj2->GetIntField(), Eq(42));
  144. EXPECT_THAT(obj2->GetDoubleField(), Eq(2.718281828));
  145. EXPECT_THAT(obj2->GetStrField(), Eq("bar"));
  146. EXPECT_THAT(obj2->GetTestTypeBasicField()->GetValue(), Eq("bazzzz"));
  147. }
  148. class CompositeParsingTest : public testing::Test {
  149. public:
  150. CompositeParsingTest() {
  151. TestTypeComposite top;
  152. top.SetIntField(42);
  153. top.SetBoolField(true);
  154. top.SetIntField(42);
  155. top.SetDoubleField(2.718281828);
  156. top.SetStrField("junk");
  157. auto child = std::make_unique<TestTypeBasic>();
  158. child->SetValue("child_value");
  159. top.SetTestTypeBasicField(std::move(child));
  160. // Let's establish that |serialized_| is a properly serialized
  161. // representation of |top|, by checking that it deserializes ok.
  162. top.AppendSerialized(&serialized_);
  163. TestTypeComposite::ReadFrom(serialized_).value();
  164. }
  165. protected:
  166. std::vector<uint8_t> serialized_;
  167. };
  168. TEST_F(CompositeParsingTest, DecodingFailure_CBORTokenizer) {
  169. // Mutates |serialized_| so that it won't parse correctly. In this case,
  170. // we're changing a string value so that it's invalid, making CBORTokenizer
  171. // unhappy.
  172. size_t position =
  173. std::string(reinterpret_cast<const char*>(serialized_.data()),
  174. serialized_.size())
  175. .find("child_value");
  176. EXPECT_GT(position, 0ul);
  177. // We override the byte just before so that it's still a string
  178. // (3 << 5), but the length is encoded in the bytes that follows.
  179. // So, we override that with 0xff (255), which exceeds the length
  180. // of the message and thereby makes the string8 invalid.
  181. --position;
  182. serialized_[position] = 3 << 5 | // major type: STRING
  183. 25; // length in encoded in byte that follows.
  184. serialized_[position + 1] = 0xff; // length
  185. auto result = TestTypeComposite::ReadFrom(serialized_);
  186. EXPECT_THAT(result.status(), StatusIs(Error::CBOR_INVALID_STRING8, position));
  187. }
  188. TEST_F(CompositeParsingTest, DecodingFailure_MandatoryFieldMissingShallow) {
  189. // We're changing the string key "int_field" to something else ("lnt_field"),
  190. // so that the mandatory field value won't be found. Unknown fields are
  191. // ignored for compatibility, so that's why this simple technique works here.
  192. size_t position =
  193. std::string(reinterpret_cast<const char*>(serialized_.data()),
  194. serialized_.size())
  195. .find("int_field");
  196. serialized_[position] = 'l'; // Change 'i' to 'l'.
  197. // serialized_.size() - 1 is the STOP character for the entire message,
  198. size_t expected_error_pos = serialized_.size() - 1;
  199. auto result = TestTypeComposite::ReadFrom(serialized_);
  200. EXPECT_THAT(result.status(), StatusIs(Error::BINDINGS_MANDATORY_FIELD_MISSING,
  201. expected_error_pos));
  202. }
  203. TEST_F(CompositeParsingTest, DecodingFailure_MandatoryFieldMissingNested) {
  204. // We're changing the string key "value" to something else ("falue"), so that
  205. // the mandatory field value in TestTypeBasic in the child won't be found.
  206. size_t position =
  207. std::string(reinterpret_cast<const char*>(serialized_.data()),
  208. serialized_.size())
  209. .find("value");
  210. serialized_[position] = 'f'; // Change 'v' to 'f'.
  211. // serialized_.size() - 1 is the STOP character for the enclosing message,
  212. // and serialized_.size() - 2 is the STOP character for TestTypeBasic.
  213. size_t expected_error_pos = serialized_.size() - 2;
  214. auto result = TestTypeComposite::ReadFrom(serialized_);
  215. EXPECT_THAT(result.status(), StatusIs(Error::BINDINGS_MANDATORY_FIELD_MISSING,
  216. expected_error_pos));
  217. }
  218. TEST_F(CompositeParsingTest, DecodingFailure_BoolValueExpected) {
  219. // We're changing the bool value (true) to null; we do this by looking
  220. // for bool_field, and searching from there for TRUE; both TRUE and null
  221. // are just one byte in the serialized buffer, so this swap is convenient.
  222. std::string serialized_view(reinterpret_cast<const char*>(serialized_.data()),
  223. serialized_.size());
  224. size_t position = serialized_view.find("bool_field");
  225. for (; position < serialized_.size(); ++position) {
  226. if (serialized_[position] == crdtp::cbor::EncodeTrue()) {
  227. serialized_[position] = crdtp::cbor::EncodeNull();
  228. break;
  229. }
  230. }
  231. auto result = TestTypeComposite::ReadFrom(serialized_);
  232. EXPECT_THAT(result.status(),
  233. StatusIs(Error::BINDINGS_BOOL_VALUE_EXPECTED, position));
  234. }
  235. class TestTypeArrays : public ProtocolObject<TestTypeArrays> {
  236. public:
  237. const std::vector<int>* GetIntArray() const { return &int_array_; }
  238. void SetIntArray(std::vector<int> value) { int_array_ = std::move(value); }
  239. const std::vector<double>* GetDoubleArray() const { return &double_array_; }
  240. void SetDoubleArray(std::vector<double> value) {
  241. double_array_ = std::move(value);
  242. }
  243. const std::vector<std::string>* GetStrArray() const { return &str_array_; }
  244. void SetStrArray(std::vector<std::string> value) {
  245. str_array_ = std::move(value);
  246. }
  247. const std::vector<std::unique_ptr<TestTypeBasic>>* GetTestTypeBasicArray()
  248. const {
  249. return &test_type_basic_array_;
  250. }
  251. void SetTestTypeBasicArray(
  252. std::vector<std::unique_ptr<TestTypeBasic>> value) {
  253. test_type_basic_array_ = std::move(value);
  254. }
  255. private:
  256. DECLARE_SERIALIZATION_SUPPORT();
  257. std::vector<int> int_array_;
  258. std::vector<double> double_array_;
  259. std::vector<std::string> str_array_;
  260. std::vector<std::unique_ptr<TestTypeBasic>> test_type_basic_array_;
  261. };
  262. // clang-format off
  263. CRDTP_BEGIN_DESERIALIZER(TestTypeArrays)
  264. CRDTP_DESERIALIZE_FIELD("int_array", int_array_),
  265. CRDTP_DESERIALIZE_FIELD("str_array", str_array_),
  266. CRDTP_DESERIALIZE_FIELD("test_type_basic_array", test_type_basic_array_),
  267. CRDTP_END_DESERIALIZER()
  268. CRDTP_BEGIN_SERIALIZER(TestTypeArrays)
  269. CRDTP_SERIALIZE_FIELD("int_array", int_array_),
  270. CRDTP_SERIALIZE_FIELD("str_array", str_array_),
  271. CRDTP_SERIALIZE_FIELD("test_type_basic_array", test_type_basic_array_),
  272. CRDTP_END_SERIALIZER();
  273. // clang-format on
  274. TEST_F(CompositeParsingTest, Arrays) {
  275. TestTypeArrays obj1;
  276. obj1.SetIntArray(std::vector<int>{1, 3, 5, 7});
  277. std::vector<std::string> strs;
  278. strs.emplace_back("foo");
  279. strs.emplace_back(std::string("bar"));
  280. obj1.SetStrArray(std::move(strs));
  281. auto val1 = std::make_unique<TestTypeBasic>();
  282. val1->SetValue("bazzzz");
  283. std::vector<std::unique_ptr<TestTypeBasic>> vec1;
  284. vec1.emplace_back(std::move(val1));
  285. obj1.SetTestTypeBasicArray(std::move(vec1));
  286. auto obj2 = Roundtrip(obj1);
  287. ASSERT_THAT(obj2, Not(testing::IsNull()));
  288. EXPECT_THAT(*obj2->GetIntArray(), testing::ElementsAre(1, 3, 5, 7));
  289. EXPECT_THAT(*obj2->GetStrArray(), testing::ElementsAre("foo", "bar"));
  290. EXPECT_THAT(obj2->GetDoubleArray()->size(), Eq(0ul));
  291. EXPECT_THAT(obj2->GetTestTypeBasicArray()->size(), Eq(1ul));
  292. EXPECT_THAT(obj2->GetTestTypeBasicArray()->front()->GetValue(), Eq("bazzzz"));
  293. }
  294. class TestTypeOptional : public ProtocolObject<TestTypeOptional> {
  295. public:
  296. TestTypeOptional() = default;
  297. bool HasIntField() const { return int_field_.isJust(); }
  298. int GetIntField() const { return int_field_.fromJust(); }
  299. void SetIntField(int value) { int_field_ = value; }
  300. bool HasStrField() { return str_field_.isJust(); }
  301. const std::string& GetStrField() const { return str_field_.fromJust(); }
  302. void SetStrField(std::string value) { str_field_ = std::move(value); }
  303. bool HasTestTypeBasicField() { return test_type_basic_field_.isJust(); }
  304. const TestTypeBasic* GetTestTypeBasicField() const {
  305. return test_type_basic_field_.isJust() ? test_type_basic_field_.fromJust()
  306. : nullptr;
  307. }
  308. void SetTestTypeBasicField(std::unique_ptr<TestTypeBasic> value) {
  309. test_type_basic_field_ = std::move(value);
  310. }
  311. private:
  312. DECLARE_SERIALIZATION_SUPPORT();
  313. Maybe<int> int_field_;
  314. Maybe<std::string> str_field_;
  315. Maybe<TestTypeBasic> test_type_basic_field_;
  316. };
  317. // clang-format off
  318. CRDTP_BEGIN_DESERIALIZER(TestTypeOptional)
  319. CRDTP_DESERIALIZE_FIELD_OPT("int_field", int_field_),
  320. CRDTP_DESERIALIZE_FIELD_OPT("str_field", str_field_),
  321. CRDTP_DESERIALIZE_FIELD_OPT("test_type_basic_field", test_type_basic_field_),
  322. CRDTP_END_DESERIALIZER()
  323. CRDTP_BEGIN_SERIALIZER(TestTypeOptional)
  324. CRDTP_SERIALIZE_FIELD("int_field", int_field_),
  325. CRDTP_SERIALIZE_FIELD("str_field", str_field_),
  326. CRDTP_SERIALIZE_FIELD("test_type_basic_field", test_type_basic_field_),
  327. CRDTP_END_SERIALIZER();
  328. // clang-format on
  329. TEST(ProtocolCoreTest, OptionalAbsent) {
  330. TestTypeOptional obj1;
  331. auto obj2 = Roundtrip(obj1);
  332. ASSERT_THAT(obj2, Not(testing::IsNull()));
  333. EXPECT_THAT(obj2->HasIntField(), Eq(false));
  334. EXPECT_THAT(obj2->HasStrField(), Eq(false));
  335. EXPECT_THAT(obj2->HasTestTypeBasicField(), Eq(false));
  336. }
  337. TEST(ProtocolCoreTest, OptionalPresent) {
  338. TestTypeOptional obj1;
  339. obj1.SetIntField(42);
  340. obj1.SetStrField("foo");
  341. auto val1 = std::make_unique<TestTypeBasic>();
  342. val1->SetValue("bar");
  343. obj1.SetTestTypeBasicField(std::move(val1));
  344. auto obj2 = Roundtrip(obj1);
  345. ASSERT_THAT(obj2, Not(testing::IsNull()));
  346. EXPECT_THAT(obj2->HasIntField(), Eq(true));
  347. EXPECT_THAT(obj2->GetIntField(), Eq(42));
  348. EXPECT_THAT(obj2->HasStrField(), Eq(true));
  349. EXPECT_THAT(obj2->GetStrField(), Eq("foo"));
  350. EXPECT_THAT(obj2->HasTestTypeBasicField(), Eq(true));
  351. EXPECT_THAT(obj2->GetTestTypeBasicField()->GetValue(), Eq("bar"));
  352. }
  353. class TestTypeLazy : public ProtocolObject<TestTypeLazy> {
  354. public:
  355. TestTypeLazy() = default;
  356. const std::string& GetStrField() const { return str_field_; }
  357. void SetStrField(std::string value) { str_field_ = std::move(value); }
  358. const DeferredMessage* deferred_test_type1_field() const {
  359. return test_type1_field_.get();
  360. }
  361. private:
  362. DECLARE_SERIALIZATION_SUPPORT();
  363. std::string str_field_;
  364. std::unique_ptr<DeferredMessage> test_type1_field_;
  365. };
  366. // clang-format off
  367. CRDTP_BEGIN_DESERIALIZER(TestTypeLazy)
  368. CRDTP_DESERIALIZE_FIELD("str_field", str_field_),
  369. CRDTP_DESERIALIZE_FIELD_OPT("test_type1_field", test_type1_field_),
  370. CRDTP_END_DESERIALIZER()
  371. CRDTP_BEGIN_SERIALIZER(TestTypeLazy)
  372. CRDTP_SERIALIZE_FIELD("str_field", str_field_),
  373. CRDTP_SERIALIZE_FIELD("test_type1_field", test_type1_field_),
  374. CRDTP_END_SERIALIZER();
  375. // clang-format on
  376. TEST(ProtocolCoreTest, TestDeferredMessage) {
  377. TestTypeComposite obj1;
  378. obj1.SetStrField("bar");
  379. auto val1 = std::make_unique<TestTypeBasic>();
  380. val1->SetValue("bazzzz");
  381. obj1.SetTestTypeBasicField(std::move(val1));
  382. auto obj2 = RoundtripToType<TestTypeLazy>(obj1);
  383. EXPECT_THAT(obj2->GetStrField(), Eq("bar"));
  384. TestTypeBasic basic_val;
  385. auto deserializer = obj2->deferred_test_type1_field()->MakeDeserializer();
  386. EXPECT_THAT(TestTypeBasic::Deserialize(&deserializer, &basic_val), Eq(true));
  387. EXPECT_THAT(basic_val.GetValue(), Eq("bazzzz"));
  388. StatusOr<std::unique_ptr<TestTypeBasic>> maybe_parsed =
  389. TestTypeBasic::ReadFrom(*obj2->deferred_test_type1_field());
  390. ASSERT_THAT(maybe_parsed.status(), StatusIsOk());
  391. ASSERT_THAT((*maybe_parsed), Not(testing::IsNull()));
  392. ASSERT_EQ((*maybe_parsed)->GetValue(), "bazzzz");
  393. }
  394. } // namespace
  395. } // namespace crdtp