| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- // v2.16.0 - the collection-schema validator and suggester, in isolation.
- //
- // What must hold: every supported keyword refuses what it should and accepts
- // what it should; an unsupported keyword is refused at compile time (so a
- // schema can never look stricter than what is enforced); lengths count
- // characters, not bytes; and a suggested schema accepts every row it was
- // suggested from.
- #include "schema/json_schema.hpp"
- #include <iostream>
- #include <string>
- using nlohmann::json;
- namespace sc = smartbotic::db::schema;
- static int pass = 0, fail = 0;
- static void ck(bool c, const std::string& m) {
- if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
- }
- static std::shared_ptr<const sc::CompiledSchema> compiled(const json& s) {
- auto r = sc::compile(s);
- if (!r.schema) std::cerr << "compile error: " << r.error << "\n";
- return r.schema;
- }
- static bool ok(const sc::CompiledSchema& s, const json& d) { return s.validate(d).empty(); }
- static std::string firstKeyword(const sc::CompiledSchema& s, const json& d) {
- auto v = s.validate(d);
- return v.empty() ? "" : v.front().keyword;
- }
- static std::string firstPath(const sc::CompiledSchema& s, const json& d) {
- auto v = s.validate(d);
- return v.empty() ? "<none>" : v.front().path;
- }
- static void test_the_owner_example() {
- // "optional key 'name', max length 128, varchar": 130 is refused.
- auto s = compiled({{"type", "object"},
- {"properties", {{"name", {{"type", "string"}, {"maxLength", 128}}}}}});
- ck(s != nullptr, "example compiles");
- ck(ok(*s, {{"name", std::string(128, 'a')}}), "name of 128 accepted");
- ck(firstKeyword(*s, {{"name", std::string(130, 'a')}}) == "maxLength", "name of 130 refused by maxLength");
- ck(firstPath(*s, {{"name", std::string(130, 'a')}}) == "name", "the violation names the field");
- ck(ok(*s, json::object()), "name is optional");
- ck(ok(*s, {{"other", 1}}), "other keys allowed by default (additionalProperties defaults to true)");
- auto msg = s->validate({{"name", std::string(130, 'a')}}).front().message;
- ck(msg.find("130") != std::string::npos && msg.find("128") != std::string::npos,
- "the message gives the size and the limit: " + msg);
- }
- static void test_lengths_are_characters() {
- auto s = compiled({{"properties", {{"n", {{"type", "string"}, {"maxLength", 3}, {"minLength", 2}}}}}});
- ck(ok(*s, {{"n", "\xC3\xA1\xC3\xA9\xC3\xAD"}}), "3 two-byte characters (6 bytes) fit maxLength 3");
- ck(firstKeyword(*s, {{"n", "\xC3\xA1\xC3\xA9\xC3\xAD\xC3\xB3"}}) == "maxLength", "4 characters do not");
- ck(firstKeyword(*s, {{"n", "\xF0\x9F\x98\x80"}}) == "minLength", "one 4-byte emoji is 1 character");
- }
- static void test_types() {
- auto s = compiled({{"properties", {
- {"i", {{"type", "integer"}}}, {"n", {{"type", "number"}}}, {"b", {{"type", "boolean"}}},
- {"z", {{"type", "null"}}}, {"a", {{"type", "array"}}}, {"o", {{"type", "object"}}},
- {"sn", {{"type", json::array({"string", "null"})}}}}}});
- ck(ok(*s, {{"i", 5}}), "integer 5");
- ck(ok(*s, {{"i", 5.0}}), "5.0 is an integer (JSON Schema)");
- ck(firstKeyword(*s, {{"i", 5.5}}) == "type", "5.5 is not an integer");
- ck(firstKeyword(*s, {{"i", "5"}}) == "type", "\"5\" is not an integer");
- ck(ok(*s, {{"n", 5}}) && ok(*s, {{"n", 5.5}}), "number takes both");
- ck(firstKeyword(*s, {{"b", 1}}) == "type", "1 is not a boolean");
- ck(ok(*s, {{"z", nullptr}}), "null");
- ck(ok(*s, {{"a", json::array()}}) && firstKeyword(*s, {{"a", json::object()}}) == "type", "array vs object");
- ck(ok(*s, {{"o", json::object()}}), "object");
- ck(ok(*s, {{"sn", "x"}}) && ok(*s, {{"sn", nullptr}}) && firstKeyword(*s, {{"sn", 1}}) == "type",
- "type array: string or null");
- }
- static void test_required_and_additional() {
- auto s = compiled({{"type", "object"}, {"required", {"id", "name"}},
- {"properties", {{"id", {{"type", "integer"}}}, {"name", {{"type", "string"}}}}},
- {"additionalProperties", false}});
- ck(ok(*s, {{"id", 1}, {"name", "x"}}), "exact keys accepted");
- ck(firstKeyword(*s, {{"id", 1}}) == "required", "missing required name");
- ck(firstPath(*s, {{"id", 1}}) == "name", "required violation names the missing key");
- ck(firstKeyword(*s, {{"id", 1}, {"name", "x"}, {"extra", 2}}) == "additionalProperties", "extra key refused");
- ck(ok(*s, {{"id", 1}, {"name", nullptr}}) == false, "null is not a string");
- auto t = compiled({{"additionalProperties", {{"type", "integer"}}}});
- ck(ok(*t, {{"a", 1}, {"b", 2}}) && firstKeyword(*t, {{"a", "x"}}) == "type",
- "additionalProperties as a schema applies to unlisted keys");
- auto u = compiled({{"minProperties", 1}, {"maxProperties", 2}});
- ck(firstKeyword(*u, json::object()) == "minProperties", "minProperties");
- ck(firstKeyword(*u, {{"a", 1}, {"b", 1}, {"c", 1}}) == "maxProperties", "maxProperties");
- }
- static void test_nested_and_arrays() {
- auto s = compiled({{"properties", {
- {"addr", {{"type", "object"}, {"required", {"zip"}},
- {"properties", {{"zip", {{"type", "string"}, {"pattern", "^[0-9]{4}$"}}}}}}},
- {"tags", {{"type", "array"}, {"items", {{"type", "string"}, {"maxLength", 5}}},
- {"minItems", 1}, {"maxItems", 3}, {"uniqueItems", true}}}}}});
- ck(ok(*s, {{"addr", {{"zip", "1234"}}}, {"tags", {"a", "b"}}}), "nested ok");
- ck(firstPath(*s, {{"addr", {{"zip", "12a4"}}}}) == "addr.zip", "nested path is dotted");
- ck(firstKeyword(*s, {{"addr", {{"zip", "12a4"}}}}) == "pattern", "pattern");
- ck(firstPath(*s, {{"addr", json::object()}}) == "addr.zip", "nested required");
- ck(firstPath(*s, {{"tags", {"a", "toolong"}}}) == "tags[1]", "array element path");
- ck(firstKeyword(*s, {{"tags", json::array()}}) == "minItems", "minItems");
- ck(firstKeyword(*s, {{"tags", {"a", "b", "c", "d"}}}) == "maxItems", "maxItems");
- ck(firstKeyword(*s, {{"tags", {"a", "a"}}}) == "uniqueItems", "uniqueItems");
- }
- static void test_numbers_enum_const_format() {
- auto s = compiled({{"properties", {
- {"age", {{"type", "integer"}, {"minimum", 0}, {"maximum", 150}}},
- {"p", {{"exclusiveMinimum", 0}, {"exclusiveMaximum", 1}}},
- {"status", {{"enum", {"active", "disabled"}}}},
- {"v", {{"const", 2}}},
- {"at", {{"type", "string"}, {"format", "date-time"}}},
- {"d", {{"format", "date"}}},
- {"u", {{"format", "uuid"}}},
- {"e", {{"format", "email"}}}}}});
- ck(ok(*s, {{"age", 0}}) && ok(*s, {{"age", 150}}), "inclusive bounds");
- ck(firstKeyword(*s, {{"age", -1}}) == "minimum" && firstKeyword(*s, {{"age", 151}}) == "maximum", "bounds");
- ck(firstKeyword(*s, {{"p", 0}}) == "exclusiveMinimum" && firstKeyword(*s, {{"p", 1}}) == "exclusiveMaximum" &&
- ok(*s, {{"p", 0.5}}), "exclusive bounds");
- ck(ok(*s, {{"status", "active"}}) && firstKeyword(*s, {{"status", "gone"}}) == "enum", "enum");
- ck(ok(*s, {{"v", 2.0}}) && firstKeyword(*s, {{"v", 3}}) == "const", "const compares numbers by value");
- ck(ok(*s, {{"at", "2026-10-09T14:27:00Z"}}) && ok(*s, {{"at", "2026-10-09T14:27:00.123+02:00"}}),
- "date-time accepted");
- ck(firstKeyword(*s, {{"at", "2026-13-09T14:27:00Z"}}) == "format", "month 13 refused");
- ck(firstKeyword(*s, {{"at", "2026-10-09 14:27:00"}}) == "format", "no T/zone refused");
- ck(ok(*s, {{"d", "2024-02-29"}}) && firstKeyword(*s, {{"d", "2025-02-29"}}) == "format", "leap years");
- ck(ok(*s, {{"u", "123e4567-e89b-12d3-a456-426614174000"}}) && firstKeyword(*s, {{"u", "123"}}) == "format", "uuid");
- ck(ok(*s, {{"e", "a@b.co"}}) && firstKeyword(*s, {{"e", "a@b"}}) == "format" &&
- firstKeyword(*s, {{"e", "a b@c.d"}}) == "format", "email");
- ck(ok(*s, {{"d", 5}}), "format applies to strings only");
- }
- static void test_refusals_at_compile() {
- for (const char* kw : {"$ref", "allOf", "anyOf", "oneOf", "not", "if", "patternProperties",
- "multipleOf", "dependentRequired", "$defs", "prefixItems"}) {
- auto r = sc::compile({{kw, json::object()}});
- ck(!r.schema && r.error.find(kw) != std::string::npos, std::string("refused: ") + kw);
- }
- ck(!sc::compile({{"properties", {{"a", {{"maxLength", -1}}}}}}).schema, "negative maxLength");
- ck(!sc::compile({{"properties", {{"a", {{"pattern", "(unclosed"}}}}}}).schema, "bad pattern");
- ck(!sc::compile({{"properties", {{"a", {{"pattern", "(a)\\1"}}}}}}).schema, "backreference (not RE2)");
- ck(!sc::compile({{"format", "ipv4"}}).schema, "unknown format");
- ck(!sc::compile({{"type", "string"}}).schema, "root must accept an object");
- ck(!sc::compile({{"type", "strng"}}).schema, "unknown type name");
- ck(!sc::compile(json::array()).schema, "schema must be an object");
- ck(!sc::compile({{"items", json::array({json::object()})}}).schema, "tuple items refused");
- auto r = sc::compile({{"title", "t"}, {"description", "d"}, {"$schema", "x"}, {"default", 1},
- {"examples", json::array()}, {"$comment", "c"}});
- ck(r.schema != nullptr, "annotations accepted");
- auto f = compiled({{"properties", {{"x", false}, {"y", true}}}});
- ck(firstKeyword(*f, {{"x", 1}}) == "false" && ok(*f, {{"y", "anything"}}), "boolean subschemas");
- }
- static void test_violation_cap_and_total() {
- auto s = compiled({{"additionalProperties", false}});
- json d = json::object();
- for (int i = 0; i < 25; ++i) d["k" + std::to_string(i)] = i;
- size_t total = 0;
- auto v = s->validate(d, 10, &total);
- ck(v.size() == 10 && total == 25, "capped at 10, total 25");
- ck(sc::summarize(v, total).find("and 15 more") != std::string::npos, "summary says how many more");
- }
- static void test_suggest() {
- sc::SchemaSuggester g;
- std::vector<json> rows;
- for (int i = 0; i < 30; ++i) {
- json d = {{"name", "user" + std::to_string(i)},
- {"age", i},
- {"score", i * 0.5},
- {"status", i % 2 ? "active" : "disabled"},
- {"created", "2026-10-09T14:27:00Z"},
- {"uid", "123e4567-e89b-12d3-a456-42661417400" + std::to_string(i % 10)},
- {"tags", {"t" + std::to_string(i % 3)}},
- {"addr", {{"zip", "1234"}, {"city", "x"}}}};
- if (i % 3 == 0) d["nick"] = nullptr;
- if (i % 5 == 0) d["note"] = "optional";
- rows.push_back(d);
- g.add(d);
- }
- const json s = g.result();
- ck(g.rows() == 30, "30 rows observed");
- auto c = sc::compile(s);
- ck(c.schema != nullptr, "the suggestion compiles: " + c.error);
- if (!c.schema) return;
- bool all = true;
- for (const auto& r : rows) all = all && c.schema->validate(r).empty();
- ck(all, "EVERY suggested-from row conforms to the suggestion");
- ck(s["properties"]["age"]["type"] == "integer", "integral numbers -> integer");
- ck(s["properties"]["score"]["type"] == "number", "fractional -> number");
- ck(s["properties"]["status"].contains("enum") && s["properties"]["status"]["enum"].size() == 2,
- "small closed set -> enum");
- ck(!s["properties"]["name"].contains("enum"), "30 distinct names are not an enum");
- ck(s["properties"]["created"]["format"] == "date-time", "date-time detected");
- ck(s["properties"]["uid"]["format"] == "uuid", "uuid detected");
- ck(s["properties"]["nick"]["type"] == "null", "a field only ever null");
- const auto req = s["required"];
- auto has = [&](const char* k) { return std::find(req.begin(), req.end(), k) != req.end(); };
- ck(has("name") && has("age") && !has("note") && !has("nick"), "required = present in every row");
- ck(s["additionalProperties"] == false, "additionalProperties false at the root");
- ck(s["properties"]["addr"]["additionalProperties"] == false && s["properties"]["addr"]["required"].size() == 2,
- "nested objects described too");
- ck(s["properties"]["tags"]["items"]["type"] == "string", "array items described");
- ck(!s["properties"]["name"].contains("maxLength") &&
- s["properties"]["name"]["description"].get<std::string>().find("observed length") != std::string::npos,
- "lengths are reported, not enforced");
- ck(c.schema->validate({{"name", "x"}}).size() > 0, "a row missing required fields is refused");
- sc::SchemaSuggester empty;
- auto e = sc::compile(empty.result());
- ck(e.schema && e.schema->validate({{"anything", 1}}).empty(), "no rows -> any object");
- sc::SchemaSuggester mixed;
- mixed.add({{"v", 1}});
- mixed.add({{"v", "x"}});
- mixed.add({{"v", 2.5}});
- auto m = mixed.result();
- auto mc = sc::compile(m);
- ck(mc.schema && mc.schema->validate({{"v", 1}}).empty() && mc.schema->validate({{"v", "x"}}).empty() &&
- mc.schema->validate({{"v", 2.5}}).empty(), "mixed types -> a type union that accepts each");
- }
- int main() {
- test_the_owner_example();
- test_lengths_are_characters();
- test_types();
- test_required_and_additional();
- test_nested_and_arrays();
- test_numbers_enum_const_format();
- test_refusals_at_compile();
- test_violation_cap_and_total();
- test_suggest();
- std::cout << "test_json_schema: " << pass << " passed, " << fail << " failed\n";
- return fail == 0 ? 0 : 1;
- }
|