Merge remote-tracking branch 'origin/fix/section_10_03' into fix/various

This commit is contained in:
opsocket 2023-01-30 19:05:03 -05:00
commit c8657d9b27
3 changed files with 48 additions and 1 deletions

View File

@ -503,6 +503,7 @@ class type_schema : public schema
std::vector<std::shared_ptr<schema>> type_;
std::pair<bool, json> enum_, const_;
std::vector<std::shared_ptr<schema>> logic_;
bool read_only_ = false;
static std::shared_ptr<schema> make(json &schema,
json::value_t type,
@ -553,8 +554,15 @@ class type_schema : public schema
else_->validate(ptr, instance, patch, e);
}
}
if (instance.is_null()) {
if (instance.is_null())
patch.add(nlohmann::json::json_pointer{}, default_value_);
// enforce default value if any read only values
if(read_only_) {
auto rod_value = default_value(ptr, instance, e);
if(rod_value != nullptr && instance != rod_value)
e.error(ptr, instance, "key is read-only");
}
}
@ -623,6 +631,12 @@ public:
sch.erase(attr);
}
attr = sch.find("readOnly");
if (attr != sch.end()) {
read_only_ = attr.value().get<bool>();
sch.erase(attr);
}
for (auto &key : known_keywords)
sch.erase(key);
@ -1460,3 +1474,4 @@ json json_validator::validate(const json &instance, error_handler &err, const js
} // namespace json_schema
} // namespace nlohmann

View File

@ -77,3 +77,7 @@ add_test(NAME issue-189-default-values COMMAND issue-189-default-values)
add_executable(issue-243-root-default-values issue-243-root-default-values.cpp)
target_link_libraries(issue-243-root-default-values nlohmann_json_schema_validator)
add_test(NAME issue-243-root-default-values COMMAND issue-243-root-default-values)
add_executable(issue-212-read-only-values read-only-values.cpp)
target_link_libraries(issue-212-read-only-values nlohmann_json_schema_validator)
add_test(NAME issue-212-read-only-values COMMAND issue-212-read-only-values)

28
test/read-only-values.cpp Normal file
View File

@ -0,0 +1,28 @@
#include <nlohmann/json-schema.hpp>
using nlohmann::json;
using nlohmann::json_schema::json_validator;
static const json read_only_schema = R"({
"type": "object",
"properties": {
"debug": {
"type": "boolean",
"default": false,
"readOnly": true
}
}
})"_json;
int main() {
json_validator validator(read_only_schema);
try {
validator.validate(R"({
"debug": true
})"_json);
} catch (const std::exception&e ) {
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}