diagnostic_writer_unittest.cc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2019 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 "components/cbor/diagnostic_writer.h"
  5. #include "components/cbor/reader.h"
  6. #include "components/cbor/values.h"
  7. #include "testing/gtest/include/gtest/gtest.h"
  8. namespace cbor {
  9. TEST(CBORDiagnosticWriterTest, Basic) {
  10. Value::MapValue map;
  11. map.emplace(1, 1);
  12. map.emplace(2, -2);
  13. map.emplace(3, "test");
  14. std::vector<uint8_t> bytes = {1, 2, 3, 4};
  15. map.emplace(4, std::move(bytes));
  16. Value::MapValue submap;
  17. submap.emplace(5, true);
  18. submap.emplace(6, false);
  19. map.emplace(5, cbor::Value(submap));
  20. Value::ArrayValue array;
  21. array.emplace_back(1);
  22. array.emplace_back(2);
  23. array.emplace_back(3);
  24. array.emplace_back("foo");
  25. map.emplace(6, cbor::Value(array));
  26. map.emplace(7, "es\'cap\\in\ng");
  27. EXPECT_EQ(
  28. "{1: 1, 2: -2, 3: \"test\", 4: h'01020304', 5: {5: true, 6: false}, 6: "
  29. "[1, 2, 3, \"foo\"], 7: \"es'cap\\\\in\\ng\"}",
  30. DiagnosticWriter::Write(cbor::Value(map)));
  31. }
  32. TEST(CBORDiagnosticWriterTest, SizeLimit) {
  33. Value::ArrayValue array;
  34. array.emplace_back(1);
  35. array.emplace_back(2);
  36. array.emplace_back(3);
  37. EXPECT_EQ("[1, 2, 3]", DiagnosticWriter::Write(cbor::Value(array)));
  38. // A limit of zero is set, but it's only rough, so a few bytes might be
  39. // produced.
  40. EXPECT_LT(
  41. DiagnosticWriter::Write(cbor::Value(array), /*rough_max_output_bytes=*/0)
  42. .size(),
  43. 3u);
  44. std::vector<uint8_t> bytes;
  45. bytes.resize(100);
  46. EXPECT_LT(
  47. DiagnosticWriter::Write(cbor::Value(bytes), /*rough_max_output_bytes=*/0)
  48. .size(),
  49. 3u);
  50. }
  51. TEST(CBORDiagnosticWriterTest, InvalidUTF8) {
  52. static const uint8_t kInvalidUTF8[] = {0x62, 0xe2, 0x80};
  53. cbor::Reader::Config config;
  54. config.allow_invalid_utf8 = true;
  55. absl::optional<cbor::Value> maybe_value =
  56. cbor::Reader::Read(kInvalidUTF8, config);
  57. ASSERT_TRUE(maybe_value);
  58. EXPECT_EQ("s'E280'", DiagnosticWriter::Write(*maybe_value));
  59. }
  60. } // namespace cbor