Skip to content

Commit

Permalink
More tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
trivialfis committed Jun 13, 2020
1 parent d45edc7 commit 05ddb8f
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
6 changes: 5 additions & 1 deletion include/xgboost/json_io.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,11 @@ class JsonReader {
std::string msg = "Expecting: \"";
msg += c;
msg += "\", got: \"";
msg += std::string {got} + " \"";
if (got == -1) {
msg += "EOF\"";
} else {
msg += std::to_string(got) + " \"";
}
Error(msg);
}

Expand Down
4 changes: 4 additions & 0 deletions src/common/json.cc
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,10 @@ void JsonReader::Error(std::string msg) const {
msg += ", around character position: " + std::to_string(cursor_.Pos());
msg += '\n';

if (cursor_.Pos() == 0) {
LOG(FATAL) << msg;
}

constexpr size_t kExtend = 8;
auto beg = static_cast<int64_t>(cursor_.Pos()) -
static_cast<int64_t>(kExtend) < 0 ? 0 : cursor_.Pos() - kExtend;
Expand Down
44 changes: 42 additions & 2 deletions tests/cpp/common/test_json.cc
Original file line number Diff line number Diff line change
Expand Up @@ -408,14 +408,54 @@ TEST(Json, LoadDump) {

std::ofstream fout(path);
ASSERT_TRUE(fout);
fout << out;
fout << out << std::flush;

std::string new_buffer = common::LoadSequentialFile(path);
Json load_back {Json::Load(StringView(new_buffer.c_str(), new_buffer.size()))};
ASSERT_EQ(ori_buffer, new_buffer);

Json load_back {Json::Load(StringView(new_buffer.c_str(), new_buffer.size()))};
ASSERT_EQ(load_back, origin);
}

TEST(Json, Invalid) {
{
std::string str = "}";
bool has_thrown = false;
try {
Json load{Json::Load(StringView(str.c_str(), str.size()))};
} catch (dmlc::Error const &e) {
std::string msg = e.what();
ASSERT_NE(msg.find("Unknown"), std::string::npos);
has_thrown = true;
};
ASSERT_TRUE(has_thrown);
}
{
std::string str = R"json({foo)json";
bool has_thrown = false;
try {
Json load{Json::Load(StringView(str.c_str(), str.size()))};
} catch (dmlc::Error const &e) {
std::string msg = e.what();
ASSERT_NE(msg.find("position: 1"), std::string::npos);
has_thrown = true;
};
ASSERT_TRUE(has_thrown);
}
{
std::string str = R"json({"foo")json";
bool has_thrown = false;
try {
Json load{Json::Load(StringView(str.c_str(), str.size()))};
} catch (dmlc::Error const &e) {
std::string msg = e.what();
ASSERT_NE(msg.find("EOF"), std::string::npos);
has_thrown = true;
};
ASSERT_TRUE(has_thrown);
}
}

// For now Json is quite ignorance about unicode.
TEST(Json, CopyUnicode) {
std::string json_str = R"json(
Expand Down

0 comments on commit 05ddb8f

Please sign in to comment.