Bitcoin Core 30.99.0
P2P Digital Currency
util_string_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2024-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <util/strencodings.h>
6#include <util/string.h>
7#include <vector>
8
9#include <boost/test/unit_test.hpp>
11
12using namespace util;
14
15BOOST_AUTO_TEST_SUITE(util_string_tests)
16
17template <unsigned NumArgs>
18void TfmFormatZeroes(const std::string& fmt)
19{
20 std::apply([&](auto... args) {
21 (void)tfm::format(tfm::RuntimeFormat{fmt}, args...);
22 }, std::array<int, NumArgs>{});
23}
24
25// Helper to allow compile-time sanity checks while providing the number of
26// args directly. Normally PassFmt<sizeof...(Args)> would be used.
27template <unsigned NumArgs>
29{
30 // Execute compile-time check again at run-time to get code coverage stats
31 BOOST_CHECK_NO_THROW(CheckNumFormatSpecifiers<NumArgs>(fmt.fmt));
32
33 // If ConstevalFormatString didn't throw above, make sure tinyformat doesn't
34 // throw either for the same format string and parameter count combination.
35 // Proves that we have some extent of protection from runtime errors
36 // (tinyformat may still throw for some type mismatches).
37 BOOST_CHECK_NO_THROW(TfmFormatZeroes<NumArgs>(fmt.fmt));
38}
39template <unsigned WrongNumArgs>
40void FailFmtWithError(const char* wrong_fmt, std::string_view error)
41{
42 BOOST_CHECK_EXCEPTION(CheckNumFormatSpecifiers<WrongNumArgs>(wrong_fmt), const char*, HasReason{error});
43}
44
45std::vector<std::byte> StringToBuffer(const std::string& str)
46{
47 auto span = std::as_bytes(std::span(str));
48 return {span.begin(), span.end()};
49}
50
51BOOST_AUTO_TEST_CASE(ConstevalFormatString_NumSpec)
52{
53 PassFmt<0>("");
54 PassFmt<0>("%%");
55 PassFmt<1>("%s");
56 PassFmt<1>("%c");
57 PassFmt<0>("%%s");
58 PassFmt<0>("s%%");
59 PassFmt<1>("%%%s");
60 PassFmt<1>("%s%%");
61 PassFmt<0>(" 1$s");
62 PassFmt<1>("%1$s");
63 PassFmt<1>("%1$s%1$s");
64 PassFmt<2>("%2$s");
65 PassFmt<2>("%2$s 4$s %2$s");
66 PassFmt<129>("%129$s 999$s %2$s");
67 PassFmt<1>("%02d");
68 PassFmt<1>("%+2s");
69 PassFmt<1>("%.6i");
70 PassFmt<1>("%5.2f");
71 PassFmt<1>("%5.f");
72 PassFmt<1>("%.f");
73 PassFmt<1>("%#x");
74 PassFmt<1>("%1$5i");
75 PassFmt<1>("%1$-5i");
76 PassFmt<1>("%1$.5i");
77 // tinyformat accepts almost any "type" spec, even '%', or '_', or '\n'.
78 PassFmt<1>("%123%");
79 PassFmt<1>("%123%s");
80 PassFmt<1>("%_");
81 PassFmt<1>("%\n");
82
83 PassFmt<2>("%*c");
84 PassFmt<2>("%+*c");
85 PassFmt<2>("%.*f");
86 PassFmt<3>("%*.*f");
87 PassFmt<3>("%2$*3$d");
88 PassFmt<3>("%2$*3$.9d");
89 PassFmt<3>("%2$.*3$d");
90 PassFmt<3>("%2$9.*3$d");
91 PassFmt<3>("%2$+9.*3$d");
92 PassFmt<4>("%3$*2$.*4$f");
93
94 // Make sure multiple flag characters "- 0+" are accepted
95 PassFmt<3>("'%- 0+*.*f'");
96 PassFmt<3>("'%1$- 0+*3$.*2$f'");
97
98 auto err_mix{"Format specifiers must be all positional or all non-positional!"};
99 FailFmtWithError<1>("%s%1$s", err_mix);
100 FailFmtWithError<2>("%2$*d", err_mix);
101 FailFmtWithError<2>("%*2$d", err_mix);
102 FailFmtWithError<2>("%.*3$d", err_mix);
103 FailFmtWithError<2>("%2$.*d", err_mix);
104
105 auto err_num{"Format specifier count must match the argument count!"};
106 FailFmtWithError<1>("", err_num);
107 FailFmtWithError<0>("%s", err_num);
108 FailFmtWithError<2>("%s", err_num);
109 FailFmtWithError<0>("%1$s", err_num);
110 FailFmtWithError<2>("%1$s", err_num);
111 FailFmtWithError<1>("%*c", err_num);
112
113 auto err_0_pos{"Positional format specifier must have position of at least 1"};
114 FailFmtWithError<1>("%$s", err_0_pos);
115 FailFmtWithError<1>("%$", err_0_pos);
116 FailFmtWithError<0>("%0$", err_0_pos);
117 FailFmtWithError<0>("%0$s", err_0_pos);
118 FailFmtWithError<2>("%2$*$d", err_0_pos);
119 FailFmtWithError<2>("%2$*0$d", err_0_pos);
120 FailFmtWithError<3>("%3$*2$.*$f", err_0_pos);
121 FailFmtWithError<3>("%3$*2$.*0$f", err_0_pos);
122
123 auto err_term{"Format specifier incorrectly terminated by end of string"};
124 FailFmtWithError<1>("%", err_term);
125 FailFmtWithError<1>("%9", err_term);
126 FailFmtWithError<1>("%9.", err_term);
127 FailFmtWithError<1>("%9.9", err_term);
128 FailFmtWithError<1>("%*", err_term);
129 FailFmtWithError<1>("%+*", err_term);
130 FailFmtWithError<1>("%.*", err_term);
131 FailFmtWithError<1>("%9.*", err_term);
132 FailFmtWithError<1>("%1$", err_term);
133 FailFmtWithError<1>("%1$9", err_term);
134 FailFmtWithError<2>("%1$*2$", err_term);
135 FailFmtWithError<2>("%1$.*2$", err_term);
136 FailFmtWithError<2>("%1$9.*2$", err_term);
137
138 // Non-parity between tinyformat and ConstevalFormatString.
139 // tinyformat throws but ConstevalFormatString does not.
140 BOOST_CHECK_EXCEPTION(tfm::format(ConstevalFormatString<1>{"%n"}, 0), tfm::format_error,
141 HasReason{"tinyformat: %n conversion spec not supported"});
142 BOOST_CHECK_EXCEPTION(tfm::format(ConstevalFormatString<2>{"%*s"}, "hi", "hi"), tfm::format_error,
143 HasReason{"tinyformat: Cannot convert from argument type to integer for use as variable width or precision"});
144 BOOST_CHECK_EXCEPTION(tfm::format(ConstevalFormatString<2>{"%.*s"}, "hi", "hi"), tfm::format_error,
145 HasReason{"tinyformat: Cannot convert from argument type to integer for use as variable width or precision"});
146
147 // Ensure that tinyformat throws if format string contains wrong number
148 // of specifiers. PassFmt relies on this to verify tinyformat successfully
149 // formats the strings, and will need to be updated if tinyformat is changed
150 // not to throw on failure.
151 BOOST_CHECK_EXCEPTION(TfmFormatZeroes<2>("%s"), tfm::format_error,
152 HasReason{"tinyformat: Not enough conversion specifiers in format string"});
153 BOOST_CHECK_EXCEPTION(TfmFormatZeroes<1>("%s %s"), tfm::format_error,
154 HasReason{"tinyformat: Too many conversion specifiers in format string"});
155}
156
157BOOST_AUTO_TEST_CASE(ascii_case_insensitive_key_equal_test)
158{
160 BOOST_CHECK(!cmp("A", "B"));
161 BOOST_CHECK(!cmp("A", "b"));
162 BOOST_CHECK(!cmp("a", "B"));
163 BOOST_CHECK(!cmp("B", "A"));
164 BOOST_CHECK(!cmp("B", "a"));
165 BOOST_CHECK(!cmp("b", "A"));
166 BOOST_CHECK(!cmp("A", "AA"));
167 BOOST_CHECK(cmp("A-A", "a-a"));
168 BOOST_CHECK(cmp("A", "A"));
169 BOOST_CHECK(cmp("A", "a"));
170 BOOST_CHECK(cmp("a", "a"));
171 BOOST_CHECK(cmp("B", "b"));
172 BOOST_CHECK(cmp("ab", "aB"));
173 BOOST_CHECK(cmp("Ab", "aB"));
174 BOOST_CHECK(cmp("AB", "ab"));
175
176 // Use a character with value > 127
177 // to ensure we don't trigger implicit-integer-sign-change
178 BOOST_CHECK(!cmp("a", "\xe4"));
179}
180
181BOOST_AUTO_TEST_CASE(ascii_case_insensitive_hash_test)
182{
184 BOOST_CHECK_NE(hsh("A"), hsh("B"));
185 BOOST_CHECK_NE(hsh("AA"), hsh("A"));
186 BOOST_CHECK_EQUAL(hsh("A"), hsh("a"));
187 BOOST_CHECK_EQUAL(hsh("Ab"), hsh("aB"));
188 BOOST_CHECK_EQUAL(hsh("A\xfe"), hsh("a\xfe"));
189}
190
191BOOST_AUTO_TEST_CASE(line_reader_test)
192{
193 {
194 // Check three lines terminated by \n and \r\n, trimming whitespace
195 const std::vector<std::byte> input{StringToBuffer("once upon a time\n there was a dog \r\nwho liked food\n")};
196 LineReader reader(input, /*max_line_length=*/128);
197 std::optional<std::string> line1{reader.ReadLine()};
198 BOOST_CHECK_EQUAL(reader.Remaining(), 34);
199 std::optional<std::string> line2{reader.ReadLine()};
200 BOOST_CHECK_EQUAL(reader.Remaining(), 15);
201 std::optional<std::string> line3{reader.ReadLine()};
202 std::optional<std::string> line4{reader.ReadLine()};
203 BOOST_CHECK(line1);
204 BOOST_CHECK(line2);
205 BOOST_CHECK(line3);
206 BOOST_CHECK(!line4);
207 BOOST_CHECK_EQUAL(line1.value(), "once upon a time");
208 BOOST_CHECK_EQUAL(line2.value(), "there was a dog");
209 BOOST_CHECK_EQUAL(line3.value(), "who liked food");
210 }
211 {
212 // Do not exceed max_line_length + 1 while searching for \n
213 // Test with 22-character line + \n + 23-character line + \n
214 const std::vector<std::byte> input{StringToBuffer("once upon a time there\nwas a dog who liked tea\n")};
215
216 LineReader reader1(input, /*max_line_length=*/22);
217 // First line is exactly the length of max_line_length
218 BOOST_CHECK_EQUAL(reader1.ReadLine(), "once upon a time there");
219 // Second line is +1 character too long
220 BOOST_CHECK_EXCEPTION(reader1.ReadLine(), std::runtime_error, HasReason{"max_line_length exceeded by LineReader"});
221
222 // Increase max_line_length by 1
223 LineReader reader2(input, /*max_line_length=*/23);
224 // Both lines fit within limit
225 BOOST_CHECK_EQUAL(reader2.ReadLine(), "once upon a time there");
226 BOOST_CHECK_EQUAL(reader2.ReadLine(), "was a dog who liked tea");
227 // End of buffer reached
228 BOOST_CHECK(!reader2.ReadLine());
229 }
230 {
231 // Empty lines are empty
232 const std::vector<std::byte> input{StringToBuffer("\n")};
233 LineReader reader(input, /*max_line_length=*/1024);
234 BOOST_CHECK_EQUAL(reader.ReadLine(), "");
235 BOOST_CHECK(!reader.ReadLine());
236 }
237 {
238 // Empty buffers are null
239 const std::vector<std::byte> input{StringToBuffer("")};
240 LineReader reader(input, /*max_line_length=*/1024);
241 BOOST_CHECK(!reader.ReadLine());
242 }
243 {
244 // Even one character is too long, if it's not \n
245 const std::vector<std::byte> input{StringToBuffer("ab\n")};
246 LineReader reader(input, /*max_line_length=*/1);
247 // First line is +1 character too long
248 BOOST_CHECK_EXCEPTION(reader.ReadLine(), std::runtime_error, HasReason{"max_line_length exceeded by LineReader"});
249 }
250 {
251 const std::vector<std::byte> input{StringToBuffer("a\nb\n")};
252 LineReader reader(input, /*max_line_length=*/1);
253 BOOST_CHECK_EQUAL(reader.ReadLine(), "a");
254 BOOST_CHECK_EQUAL(reader.ReadLine(), "b");
255 BOOST_CHECK(!reader.ReadLine());
256 }
257 {
258 // If ReadLine fails, the iterator is reset and we can ReadLength instead
259 const std::vector<std::byte> input{StringToBuffer("a\nbaboon\n")};
260 LineReader reader(input, /*max_line_length=*/1);
261 BOOST_CHECK_EQUAL(reader.ReadLine(), "a");
262 // "baboon" is too long
263 BOOST_CHECK_EXCEPTION(reader.ReadLine(), std::runtime_error, HasReason{"max_line_length exceeded by LineReader"});
264 BOOST_CHECK_EQUAL(reader.ReadLength(1), "b");
265 BOOST_CHECK_EQUAL(reader.ReadLength(1), "a");
266 BOOST_CHECK_EQUAL(reader.ReadLength(2), "bo");
267 // "on" is too long
268 BOOST_CHECK_EXCEPTION(reader.ReadLine(), std::runtime_error, HasReason{"max_line_length exceeded by LineReader"});
269 BOOST_CHECK_EQUAL(reader.ReadLength(1), "o");
270 BOOST_CHECK_EQUAL(reader.ReadLine(), "n"); // now the remainder of the buffer fits in one line
271 BOOST_CHECK(!reader.ReadLine());
272 }
273 {
274 // The end of the buffer (EOB) does not count as end of line \n
275 const std::vector<std::byte> input{StringToBuffer("once upon a time there")};
276
277 LineReader reader(input, /*max_line_length=*/22);
278 // First line is exactly the length of max_line_length, but that doesn't matter because \n is missing
279 BOOST_CHECK(!reader.ReadLine());
280 // Data can still be read using ReadLength
281 BOOST_CHECK_EQUAL(reader.ReadLength(22), "once upon a time there");
282 // End of buffer reached
283 BOOST_CHECK_EQUAL(reader.Remaining(), 0);
284 }
285 {
286 // Read specific number of bytes regardless of max_line_length or \n unless buffer is too short
287 const std::vector<std::byte> input{StringToBuffer("once upon a time\n there was a dog \r\nwho liked food")};
288 LineReader reader(input, /*max_line_length=*/1);
289 BOOST_CHECK_EQUAL(reader.ReadLength(0), "");
290 BOOST_CHECK_EQUAL(reader.ReadLength(3), "onc");
291 BOOST_CHECK_EQUAL(reader.ReadLength(8), "e upon a");
292 BOOST_CHECK_EQUAL(reader.ReadLength(8), " time\n t");
293 BOOST_CHECK_EXCEPTION(reader.ReadLength(128), std::runtime_error, HasReason{"Not enough data in buffer"});
294 // After the error the iterator is reset so we can try again
295 BOOST_CHECK_EQUAL(reader.ReadLength(31), "here was a dog \r\nwho liked food");
296 // End of buffer reached
297 BOOST_CHECK_EQUAL(reader.Remaining(), 0);
298 }
299}
300
ArgsManager & args
Definition: bitcoind.cpp:277
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:293
BOOST_AUTO_TEST_SUITE_END()
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
static constexpr void CheckNumFormatSpecifiers(const char *str)
Definition: string.h:23
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
#define BOOST_CHECK_NO_THROW(stmt)
Definition: object.cpp:27
#define BOOST_CHECK(expr)
Definition: object.cpp:16
A wrapper for a compile-time partially validated format string.
Definition: string.h:93
const char *const fmt
Definition: string.h:94
size_t Remaining() const
Returns remaining size of bytes in buffer.
Definition: string.cpp:66
std::string ReadLength(size_t len)
Returns string from current iterator position of specified length if possible and advances iterator o...
Definition: string.cpp:57
std::optional< std::string > ReadLine()
Returns a string from current iterator position up to (but not including) next and advances iterator...
Definition: string.cpp:20
BOOST_AUTO_TEST_CASE(ConstevalFormatString_NumSpec)
void TfmFormatZeroes(const std::string &fmt)
std::vector< std::byte > StringToBuffer(const std::string &str)
void PassFmt(ConstevalFormatString< NumArgs > fmt)
void FailFmtWithError(const char *wrong_fmt, std::string_view error)