MQTTSuite
Loading...
Searching...
No Matches
issue-189-default-values.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <nlohmann/json-schema.hpp>
3
4using nlohmann::json;
5using nlohmann::json_uri;
6using nlohmann::json_schema::json_validator;
7
8static const json rectangle_schema = R"(
9{
10 "$schema": "http://json-schema.org/draft-07/schema#",
11 "properties": {
12 "width": {
13 "$ref": "#/definitions/length",
14 "default": 20
15 },
16 "height": {
17 "$ref": "#/definitions/length"
18 }
19 },
20 "definitions": {
21 "length": {
22 "type": "integer",
23 "default": 10
24 }
25 }
26})"_json;
27
28static const json quad_schema = R"(
29{
30 "$schema": "http://json-schema.org/draft-07/schema#",
31 "properties": {
32 "width": {
33 "$ref": "#/properties/height",
34 "default": 20
35 },
36 "height": {
37 "$ref": "#/definitions/length"
38 },
39 "depth": {
40 "$ref": "default_schema#/definitions/defaultLength"
41 },
42 "time": {
43 "$ref": "#/definitions/time"
44 }
45 },
46 "definitions": {
47 "length": {
48 "$ref": "default_schema#/definitions/defaultLength",
49 "default": 10
50 },
51 "time": {
52 "type": "integer",
53 "default": 15
54 }
55 }
56})"_json;
57
58static const json default_schema = R"(
59{
60 "$schema": "http://json-schema.org/draft-07/schema#",
61 "definitions": {
62 "defaultLength": {
63 "default": 5
64 }
65 }
66})"_json;
67
68static void loader(const json_uri &uri, json &schema)
69{
70 schema = default_schema;
71}
72
73int main(void)
74{
75 json_validator validator(loader);
76
78
79 {
80 json empty_quad = R"({})"_json;
81
82 const auto default_patch = validator.validate(empty_quad);
83 const auto actual = empty_quad.patch(default_patch);
84
85 const auto expected = R"({"height":10,"width":20,"depth":5,"time":15})"_json;
86 if (actual != expected) {
87 std::cerr << "Patch with defaults contains wrong value: '" << actual << "' instead of expected '" << expected.dump() << "'" << std::endl;
88 return 1;
89 }
90 }
91
93
94 {
95 json empty_rectangle = R"({})"_json;
96
97 const auto default_patch = validator.validate(empty_rectangle);
98 const auto actual = empty_rectangle.patch(default_patch);
99
100 // height must be 10 according to the default specified in the length definition while width must be 10 overridden by the width element
101 const auto expected = R"({"height":10,"width":20})"_json;
102 if (actual != expected) {
103 std::cerr << "Patch with defaults contains wrong value: '" << actual << "' instead of expected '" << expected.dump() << "'" << std::endl;
104 return 1;
105 }
106 }
107
108 return 0;
109}
json_validator(schema_loader=nullptr, format_checker=nullptr, content_checker=nullptr)
int main()
Definition format.cpp:34
static const json quad_schema
static void loader(const json_uri &uri, json &schema)
static const json default_schema
static const json rectangle_schema