Skip to content

Commit

Permalink
test: Tweak JSON integer loading
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
chfast committed Nov 24, 2023
1 parent 8ed570e commit c549bd3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
11 changes: 5 additions & 6 deletions test/statetest/statetest_loader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ static std::optional<T> integer_from_json(const json::json& j)
return {};

const auto s = j.get<std::string>();
size_t num_processed = 0;
T v = 0;
if constexpr (std::is_same_v<T, uint64_t>)
v = std::stoull(s, &num_processed, 0);
else
v = std::stoll(s, &num_processed, 0);

// 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.
// TODO: Change timestamp type to uint64.
size_t num_processed = 0;
const auto v = static_cast<T>(std::stoull(s, &num_processed, 0));
if (num_processed == 0 || num_processed != s.size())
return {};
return v;
Expand Down
13 changes: 10 additions & 3 deletions test/unittests/statetest_loader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,16 @@ TEST(json_loader, int64_t)
from_json<int64_t>(basic_json("9223372036854775807")), std::numeric_limits<int64_t>::max());
EXPECT_EQ(from_json<int64_t>(basic_json("-9223372036854775808")),
std::numeric_limits<int64_t>::min());
EXPECT_THROW(from_json<int64_t>(basic_json("0xffffffffffffffff")), std::out_of_range);
EXPECT_THROW(from_json<int64_t>(basic_json("9223372036854775808")), std::out_of_range);
EXPECT_THROW(from_json<int64_t>(basic_json("-9223372036854775809")), std::out_of_range);

// Unfortunate conversion results:
EXPECT_EQ(from_json<int64_t>(basic_json("0xffffffffffffffff")), int64_t{-1});
EXPECT_EQ(
from_json<int64_t>(basic_json("9223372036854775808")), std::numeric_limits<int64_t>::min());
EXPECT_EQ(from_json<int64_t>(basic_json("-9223372036854775809")),
std::numeric_limits<int64_t>::max());

EXPECT_THROW(from_json<uint64_t>(basic_json("0x10000000000000000")), std::out_of_range);
EXPECT_THROW(from_json<uint64_t>(basic_json("18446744073709551616")), std::out_of_range);

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

0 comments on commit c549bd3

Please sign in to comment.