diff --git a/src/json-validator.cpp b/src/json-validator.cpp index f16f3ef..f497aea 100644 --- a/src/json-validator.cpp +++ b/src/json-validator.cpp @@ -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); } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 8d67e90..569e01e 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -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) diff --git a/test/issue-117-format-error.cpp b/test/issue-117-format-error.cpp new file mode 100644 index 0000000..5422e5a --- /dev/null +++ b/test/issue-117-format-error.cpp @@ -0,0 +1,69 @@ +// issue-00-format-error.cpp + +#include "nlohmann/json-schema.hpp" +#include "nlohmann/json.hpp" +#include + +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; +}