add checking about format-checker existance at schema parsing time

This commit is contained in:
andrejlevkovitch 2020-06-04 10:20:17 +03:00 committed by Patrick Boettcher
parent 80333cda2b
commit 7554b4ca70
3 changed files with 78 additions and 0 deletions

View File

@ -672,6 +672,10 @@ public:
attr = sch.find("format");
if (attr != sch.end()) {
if (root_->format_check() == nullptr) {
throw std::invalid_argument{"a format checker was not provided but a format keyword for this string is present: " + format_.second};
}
format_ = {true, attr.value()};
sch.erase(attr);
}

View File

@ -55,3 +55,8 @@ add_executable(json-patch json-patch.cpp)
target_include_directories(json-patch PRIVATE ${PROJECT_SOURCE_DIR}/src)
target_link_libraries(json-patch nlohmann_json_schema_validator)
add_test(NAME json-patch COMMAND json-patch)
# Unit test for format checker fail at schema parsing time
add_executable(issue-117-format-error issue-117-format-error.cpp)
target_link_libraries(issue-117-format-error nlohmann_json_schema_validator)
add_test(NAME issue-117-format-error COMMAND issue-117-format-error)

View File

@ -0,0 +1,69 @@
// issue-00-format-error.cpp
#include "nlohmann/json-schema.hpp"
#include "nlohmann/json.hpp"
#include <iostream>
static int error_count = 0;
#define CHECK_THROW(x, msg) \
{ \
bool fail = false; \
try { \
x; \
} catch (std::exception &) { \
fail = true; \
} \
if (fail == false) { \
++error_count; \
std::cout << msg << std::endl; \
} \
}
#define CHECK_NO_THROW(x, msg) \
{ \
bool fail = false; \
std::string exception_error; \
try { \
x; \
} catch (std::exception & e) { \
fail = true; \
exception_error = e.what(); \
} \
if (fail == true) { \
++error_count; \
std::cout << msg << ": " << exception_error << std::endl; \
} \
}
using json = nlohmann::json;
using validator = nlohmann::json_schema::json_validator;
json schema_with_format = json::parse(R"(
{
"type": "object",
"properties": {
"str": {
"type": "string",
"format": "placeholder"
}
}
}
)");
int main()
{
// check that if we get validator without format checker we get error at schema loading
validator without_format_checker;
CHECK_THROW(without_format_checker.set_root_schema(schema_with_format), "validator without format checker must fail at schema loading");
// check that with format checker all works fine
validator with_format_checker{nullptr, [](const std::string &, const std::string &) {}};
CHECK_NO_THROW(with_format_checker.set_root_schema(schema_with_format), "schema must be succesed by validator with format checker");
CHECK_NO_THROW(with_format_checker.validate(json{{"str", "placeholder"}}), "validator must not throw while validation schema with format");
return error_count;
}