fix #93 by returning default-values for refs

and also return them for root-schemas
This commit is contained in:
Patrick Boettcher 2020-03-23 22:43:42 +01:00 committed by Patrick Boettcher
parent cb95425f59
commit 940262ceae
7 changed files with 93 additions and 3 deletions

View File

@ -75,7 +75,7 @@ class schema_ref : public schema
const json &defaultValue(const json::json_pointer &ptr, const json &instance, error_handler &e) const override
{
if (target_)
target_->defaultValue(ptr, instance, e);
return target_->defaultValue(ptr, instance, e);
else
e.error(ptr, instance, "unresolved schema-reference " + id_);
@ -241,7 +241,7 @@ public:
const json &defaultValue(const json::json_pointer &ptr, const json &instance, error_handler &e) const override
{
if (root_)
root_->defaultValue(ptr, instance, e);
return root_->defaultValue(ptr, instance, e);
else
e.error(ptr, "", "no root schema has yet been set for validating an instance");

View File

@ -0,0 +1,7 @@
add_executable(issue-93 issue-93.cpp)
target_link_libraries(issue-93 nlohmann_json_schema_validator)
add_test(NAME issue-93
COMMAND issue-93
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

View File

@ -0,0 +1,11 @@
{
"type":"array",
"items": {
"type":"object",
"properties": {
"renderable": {
"$ref":"/components.schema.json#/Renderable"
}
}
}
}

View File

@ -0,0 +1,13 @@
{
"Renderable": {
"type":"object",
"properties": {
"fg":{
"$ref":"/types/color.schema.json"
},
"bg":{
"$ref":"/types/color.schema.json"
}
}
}
}

View File

@ -0,0 +1,55 @@
#include <nlohmann/json-schema.hpp>
#include <fstream>
#include <iostream>
using nlohmann::json;
using nlohmann::json_uri;
using nlohmann::json_schema::json_validator;
static const auto expected_patch = R"(
[{"op":"add","path":"/0/renderable/bg","value":"Black"}]
)"_json;
static const auto instance = R"(
[
{
"name":"player",
"renderable": {
"fg":"White"
}
}
]
)"_json;
static void loader(const json_uri &uri, json &schema)
{
std::string filename = "./" + uri.path();
std::ifstream lf(filename);
if (!lf.good())
throw std::invalid_argument("could not open " + uri.url() + " tried with " + filename);
try {
lf >> schema;
} catch (const std::exception &e) {
throw e;
}
}
int main(void)
{
json_validator validator(loader);
std::fstream f("blueprints.schema.json");
json schema;
f >> schema;
validator.set_root_schema(schema);
auto missing_default_patch = validator.validate(instance);
std::cerr << missing_default_patch << "\n";
std::cerr << expected_patch << "\n";
return missing_default_patch != expected_patch;
}

View File

@ -0,0 +1,4 @@
{
"type":"string",
"default":"Black"
}

View File

@ -1,7 +1,7 @@
#!/bin/bash
# all argument are considered as a program to call (with its arguments),
# the last argument is read from via '<'
# the last argument is read from stdin via '<'
set -e