Skip to content

Commit c549bd3

Browse files
committed
test: Tweak JSON integer loading
Always load integers as unsigned and cast to the required type. This will work for cases where a test case uses uint64 timestamps while we use int64.
1 parent 8ed570e commit c549bd3

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

test/statetest/statetest_loader.cpp

+5-6
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,12 @@ static std::optional<T> integer_from_json(const json::json& j)
3333
return {};
3434

3535
const auto s = j.get<std::string>();
36-
size_t num_processed = 0;
37-
T v = 0;
38-
if constexpr (std::is_same_v<T, uint64_t>)
39-
v = std::stoull(s, &num_processed, 0);
40-
else
41-
v = std::stoll(s, &num_processed, 0);
4236

37+
// Always load integers as unsigned and cast to the required type.
38+
// This will work for cases where a test case uses uint64 timestamps while we use int64.
39+
// TODO: Change timestamp type to uint64.
40+
size_t num_processed = 0;
41+
const auto v = static_cast<T>(std::stoull(s, &num_processed, 0));
4342
if (num_processed == 0 || num_processed != s.size())
4443
return {};
4544
return v;

test/unittests/statetest_loader_test.cpp

+10-3
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,16 @@ TEST(json_loader, int64_t)
5252
from_json<int64_t>(basic_json("9223372036854775807")), std::numeric_limits<int64_t>::max());
5353
EXPECT_EQ(from_json<int64_t>(basic_json("-9223372036854775808")),
5454
std::numeric_limits<int64_t>::min());
55-
EXPECT_THROW(from_json<int64_t>(basic_json("0xffffffffffffffff")), std::out_of_range);
56-
EXPECT_THROW(from_json<int64_t>(basic_json("9223372036854775808")), std::out_of_range);
57-
EXPECT_THROW(from_json<int64_t>(basic_json("-9223372036854775809")), std::out_of_range);
55+
56+
// Unfortunate conversion results:
57+
EXPECT_EQ(from_json<int64_t>(basic_json("0xffffffffffffffff")), int64_t{-1});
58+
EXPECT_EQ(
59+
from_json<int64_t>(basic_json("9223372036854775808")), std::numeric_limits<int64_t>::min());
60+
EXPECT_EQ(from_json<int64_t>(basic_json("-9223372036854775809")),
61+
std::numeric_limits<int64_t>::max());
62+
63+
EXPECT_THROW(from_json<uint64_t>(basic_json("0x10000000000000000")), std::out_of_range);
64+
EXPECT_THROW(from_json<uint64_t>(basic_json("18446744073709551616")), std::out_of_range);
5865

5966
// Octal is also supported.
6067
EXPECT_EQ(from_json<int64_t>(basic_json("0777")), 0777);

0 commit comments

Comments
 (0)