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