schematest.cpp 46.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Tencent is pleased to support the open source community by making RapidJSON available.
// 
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed 
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
// CONDITIONS OF ANY KIND, either express or implied. See the License for the 
// specific language governing permissions and limitations under the License.

#include "unittest.h"
#include "rapidjson/schema.h"
17
#include "rapidjson/stringbuffer.h"
18
#include "rapidjson/writer.h"
19

20 21 22 23 24
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(variadic-macros)
#endif

25 26
using namespace rapidjson;

miloyip's avatar
miloyip committed
27 28 29 30 31 32 33 34 35 36
#define TEST_HASHER(json1, json2, expected) \
{\
    Document d1, d2;\
    d1.Parse(json1);\
    ASSERT_FALSE(d1.HasParseError());\
    d2.Parse(json2);\
    ASSERT_FALSE(d2.HasParseError());\
    internal::Hasher<Value, CrtAllocator> h1, h2;\
    d1.Accept(h1);\
    d2.Accept(h2);\
miloyip's avatar
miloyip committed
37 38
    ASSERT_TRUE(h1.IsValid());\
    ASSERT_TRUE(h2.IsValid());\
miloyip's avatar
miloyip committed
39
    /*printf("%s: 0x%016llx\n%s: 0x%016llx\n\n", json1, h1.GetHashCode(), json2, h2.GetHashCode());*/\
miloyip's avatar
miloyip committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53
    EXPECT_TRUE(expected == (h1.GetHashCode() == h2.GetHashCode()));\
}

TEST(SchemaValidator, Hasher) {
    TEST_HASHER("null", "null", true);

    TEST_HASHER("true", "true", true);
    TEST_HASHER("false", "false", true);
    TEST_HASHER("true", "false", false);
    TEST_HASHER("false", "true", false);
    TEST_HASHER("true", "null", false);
    TEST_HASHER("false", "null", false);

    TEST_HASHER("1", "1", true);
54 55 56 57
    TEST_HASHER("2147483648", "2147483648", true); // 2^31 can only be fit in unsigned
    TEST_HASHER("-2147483649", "-2147483649", true); // -2^31 - 1 can only be fit in int64_t
    TEST_HASHER("2147483648", "2147483648", true); // 2^31 can only be fit in unsigned
    TEST_HASHER("4294967296", "4294967296", true); // 2^32 can only be fit in int64_t
58
    TEST_HASHER("9223372036854775808", "9223372036854775808", true); // 2^63 can only be fit in uint64_t
miloyip's avatar
miloyip committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    TEST_HASHER("1.5", "1.5", true);
    TEST_HASHER("1", "1.0", true);
    TEST_HASHER("1", "-1", false);
    TEST_HASHER("0.0", "-0.0", false);
    TEST_HASHER("1", "true", false);
    TEST_HASHER("0", "false", false);
    TEST_HASHER("0", "null", false);

    TEST_HASHER("\"\"", "\"\"", true);
    TEST_HASHER("\"\"", "\"\\u0000\"", false);
    TEST_HASHER("\"Hello\"", "\"Hello\"", true);
    TEST_HASHER("\"Hello\"", "\"World\"", false);
    TEST_HASHER("\"Hello\"", "null", false);
    TEST_HASHER("\"Hello\\u0000\"", "\"Hello\"", false);
    TEST_HASHER("\"\"", "null", false);
    TEST_HASHER("\"\"", "true", false);
    TEST_HASHER("\"\"", "false", false);

    TEST_HASHER("[]", "[ ]", true);
    TEST_HASHER("[1, true, false]", "[1, true, false]", true);
    TEST_HASHER("[1, true, false]", "[1, true]", false);
    TEST_HASHER("[1, 2]", "[2, 1]", false);
    TEST_HASHER("[[1], 2]", "[[1, 2]]", false);
    TEST_HASHER("[1, 2]", "[1, [2]]", false);
    TEST_HASHER("[]", "null", false);
    TEST_HASHER("[]", "true", false);
    TEST_HASHER("[]", "false", false);
    TEST_HASHER("[]", "0", false);
    TEST_HASHER("[]", "0.0", false);
    TEST_HASHER("[]", "\"\"", false);

    TEST_HASHER("{}", "{ }", true);
    TEST_HASHER("{\"a\":1}", "{\"a\":1}", true);
    TEST_HASHER("{\"a\":1}", "{\"b\":1}", false);
    TEST_HASHER("{\"a\":1}", "{\"a\":2}", false);
    TEST_HASHER("{\"a\":1, \"b\":2}", "{\"b\":2, \"a\":1}", true); // Member order insensitive
    TEST_HASHER("{}", "null", false);
    TEST_HASHER("{}", "false", false);
    TEST_HASHER("{}", "true", false);
    TEST_HASHER("{}", "0", false);
    TEST_HASHER("{}", "0.0", false);
    TEST_HASHER("{}", "\"\"", false);
}

103 104 105 106 107 108
// Test cases following http://spacetelescope.github.io/understanding-json-schema

#define VALIDATE(schema, json, expected) \
{\
    SchemaValidator validator(schema);\
    Document d;\
109
    /*printf("\n%s\n", json);*/\
110 111
    d.Parse(json);\
    EXPECT_FALSE(d.HasParseError());\
miloyip's avatar
miloyip committed
112 113
    EXPECT_TRUE(expected == d.Accept(validator));\
    EXPECT_TRUE(expected == validator.IsValid());\
miloyip's avatar
miloyip committed
114
    if (expected && !validator.IsValid()) {\
115 116
        StringBuffer sb;\
        validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);\
miloyip's avatar
miloyip committed
117 118
        printf("Invalid schema: %s\n", sb.GetString());\
        printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());\
119 120
        sb.Clear();\
        validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);\
miloyip's avatar
miloyip committed
121 122
        printf("Invalid document: %s\n", sb.GetString());\
    }\
123 124
}

miloyip's avatar
miloyip committed
125
#define INVALIDATE(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer) \
126 127 128
{\
    SchemaValidator validator(schema);\
    Document d;\
129
    /*printf("\n%s\n", json);*/\
130 131 132 133 134 135 136 137 138 139
    d.Parse(json);\
    EXPECT_FALSE(d.HasParseError());\
    EXPECT_FALSE(d.Accept(validator));\
    EXPECT_FALSE(validator.IsValid());\
    if (validator.GetInvalidSchemaPointer() != Pointer(invalidSchemaPointer)) {\
        StringBuffer sb;\
        validator.GetInvalidSchemaPointer().Stringify(sb);\
        printf("GetInvalidSchemaPointer() Expected: %s Actual: %s\n", invalidSchemaPointer, sb.GetString());\
        ADD_FAILURE();\
    }\
140
    ASSERT_TRUE(validator.GetInvalidSchemaKeyword() != 0);\
miloyip's avatar
miloyip committed
141 142 143 144
    if (strcmp(validator.GetInvalidSchemaKeyword(), invalidSchemaKeyword) != 0) {\
        printf("GetInvalidSchemaKeyword() Expected: %s Actual %s\n", invalidSchemaKeyword, validator.GetInvalidSchemaKeyword());\
        ADD_FAILURE();\
    }\
145 146 147 148 149 150
    if (validator.GetInvalidDocumentPointer() != Pointer(invalidDocumentPointer)) {\
        StringBuffer sb;\
        validator.GetInvalidDocumentPointer().Stringify(sb);\
        printf("GetInvalidDocumentPointer() Expected: %s Actual: %s\n", invalidDocumentPointer, sb.GetString());\
        ADD_FAILURE();\
    }\
151 152 153 154 155
}

TEST(SchemaValidator, Typeless) {
    Document sd;
    sd.Parse("{}");
Milo Yip's avatar
Milo Yip committed
156
    SchemaDocument s(sd);
157 158 159 160 161 162
    
    VALIDATE(s, "42", true);
    VALIDATE(s, "\"I'm a string\"", true);
    VALIDATE(s, "{ \"an\": [ \"arbitrarily\", \"nested\" ], \"data\": \"structure\" }", true);
}

miloyip's avatar
miloyip committed
163 164 165
TEST(SchemaValidator, MultiType) {
    Document sd;
    sd.Parse("{ \"type\": [\"number\", \"string\"] }");
Milo Yip's avatar
Milo Yip committed
166
    SchemaDocument s(sd);
miloyip's avatar
miloyip committed
167 168 169

    VALIDATE(s, "42", true);
    VALIDATE(s, "\"Life, the universe, and everything\"", true);
miloyip's avatar
miloyip committed
170
    INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", "");
miloyip's avatar
miloyip committed
171 172
}

173 174 175
TEST(SchemaValidator, Enum_Typed) {
    Document sd;
    sd.Parse("{ \"type\": \"string\", \"enum\" : [\"red\", \"amber\", \"green\"] }");
Milo Yip's avatar
Milo Yip committed
176
    SchemaDocument s(sd);
177 178

    VALIDATE(s, "\"red\"", true);
miloyip's avatar
miloyip committed
179
    INVALIDATE(s, "\"blue\"", "", "enum", "");
180 181 182 183 184
}

TEST(SchemaValidator, Enum_Typless) {
    Document sd;
    sd.Parse("{  \"enum\": [\"red\", \"amber\", \"green\", null, 42] }");
Milo Yip's avatar
Milo Yip committed
185
    SchemaDocument s(sd);
186 187 188 189

    VALIDATE(s, "\"red\"", true);
    VALIDATE(s, "null", true);
    VALIDATE(s, "42", true);
miloyip's avatar
miloyip committed
190
    INVALIDATE(s, "0", "", "enum", "");
191 192 193 194 195
}

TEST(SchemaValidator, Enum_InvalidType) {
    Document sd;
    sd.Parse("{ \"type\": \"string\", \"enum\": [\"red\", \"amber\", \"green\", null] }");
Milo Yip's avatar
Milo Yip committed
196
    SchemaDocument s(sd);
197 198

    VALIDATE(s, "\"red\"", true);
miloyip's avatar
miloyip committed
199
    INVALIDATE(s, "null", "", "type", "");
200 201
}

202 203 204
TEST(SchemaValidator, AllOf) {
    {
        Document sd;
205
        sd.Parse("{\"allOf\": [{ \"type\": \"string\" }, { \"type\": \"string\", \"maxLength\": 5 }]}");
Milo Yip's avatar
Milo Yip committed
206
        SchemaDocument s(sd);
207

208
        VALIDATE(s, "\"ok\"", true);
miloyip's avatar
miloyip committed
209
        INVALIDATE(s, "\"too long\"", "", "allOf", "");
210 211 212 213
    }
    {
        Document sd;
        sd.Parse("{\"allOf\": [{ \"type\": \"string\" }, { \"type\": \"number\" } ] }");
Milo Yip's avatar
Milo Yip committed
214
        SchemaDocument s(sd);
215 216

        VALIDATE(s, "\"No way\"", false);
miloyip's avatar
miloyip committed
217
        INVALIDATE(s, "-1", "", "allOf", "");
218 219 220 221 222 223
    }
}

TEST(SchemaValidator, AnyOf) {
    Document sd;
    sd.Parse("{\"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"number\" } ] }");
Milo Yip's avatar
Milo Yip committed
224
    SchemaDocument s(sd);
225

miloyip's avatar
miloyip committed
226 227 228
    VALIDATE(s, "\"Yes\"", true);
    VALIDATE(s, "42", true);
    INVALIDATE(s, "{ \"Not a\": \"string or number\" }", "", "anyOf", "");
229 230 231 232 233
}

TEST(SchemaValidator, OneOf) {
    Document sd;
    sd.Parse("{\"oneOf\": [{ \"type\": \"number\", \"multipleOf\": 5 }, { \"type\": \"number\", \"multipleOf\": 3 } ] }");
Milo Yip's avatar
Milo Yip committed
234
    SchemaDocument s(sd);
235 236 237

    VALIDATE(s, "10", true);
    VALIDATE(s, "9", true);
miloyip's avatar
miloyip committed
238 239
    INVALIDATE(s, "2", "", "oneOf", "");
    INVALIDATE(s, "15", "", "oneOf", "");
240 241 242 243 244
}

TEST(SchemaValidator, Not) {
    Document sd;
    sd.Parse("{\"not\":{ \"type\": \"string\"}}");
Milo Yip's avatar
Milo Yip committed
245
    SchemaDocument s(sd);
246 247

    VALIDATE(s, "42", true);
miloyip's avatar
miloyip committed
248 249
    VALIDATE(s, "{ \"key\": \"value\" }", true);
    INVALIDATE(s, "\"I am a string\"", "", "not", "");
250 251
}

miloyip's avatar
miloyip committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
TEST(SchemaValidator, Ref) {
    Document sd;
    sd.Parse(
        "{"
        "  \"$schema\": \"http://json-schema.org/draft-04/schema#\","
        ""
        "  \"definitions\": {"
        "    \"address\": {"
        "      \"type\": \"object\","
        "      \"properties\": {"
        "        \"street_address\": { \"type\": \"string\" },"
        "        \"city\":           { \"type\": \"string\" },"
        "        \"state\":          { \"type\": \"string\" }"
        "      },"
        "      \"required\": [\"street_address\", \"city\", \"state\"]"
        "    }"
        "  },"
        "  \"type\": \"object\","
        "  \"properties\": {"
        "    \"billing_address\": { \"$ref\": \"#/definitions/address\" },"
        "    \"shipping_address\": { \"$ref\": \"#/definitions/address\" }"
        "  }"
        "}");
    SchemaDocument s(sd);

    VALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"}, \"billing_address\": {\"street_address\": \"1st Street SE\", \"city\": \"Washington\", \"state\": \"DC\"} }", true);
}

TEST(SchemaValidator, Ref_AllOf) {
    Document sd;
    sd.Parse(
        "{"
        "  \"$schema\": \"http://json-schema.org/draft-04/schema#\","
        ""
        "  \"definitions\": {"
        "    \"address\": {"
        "      \"type\": \"object\","
        "      \"properties\": {"
        "        \"street_address\": { \"type\": \"string\" },"
        "        \"city\":           { \"type\": \"string\" },"
        "        \"state\":          { \"type\": \"string\" }"
        "      },"
        "      \"required\": [\"street_address\", \"city\", \"state\"]"
        "    }"
        "  },"
        "  \"type\": \"object\","
        "  \"properties\": {"
        "    \"billing_address\": { \"$ref\": \"#/definitions/address\" },"
        "    \"shipping_address\": {"
        "      \"allOf\": ["
        "        { \"$ref\": \"#/definitions/address\" },"
        "        { \"properties\":"
        "          { \"type\": { \"enum\": [ \"residential\", \"business\" ] } },"
        "          \"required\": [\"type\"]"
        "        }"
        "      ]"
        "    }"
        "  }"
        "}");
    SchemaDocument s(sd);

miloyip's avatar
miloyip committed
313
    INVALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"} }", "/properties/shipping_address", "allOf", "/shipping_address");
miloyip's avatar
miloyip committed
314 315 316
    VALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\", \"type\": \"business\"} }", true);
}

317 318 319
TEST(SchemaValidator, String) {
    Document sd;
    sd.Parse("{\"type\":\"string\"}");
Milo Yip's avatar
Milo Yip committed
320
    SchemaDocument s(sd);
321 322

    VALIDATE(s, "\"I'm a string\"", true);
miloyip's avatar
miloyip committed
323
    INVALIDATE(s, "42", "", "type", "");
324 325 326 327
    INVALIDATE(s, "2147483648", "", "type", ""); // 2^31 can only be fit in unsigned
    INVALIDATE(s, "-2147483649", "", "type", ""); // -2^31 - 1 can only be fit in int64_t
    INVALIDATE(s, "4294967296", "", "type", ""); // 2^32 can only be fit in int64_t
    INVALIDATE(s, "3.1415926", "", "type", "");
328 329 330 331 332
}

TEST(SchemaValidator, String_LengthRange) {
    Document sd;
    sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}");
Milo Yip's avatar
Milo Yip committed
333
    SchemaDocument s(sd);
334

miloyip's avatar
miloyip committed
335
    INVALIDATE(s, "\"A\"", "", "minLength", "");
336 337
    VALIDATE(s, "\"AB\"", true);
    VALIDATE(s, "\"ABC\"", true);
miloyip's avatar
miloyip committed
338
    INVALIDATE(s, "\"ABCD\"", "", "maxLength", "");
339 340
}

miloyip's avatar
miloyip committed
341
#if RAPIDJSON_SCHEMA_HAS_REGEX
miloyip's avatar
miloyip committed
342 343 344
TEST(SchemaValidator, String_Pattern) {
    Document sd;
    sd.Parse("{\"type\":\"string\",\"pattern\":\"^(\\\\([0-9]{3}\\\\))?[0-9]{3}-[0-9]{4}$\"}");
Milo Yip's avatar
Milo Yip committed
345
    SchemaDocument s(sd);
miloyip's avatar
miloyip committed
346 347 348

    VALIDATE(s, "\"555-1212\"", true);
    VALIDATE(s, "\"(888)555-1212\"", true);
miloyip's avatar
miloyip committed
349 350
    INVALIDATE(s, "\"(888)555-1212 ext. 532\"", "", "pattern", "");
    INVALIDATE(s, "\"(800)FLOWERS\"", "", "pattern", "");
miloyip's avatar
miloyip committed
351
}
352 353 354 355 356 357 358 359 360 361

TEST(SchemaValidator, String_Pattern_Invalid) {
    Document sd;
    sd.Parse("{\"type\":\"string\",\"pattern\":\"a{0}\"}"); // TODO: report regex is invalid somehow
    SchemaDocument s(sd);

    VALIDATE(s, "\"\"", true);
    VALIDATE(s, "\"a\"", true);
    VALIDATE(s, "\"aa\"", true);
}
miloyip's avatar
miloyip committed
362
#endif
miloyip's avatar
miloyip committed
363

364 365 366
TEST(SchemaValidator, Integer) {
    Document sd;
    sd.Parse("{\"type\":\"integer\"}");
Milo Yip's avatar
Milo Yip committed
367
    SchemaDocument s(sd);
368 369 370

    VALIDATE(s, "42", true);
    VALIDATE(s, "-1", true);
371 372 373 374
    VALIDATE(s, "2147483648", true); // 2^31 can only be fit in unsigned
    VALIDATE(s, "-2147483649", true); // -2^31 - 1 can only be fit in int64_t
    VALIDATE(s, "2147483648", true); // 2^31 can only be fit in unsigned
    VALIDATE(s, "4294967296", true); // 2^32 can only be fit in int64_t
miloyip's avatar
miloyip committed
375 376
    INVALIDATE(s, "3.1415926", "", "type", "");
    INVALIDATE(s, "\"42\"", "", "type", "");
377 378 379 380 381
}

TEST(SchemaValidator, Integer_Range) {
    Document sd;
    sd.Parse("{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"exclusiveMaximum\":true}");
Milo Yip's avatar
Milo Yip committed
382
    SchemaDocument s(sd);
383

miloyip's avatar
miloyip committed
384
    INVALIDATE(s, "-1", "", "minimum", "");
385 386 387
    VALIDATE(s, "0", true);
    VALIDATE(s, "10", true);
    VALIDATE(s, "99", true);
miloyip's avatar
miloyip committed
388 389
    INVALIDATE(s, "100", "", "maximum", "");
    INVALIDATE(s, "101", "", "maximum", "");
390 391
}

392 393
TEST(SchemaValidator, Integer_Range64Boundary) {
    Document sd;
394
    sd.Parse("{\"type\":\"integer\",\"minimum\":-9223372036854775807,\"maximum\":9223372036854775806}");
395 396 397 398
    SchemaDocument s(sd);

    INVALIDATE(s, "-9223372036854775808", "", "minimum", "");
    VALIDATE(s, "-9223372036854775807", true);
399 400 401 402
    VALIDATE(s, "-2147483648", true); // int min
    VALIDATE(s, "0", true);
    VALIDATE(s, "2147483647", true);  // int max
    VALIDATE(s, "2147483648", true);  // unsigned first
403
    VALIDATE(s, "4294967295", true);  // unsigned max
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    VALIDATE(s, "9223372036854775806", true);
    INVALIDATE(s, "9223372036854775807", "", "maximum", "");
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");   // uint64_t max
}

TEST(SchemaValidator, Integer_RangeU64Boundary) {
    Document sd;
    sd.Parse("{\"type\":\"integer\",\"minimum\":9223372036854775808,\"maximum\":18446744073709551614}");
    SchemaDocument s(sd);

    INVALIDATE(s, "-9223372036854775808", "", "minimum", "");
    INVALIDATE(s, "9223372036854775807", "", "minimum", "");
    INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min
    INVALIDATE(s, "0", "", "minimum", "");
    INVALIDATE(s, "2147483647", "", "minimum", "");  // int max
    INVALIDATE(s, "2147483648", "", "minimum", "");  // unsigned first
420
    INVALIDATE(s, "4294967295", "", "minimum", "");  // unsigned max
421
    VALIDATE(s, "9223372036854775808", true);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    VALIDATE(s, "18446744073709551614", true);
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");
}

TEST(SchemaValidator, Integer_Range64BoundaryExclusive) {
    Document sd;
    sd.Parse("{\"type\":\"integer\",\"minimum\":-9223372036854775808,\"maximum\":18446744073709551615,\"exclusiveMinimum\":true,\"exclusiveMaximum\":true}");
    SchemaDocument s(sd);

    INVALIDATE(s, "-9223372036854775808", "", "minimum", "");
    VALIDATE(s, "-9223372036854775807", true);
    VALIDATE(s, "18446744073709551614", true);
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");
}

437 438 439
TEST(SchemaValidator, Integer_MultipleOf) {
    Document sd;
    sd.Parse("{\"type\":\"integer\",\"multipleOf\":10}");
Milo Yip's avatar
Milo Yip committed
440
    SchemaDocument s(sd);
441

442 443
    VALIDATE(s, "0", true);
    VALIDATE(s, "10", true);
444
    VALIDATE(s, "-10", true);
445
    VALIDATE(s, "20", true);
miloyip's avatar
miloyip committed
446
    INVALIDATE(s, "23", "", "multipleOf", "");
447 448 449 450 451 452 453 454 455 456 457
    INVALIDATE(s, "-23", "", "multipleOf", "");
}

TEST(SchemaValidator, Integer_MultipleOf64Boundary) {
    Document sd;
    sd.Parse("{\"type\":\"integer\",\"multipleOf\":18446744073709551615}");
    SchemaDocument s(sd);

    VALIDATE(s, "0", true);
    VALIDATE(s, "18446744073709551615", true);
    INVALIDATE(s, "18446744073709551614", "", "multipleOf", "");
458 459 460 461 462
}

TEST(SchemaValidator, Number_Range) {
    Document sd;
    sd.Parse("{\"type\":\"number\",\"minimum\":0,\"maximum\":100,\"exclusiveMaximum\":true}");
Milo Yip's avatar
Milo Yip committed
463
    SchemaDocument s(sd);
464

miloyip's avatar
miloyip committed
465
    INVALIDATE(s, "-1", "", "minimum", "");
466
    VALIDATE(s, "0", true);
467
    VALIDATE(s, "0.1", true);
468 469
    VALIDATE(s, "10", true);
    VALIDATE(s, "99", true);
470
    VALIDATE(s, "99.9", true);
miloyip's avatar
miloyip committed
471
    INVALIDATE(s, "100", "", "maximum", "");
472 473 474 475
    INVALIDATE(s, "100.0", "", "maximum", "");
    INVALIDATE(s, "101.5", "", "maximum", "");
}

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
TEST(SchemaValidator, Number_RangeInt) {
    Document sd;
    sd.Parse("{\"type\":\"number\",\"minimum\":-100,\"maximum\":-1,\"exclusiveMaximum\":true}");
    SchemaDocument s(sd);

    INVALIDATE(s, "-101", "", "minimum", "");
    INVALIDATE(s, "-100.1", "", "minimum", "");
    VALIDATE(s, "-100", true);
    VALIDATE(s, "-2", true);
    INVALIDATE(s, "-1", "", "maximum", "");
    INVALIDATE(s, "-0.9", "", "maximum", "");
    INVALIDATE(s, "0", "", "maximum", "");
    INVALIDATE(s, "2147483647", "", "maximum", "");  // int max
    INVALIDATE(s, "2147483648", "", "maximum", "");  // unsigned first
    INVALIDATE(s, "4294967295", "", "maximum", "");  // unsigned max
    INVALIDATE(s, "9223372036854775808", "", "maximum", "");
    INVALIDATE(s, "18446744073709551614", "", "maximum", "");
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");
}

496 497 498 499 500 501 502 503 504 505 506 507
TEST(SchemaValidator, Number_RangeDouble) {
    Document sd;
    sd.Parse("{\"type\":\"number\",\"minimum\":0.1,\"maximum\":100.1,\"exclusiveMaximum\":true}");
    SchemaDocument s(sd);

    INVALIDATE(s, "-9223372036854775808", "", "minimum", "");
    INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min
    INVALIDATE(s, "-1", "", "minimum", "");
    VALIDATE(s, "0.1", true);
    VALIDATE(s, "10", true);
    VALIDATE(s, "99", true);
    VALIDATE(s, "100", true);
miloyip's avatar
miloyip committed
508
    INVALIDATE(s, "101", "", "maximum", "");
509 510 511 512 513
    INVALIDATE(s, "101.5", "", "maximum", "");
    INVALIDATE(s, "18446744073709551614", "", "maximum", "");
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");
    INVALIDATE(s, "2147483647", "", "maximum", "");  // int max
    INVALIDATE(s, "2147483648", "", "maximum", "");  // unsigned first
514
    INVALIDATE(s, "4294967295", "", "maximum", "");  // unsigned max
515 516 517
    INVALIDATE(s, "9223372036854775808", "", "maximum", "");
    INVALIDATE(s, "18446744073709551614", "", "maximum", "");
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");
518 519
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
TEST(SchemaValidator, Number_RangeDoubleU64Boundary) {
    Document sd;
    sd.Parse("{\"type\":\"number\",\"minimum\":9223372036854775808.0,\"maximum\":18446744073709550000.0}");
    SchemaDocument s(sd);

    INVALIDATE(s, "-9223372036854775808", "", "minimum", "");
    INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min
    INVALIDATE(s, "0", "", "minimum", "");
    INVALIDATE(s, "2147483647", "", "minimum", "");  // int max
    INVALIDATE(s, "2147483648", "", "minimum", "");  // unsigned first
    INVALIDATE(s, "4294967295", "", "minimum", "");  // unsigned max
    VALIDATE(s, "9223372036854775808", true);
    VALIDATE(s, "18446744073709540000", true);
    INVALIDATE(s, "18446744073709551615", "", "maximum", "");
}

536 537
TEST(SchemaValidator, Number_MultipleOf) {
    Document sd;
538
    sd.Parse("{\"type\":\"number\",\"multipleOf\":10.0}");
Milo Yip's avatar
Milo Yip committed
539
    SchemaDocument s(sd);
540 541 542

    VALIDATE(s, "0", true);
    VALIDATE(s, "10", true);
543
    VALIDATE(s, "-10", true);
544
    VALIDATE(s, "20", true);
miloyip's avatar
miloyip committed
545
    INVALIDATE(s, "23", "", "multipleOf", "");
546 547 548 549 550 551 552
    INVALIDATE(s, "-2147483648", "", "multipleOf", "");  // int min
    VALIDATE(s, "-2147483640", true);
    INVALIDATE(s, "2147483647", "", "multipleOf", "");  // int max
    INVALIDATE(s, "2147483648", "", "multipleOf", "");  // unsigned first
    VALIDATE(s, "2147483650", true);
    INVALIDATE(s, "4294967295", "", "multipleOf", "");  // unsigned max
    VALIDATE(s, "4294967300", true);
553 554 555 556 557
}

TEST(SchemaValidator, Number_MultipleOfOne) {
    Document sd;
    sd.Parse("{\"type\":\"number\",\"multipleOf\":1}");
Milo Yip's avatar
Milo Yip committed
558
    SchemaDocument s(sd);
559 560 561

    VALIDATE(s, "42", true);
    VALIDATE(s, "42.0", true);
miloyip's avatar
miloyip committed
562
    INVALIDATE(s, "3.1415926", "", "multipleOf", "");
563 564 565 566 567
}

TEST(SchemaValidator, Object) {
    Document sd;
    sd.Parse("{\"type\":\"object\"}");
Milo Yip's avatar
Milo Yip committed
568
    SchemaDocument s(sd);
569 570 571

    VALIDATE(s, "{\"key\":\"value\",\"another_key\":\"another_value\"}", true);
    VALIDATE(s, "{\"Sun\":1.9891e30,\"Jupiter\":1.8986e27,\"Saturn\":5.6846e26,\"Neptune\":10.243e25,\"Uranus\":8.6810e25,\"Earth\":5.9736e24,\"Venus\":4.8685e24,\"Mars\":6.4185e23,\"Mercury\":3.3022e23,\"Moon\":7.349e22,\"Pluto\":1.25e22}", true);    
miloyip's avatar
miloyip committed
572 573
    INVALIDATE(s, "[\"An\", \"array\", \"not\", \"an\", \"object\"]", "", "type", "");
    INVALIDATE(s, "\"Not an object\"", "", "type", "");
574 575 576 577 578 579 580 581 582 583 584 585 586 587
}

TEST(SchemaValidator, Object_Properties) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": \"object\","
        "    \"properties\" : {"
        "        \"number\": { \"type\": \"number\" },"
        "        \"street_name\" : { \"type\": \"string\" },"
        "        \"street_type\" : { \"type\": \"string\", \"enum\" : [\"Street\", \"Avenue\", \"Boulevard\"] }"
        "    }"
        "}");

Milo Yip's avatar
Milo Yip committed
588
    SchemaDocument s(sd);
589 590

    VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true);
miloyip's avatar
miloyip committed
591
    INVALIDATE(s, "{ \"number\": \"1600\", \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", "/properties/number", "type", "/number");
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\" }", true);
    VALIDATE(s, "{}", true);
    VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", true);
}

TEST(SchemaValidator, Object_AdditionalPropertiesBoolean) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": \"object\","
        "        \"properties\" : {"
        "        \"number\": { \"type\": \"number\" },"
        "            \"street_name\" : { \"type\": \"string\" },"
        "            \"street_type\" : { \"type\": \"string\","
        "            \"enum\" : [\"Street\", \"Avenue\", \"Boulevard\"]"
        "        }"
        "    },"
        "    \"additionalProperties\": false"
        "}");

Milo Yip's avatar
Milo Yip committed
612
    SchemaDocument s(sd);
613 614

    VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true);
miloyip's avatar
miloyip committed
615
    INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", "", "additionalProperties", "/direction");
616 617 618 619 620 621 622
}

TEST(SchemaValidator, Object_AdditionalPropertiesObject) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": \"object\","
miloyip's avatar
miloyip committed
623
        "    \"properties\" : {"
624
        "        \"number\": { \"type\": \"number\" },"
miloyip's avatar
miloyip committed
625 626
        "        \"street_name\" : { \"type\": \"string\" },"
        "        \"street_type\" : { \"type\": \"string\","
627 628 629 630 631
        "            \"enum\" : [\"Street\", \"Avenue\", \"Boulevard\"]"
        "        }"
        "    },"
        "    \"additionalProperties\": { \"type\": \"string\" }"
        "}");
Milo Yip's avatar
Milo Yip committed
632
    SchemaDocument s(sd);
633 634 635

    VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true);
    VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", true);
miloyip's avatar
miloyip committed
636
    INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"office_number\": 201 }", "/additionalProperties", "type", "/office_number");
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
}

TEST(SchemaValidator, Object_Required) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": \"object\","
        "    \"properties\" : {"
        "        \"name\":      { \"type\": \"string\" },"
        "        \"email\" : { \"type\": \"string\" },"
        "        \"address\" : { \"type\": \"string\" },"
        "        \"telephone\" : { \"type\": \"string\" }"
        "    },"
        "    \"required\":[\"name\", \"email\"]"
        "}");
Milo Yip's avatar
Milo Yip committed
652
    SchemaDocument s(sd);
653 654 655

    VALIDATE(s, "{ \"name\": \"William Shakespeare\", \"email\" : \"bill@stratford-upon-avon.co.uk\" }", true);
    VALIDATE(s, "{ \"name\": \"William Shakespeare\", \"email\" : \"bill@stratford-upon-avon.co.uk\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\", \"authorship\" : \"in question\"}", true);
miloyip's avatar
miloyip committed
656
    INVALIDATE(s, "{ \"name\": \"William Shakespeare\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\" }", "", "required", "");
657 658 659 660 661 662
}


TEST(SchemaValidator, Object_PropertiesRange) {
    Document sd;
    sd.Parse("{\"type\":\"object\", \"minProperties\":2, \"maxProperties\":3}");
Milo Yip's avatar
Milo Yip committed
663
    SchemaDocument s(sd);
664

miloyip's avatar
miloyip committed
665 666
    INVALIDATE(s, "{}", "", "minProperties", "");
    INVALIDATE(s, "{\"a\":0}", "", "minProperties", "");
667 668
    VALIDATE(s, "{\"a\":0,\"b\":1}", true);
    VALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2}", true);
miloyip's avatar
miloyip committed
669
    INVALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2,\"d\":3}", "", "maxProperties", "");
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
}

TEST(SchemaValidator, Object_PropertyDependencies) {
    Document sd;
    sd.Parse(
        "{"
        "  \"type\": \"object\","
        "  \"properties\": {"
        "    \"name\": { \"type\": \"string\" },"
        "    \"credit_card\": { \"type\": \"number\" },"
        "    \"billing_address\": { \"type\": \"string\" }"
        "  },"
        "  \"required\": [\"name\"],"
        "  \"dependencies\": {"
        "    \"credit_card\": [\"billing_address\"]"
        "  }"
        "}");
Milo Yip's avatar
Milo Yip committed
687
    SchemaDocument s(sd);
688

miloyip's avatar
miloyip committed
689 690
    VALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555, \"billing_address\": \"555 Debtor's Lane\" }", true);
    INVALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555 }", "", "dependencies", "");
691 692 693 694
    VALIDATE(s, "{ \"name\": \"John Doe\"}", true);
    VALIDATE(s, "{ \"name\": \"John Doe\", \"billing_address\": \"555 Debtor's Lane\" }", true);
}

695 696 697 698 699 700
TEST(SchemaValidator, Object_SchemaDependencies) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": \"object\","
        "    \"properties\" : {"
miloyip's avatar
miloyip committed
701
        "        \"name\": { \"type\": \"string\" },"
702 703 704
        "        \"credit_card\" : { \"type\": \"number\" }"
        "    },"
        "    \"required\" : [\"name\"],"
miloyip's avatar
miloyip committed
705
        "    \"dependencies\" : {"
706 707 708 709 710 711 712 713
        "        \"credit_card\": {"
        "            \"properties\": {"
        "                \"billing_address\": { \"type\": \"string\" }"
        "            },"
        "            \"required\" : [\"billing_address\"]"
        "        }"
        "    }"
        "}");
Milo Yip's avatar
Milo Yip committed
714
    SchemaDocument s(sd);
715

miloyip's avatar
miloyip committed
716 717
    VALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555,\"billing_address\" : \"555 Debtor's Lane\"}", true);
    INVALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555 }", "", "dependencies", "");
718 719 720
    VALIDATE(s, "{\"name\": \"John Doe\", \"billing_address\" : \"555 Debtor's Lane\"}", true);
}

721
#if RAPIDJSON_SCHEMA_HAS_REGEX
722 723 724 725 726 727 728 729 730 731
TEST(SchemaValidator, Object_PatternProperties) {
    Document sd;
    sd.Parse(
        "{"
        "  \"type\": \"object\","
        "  \"patternProperties\": {"
        "    \"^S_\": { \"type\": \"string\" },"
        "    \"^I_\": { \"type\": \"integer\" }"
        "  }"
        "}");
Milo Yip's avatar
Milo Yip committed
732
    SchemaDocument s(sd);
733 734 735

    VALIDATE(s, "{ \"S_25\": \"This is a string\" }", true);
    VALIDATE(s, "{ \"I_0\": 42 }", true);
miloyip's avatar
miloyip committed
736 737
    INVALIDATE(s, "{ \"S_0\": 42 }", "", "patternProperties", "/S_0");
    INVALIDATE(s, "{ \"I_42\": \"This is a string\" }", "", "patternProperties", "/I_42");
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    VALIDATE(s, "{ \"keyword\": \"value\" }", true);
}

TEST(SchemaValidator, Object_PatternProperties_AdditionalProperties) {
    Document sd;
    sd.Parse(
        "{"
        "  \"type\": \"object\","
        "  \"properties\": {"
        "    \"builtin\": { \"type\": \"number\" }"
        "  },"
        "  \"patternProperties\": {"
        "    \"^S_\": { \"type\": \"string\" },"
        "    \"^I_\": { \"type\": \"integer\" }"
        "  },"
        "  \"additionalProperties\": { \"type\": \"string\" }"
        "}");
Milo Yip's avatar
Milo Yip committed
755
    SchemaDocument s(sd);
756 757 758

    VALIDATE(s, "{ \"builtin\": 42 }", true);
    VALIDATE(s, "{ \"keyword\": \"value\" }", true);
miloyip's avatar
miloyip committed
759
    INVALIDATE(s, "{ \"keyword\": 42 }", "/additionalProperties", "type", "/keyword");
760
}
761
#endif
762

763 764 765
TEST(SchemaValidator, Array) {
    Document sd;
    sd.Parse("{\"type\":\"array\"}");
Milo Yip's avatar
Milo Yip committed
766
    SchemaDocument s(sd);
767 768 769

    VALIDATE(s, "[1, 2, 3, 4, 5]", true);
    VALIDATE(s, "[3, \"different\", { \"types\" : \"of values\" }]", true);
miloyip's avatar
miloyip committed
770
    INVALIDATE(s, "{\"Not\": \"an array\"}", "", "type", "");
771 772 773 774 775 776 777 778 779 780 781
}

TEST(SchemaValidator, Array_ItemsList) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": \"array\","
        "    \"items\" : {"
        "        \"type\": \"number\""
        "    }"
        "}");
Milo Yip's avatar
Milo Yip committed
782
    SchemaDocument s(sd);
783 784

    VALIDATE(s, "[1, 2, 3, 4, 5]", true);
Milo Yip's avatar
Milo Yip committed
785
    INVALIDATE(s, "[1, 2, \"3\", 4, 5]", "/items", "type", "/2");
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    VALIDATE(s, "[]", true);
}

TEST(SchemaValidator, Array_ItemsTuple) {
    Document sd;
    sd.Parse(
        "{"
        "  \"type\": \"array\","
        "  \"items\": ["
        "    {"
        "      \"type\": \"number\""
        "    },"
        "    {"
        "      \"type\": \"string\""
        "    },"
        "    {"
        "      \"type\": \"string\","
        "      \"enum\": [\"Street\", \"Avenue\", \"Boulevard\"]"
        "    },"
        "    {"
        "      \"type\": \"string\","
        "      \"enum\": [\"NW\", \"NE\", \"SW\", \"SE\"]"
        "    }"
        "  ]"
        "}");
Milo Yip's avatar
Milo Yip committed
811
    SchemaDocument s(sd);
812 813

    VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\"]", true);
miloyip's avatar
miloyip committed
814 815
    INVALIDATE(s, "[24, \"Sussex\", \"Drive\"]", "/items/2", "enum", "/2");
    INVALIDATE(s, "[\"Palais de l'Elysee\"]", "/items/0", "type", "/0");
816 817 818 819
    VALIDATE(s, "[10, \"Downing\", \"Street\"]", true);
    VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", true);
}

Milo Yip's avatar
Milo Yip committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
TEST(SchemaValidator, Array_AdditionalItmes) {
    Document sd;
    sd.Parse(
        "{"
        "  \"type\": \"array\","
        "  \"items\": ["
        "    {"
        "      \"type\": \"number\""
        "    },"
        "    {"
        "      \"type\": \"string\""
        "    },"
        "    {"
        "      \"type\": \"string\","
        "      \"enum\": [\"Street\", \"Avenue\", \"Boulevard\"]"
        "    },"
        "    {"
        "      \"type\": \"string\","
        "      \"enum\": [\"NW\", \"NE\", \"SW\", \"SE\"]"
        "    }"
        "  ],"
        "  \"additionalItems\": false"
        "}");
Milo Yip's avatar
Milo Yip committed
843
    SchemaDocument s(sd);
Milo Yip's avatar
Milo Yip committed
844 845 846

    VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\"]", true);
    VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\"]", true);
miloyip's avatar
miloyip committed
847
    INVALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", "", "items", "/4");
Milo Yip's avatar
Milo Yip committed
848 849
}

850 851 852
TEST(SchemaValidator, Array_ItemsRange) {
    Document sd;
    sd.Parse("{\"type\": \"array\",\"minItems\": 2,\"maxItems\" : 3}");
Milo Yip's avatar
Milo Yip committed
853
    SchemaDocument s(sd);
854

miloyip's avatar
miloyip committed
855 856
    INVALIDATE(s, "[]", "", "minItems", "");
    INVALIDATE(s, "[1]", "", "minItems", "");
857 858
    VALIDATE(s, "[1, 2]", true);
    VALIDATE(s, "[1, 2, 3]", true);
miloyip's avatar
miloyip committed
859
    INVALIDATE(s, "[1, 2, 3, 4]", "", "maxItems", "");
860 861
}

miloyip's avatar
miloyip committed
862
TEST(SchemaValidator, Array_UniqueItems) {
863 864
    Document sd;
    sd.Parse("{\"type\": \"array\", \"uniqueItems\": true}");
Milo Yip's avatar
Milo Yip committed
865
    SchemaDocument s(sd);
866 867

    VALIDATE(s, "[1, 2, 3, 4, 5]", true);
miloyip's avatar
miloyip committed
868
    INVALIDATE(s, "[1, 2, 3, 3, 4]", "", "uniqueItems", "/3");
miloyip's avatar
miloyip committed
869
    VALIDATE(s, "[]", true);
870 871 872 873 874
}

TEST(SchemaValidator, Boolean) {
    Document sd;
    sd.Parse("{\"type\":\"boolean\"}");
Milo Yip's avatar
Milo Yip committed
875
    SchemaDocument s(sd);
876 877 878

    VALIDATE(s, "true", true);
    VALIDATE(s, "false", true);
miloyip's avatar
miloyip committed
879 880
    INVALIDATE(s, "\"true\"", "", "type", "");
    INVALIDATE(s, "0", "", "type", "");
881 882 883 884 885
}

TEST(SchemaValidator, Null) {
    Document sd;
    sd.Parse("{\"type\":\"null\"}");
Milo Yip's avatar
Milo Yip committed
886
    SchemaDocument s(sd);
887 888

    VALIDATE(s, "null", true);
miloyip's avatar
miloyip committed
889 890 891
    INVALIDATE(s, "false", "", "type", "");
    INVALIDATE(s, "0", "", "type", "");
    INVALIDATE(s, "\"\"", "", "type", "");
892
}
Milo Yip's avatar
Milo Yip committed
893

miloyip's avatar
miloyip committed
894 895
// Additional tests

Milo Yip's avatar
Milo Yip committed
896 897 898
TEST(SchemaValidator, ObjectInArray) {
    Document sd;
    sd.Parse("{\"type\":\"array\", \"items\": { \"type\":\"string\" }}");
Milo Yip's avatar
Milo Yip committed
899
    SchemaDocument s(sd);
Milo Yip's avatar
Milo Yip committed
900

901
    VALIDATE(s, "[\"a\"]", true);
Milo Yip's avatar
Milo Yip committed
902 903
    INVALIDATE(s, "[1]", "/items", "type", "/0");
    INVALIDATE(s, "[{}]", "/items", "type", "/0");
miloyip's avatar
miloyip committed
904 905 906 907 908 909 910 911 912 913 914 915 916
}

TEST(SchemaValidator, MultiTypeInObject) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\":\"object\","
        "    \"properties\": {"
        "        \"tel\" : {"
        "            \"type\":[\"integer\", \"string\"]"
        "        }"
        "    }"
        "}");
Milo Yip's avatar
Milo Yip committed
917
    SchemaDocument s(sd);
miloyip's avatar
miloyip committed
918 919 920

    VALIDATE(s, "{ \"tel\": 999 }", true);
    VALIDATE(s, "{ \"tel\": \"123-456\" }", true);
miloyip's avatar
miloyip committed
921
    INVALIDATE(s, "{ \"tel\": true }", "/properties/tel", "type", "/tel");
miloyip's avatar
miloyip committed
922 923 924 925 926 927 928 929 930 931 932 933 934
}

TEST(SchemaValidator, MultiTypeWithObject) {
    Document sd;
    sd.Parse(
        "{"
        "    \"type\": [\"object\",\"string\"],"
        "    \"properties\": {"
        "        \"tel\" : {"
        "            \"type\": \"integer\""
        "        }"
        "    }"
        "}");
Milo Yip's avatar
Milo Yip committed
935
    SchemaDocument s(sd);
miloyip's avatar
miloyip committed
936 937 938

    VALIDATE(s, "\"Hello\"", true);
    VALIDATE(s, "{ \"tel\": 999 }", true);
miloyip's avatar
miloyip committed
939
    INVALIDATE(s, "{ \"tel\": \"fail\" }", "/properties/tel", "type", "/tel");
miloyip's avatar
miloyip committed
940 941
}

Milo Yip's avatar
Milo Yip committed
942 943 944 945 946 947 948 949 950 951
TEST(SchemaValidator, AllOf_Nested) {
    Document sd;
    sd.Parse(
    "{"
    "    \"allOf\": ["
    "        { \"type\": \"string\", \"minLength\": 2 },"
    "        { \"type\": \"string\", \"maxLength\": 5 },"
    "        { \"allOf\": [ { \"enum\" : [\"ok\", \"okay\", \"OK\", \"o\"] }, { \"enum\" : [\"ok\", \"OK\", \"o\"]} ] }"
    "    ]"
    "}");
Milo Yip's avatar
Milo Yip committed
952
    SchemaDocument s(sd);
Milo Yip's avatar
Milo Yip committed
953 954 955

    VALIDATE(s, "\"ok\"", true);
    VALIDATE(s, "\"OK\"", true);
miloyip's avatar
miloyip committed
956 957 958 959 960
    INVALIDATE(s, "\"okay\"", "", "allOf", "");
    INVALIDATE(s, "\"o\"", "", "allOf", "");
    INVALIDATE(s, "\"n\"", "", "allOf", "");
    INVALIDATE(s, "\"too long\"", "", "allOf", "");
    INVALIDATE(s, "123", "", "allOf", "");
Milo Yip's avatar
Milo Yip committed
961
}
miloyip's avatar
miloyip committed
962

963 964 965 966 967 968 969 970 971 972 973 974 975
TEST(SchemaValidator, EscapedPointer) {
    Document sd;
    sd.Parse(
        "{"
        "  \"type\": \"object\","
        "  \"properties\": {"
        "    \"~/\": { \"type\": \"number\" }"
        "  }"
        "}");
    SchemaDocument s(sd);
    INVALIDATE(s, "{\"~/\":true}", "/properties/~0~1", "type", "/~0~1");
}

976
template <typename Allocator>
977
static char* ReadFile(const char* filename, Allocator& allocator) {
miloyip's avatar
miloyip committed
978
    const char *paths[] = {
979 980 981 982 983
        "",
        "bin/",
        "../bin/",
        "../../bin/",
        "../../../bin/"
miloyip's avatar
miloyip committed
984 985 986 987
    };
    char buffer[1024];
    FILE *fp = 0;
    for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) {
988
        sprintf(buffer, "%s%s", paths[i], filename);
miloyip's avatar
miloyip committed
989 990 991 992 993 994 995 996 997
        fp = fopen(buffer, "rb");
        if (fp)
            break;
    }

    if (!fp)
        return 0;

    fseek(fp, 0, SEEK_END);
998
    size_t length = static_cast<size_t>(ftell(fp));
miloyip's avatar
miloyip committed
999
    fseek(fp, 0, SEEK_SET);
1000
    char* json = reinterpret_cast<char*>(allocator.Malloc(length + 1));
miloyip's avatar
miloyip committed
1001 1002 1003 1004 1005 1006
    size_t readLength = fread(json, 1, length, fp);
    json[readLength] = '\0';
    fclose(fp);
    return json;
}

1007
TEST(SchemaValidator, ValidateMetaSchema) {
1008 1009
    CrtAllocator allocator;
    char* json = ReadFile("draft-04/schema", allocator);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    Document d;
    d.Parse(json);
    ASSERT_FALSE(d.HasParseError());
    SchemaDocument sd(d);
    SchemaValidator validator(sd);
    if (!d.Accept(validator)) {
        StringBuffer sb;
        validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
        printf("Invalid schema: %s\n", sb.GetString());
        printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());
        sb.Clear();
        validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
        printf("Invalid document: %s\n", sb.GetString());
1023 1024
        ADD_FAILURE();
    }
1025
    CrtAllocator::Free(json);
1026 1027 1028 1029 1030 1031 1032
}

TEST(SchemaValidator, ValidateMetaSchema_UTF16) {
    typedef GenericDocument<UTF16<> > D;
    typedef GenericSchemaDocument<D::ValueType> SD;
    typedef GenericSchemaValidator<SD> SV;

1033 1034
    CrtAllocator allocator;
    char* json = ReadFile("draft-04/schema", allocator);
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

    D d;
    StringStream ss(json);
    d.ParseStream<0, UTF8<> >(ss);
    ASSERT_FALSE(d.HasParseError());
    SD sd(d);
    SV validator(sd);
    if (!d.Accept(validator)) {
        GenericStringBuffer<UTF16<> > sb;
        validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
        wprintf(L"Invalid schema: %ls\n", sb.GetString());
        wprintf(L"Invalid keyword: %ls\n", validator.GetInvalidSchemaKeyword());
        sb.Clear();
        validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
        wprintf(L"Invalid document: %ls\n", sb.GetString());
        ADD_FAILURE();
1051
    }
1052
    CrtAllocator::Free(json);
1053 1054
}

1055 1056
template <typename SchemaDocumentType = SchemaDocument>
class RemoteSchemaDocumentProvider : public IGenericRemoteSchemaDocumentProvider<SchemaDocumentType> {
miloyip's avatar
miloyip committed
1057
public:
1058 1059 1060 1061
    RemoteSchemaDocumentProvider() : 
        documentAllocator_(documentBuffer_, sizeof(documentBuffer_)), 
        schemaAllocator_(schemaBuffer_, sizeof(schemaBuffer_)) 
    {
miloyip's avatar
miloyip committed
1062
        const char* filenames[kCount] = {
miloyip's avatar
miloyip committed
1063 1064 1065 1066
            "jsonschema/remotes/integer.json",
            "jsonschema/remotes/subSchemas.json",
            "jsonschema/remotes/folder/folderInteger.json",
            "draft-04/schema"
miloyip's avatar
miloyip committed
1067 1068 1069 1070 1071
        };

        for (size_t i = 0; i < kCount; i++) {
            sd_[i] = 0;

1072 1073 1074
            char jsonBuffer[8192];
            MemoryPoolAllocator<> jsonAllocator(jsonBuffer, sizeof(jsonBuffer));
            char* json = ReadFile(filenames[i], jsonAllocator);
miloyip's avatar
miloyip committed
1075
            if (!json) {
miloyip's avatar
miloyip committed
1076
                printf("json remote file %s not found", filenames[i]);
miloyip's avatar
miloyip committed
1077 1078 1079
                ADD_FAILURE();
            }
            else {
1080 1081 1082
                char stackBuffer[4096];
                MemoryPoolAllocator<> stackAllocator(stackBuffer, sizeof(stackBuffer));
                DocumentType d(&documentAllocator_, 1024, &stackAllocator);
1083
                d.Parse(json);
1084
                sd_[i] = new SchemaDocumentType(d, 0, &schemaAllocator_);
1085
                MemoryPoolAllocator<>::Free(json);
miloyip's avatar
miloyip committed
1086 1087 1088 1089 1090
            }
        };
    }

    ~RemoteSchemaDocumentProvider() {
1091
        for (size_t i = 0; i < kCount; i++)
miloyip's avatar
miloyip committed
1092 1093 1094
            delete sd_[i];
    }

1095
    virtual const SchemaDocumentType* GetRemoteDocument(const char* uri, SizeType length) {
miloyip's avatar
miloyip committed
1096 1097 1098
        const char* uris[kCount] = {
            "http://localhost:1234/integer.json",
            "http://localhost:1234/subSchemas.json",
miloyip's avatar
miloyip committed
1099 1100
            "http://localhost:1234/folder/folderInteger.json",
            "http://json-schema.org/draft-04/schema"
miloyip's avatar
miloyip committed
1101 1102
        };

miloyip's avatar
miloyip committed
1103
        for (size_t i = 0; i < kCount; i++)
miloyip's avatar
miloyip committed
1104 1105 1106 1107 1108 1109
            if (strncmp(uri, uris[i], length) == 0)
                return sd_[i];
        return 0;
    }

private:
1110
    typedef GenericDocument<typename SchemaDocumentType::EncodingType, MemoryPoolAllocator<>, MemoryPoolAllocator<> > DocumentType;
1111

miloyip's avatar
miloyip committed
1112
    RemoteSchemaDocumentProvider(const RemoteSchemaDocumentProvider&);
miloyip's avatar
miloyip committed
1113
    RemoteSchemaDocumentProvider& operator=(const RemoteSchemaDocumentProvider&);
miloyip's avatar
miloyip committed
1114

miloyip's avatar
miloyip committed
1115
    static const size_t kCount = 4;
1116 1117 1118
    SchemaDocumentType* sd_[kCount];
    typename DocumentType::AllocatorType documentAllocator_;
    typename SchemaDocumentType::AllocatorType schemaAllocator_;
1119 1120
    char documentBuffer_[16384];
    char schemaBuffer_[128 * 1024];
miloyip's avatar
miloyip committed
1121
};
miloyip's avatar
miloyip committed
1122 1123 1124 1125 1126 1127 1128

TEST(SchemaValidator, TestSuite) {
    const char* filenames[] = {
        "additionalItems.json",
        "additionalProperties.json",
        "allOf.json",
        "anyOf.json",
1129
        "default.json",
miloyip's avatar
miloyip committed
1130
        "definitions.json",
1131
        "dependencies.json",
miloyip's avatar
miloyip committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        "enum.json",
        "items.json",
        "maximum.json",
        "maxItems.json",
        "maxLength.json",
        "maxProperties.json",
        "minimum.json",
        "minItems.json",
        "minLength.json",
        "minProperties.json",
        "multipleOf.json",
        "not.json",
        "oneOf.json",
        "pattern.json",
        "patternProperties.json",
        "properties.json",
miloyip's avatar
miloyip committed
1148
        "ref.json",
miloyip's avatar
miloyip committed
1149
        "refRemote.json",
miloyip's avatar
miloyip committed
1150 1151
        "required.json",
        "type.json",
miloyip's avatar
miloyip committed
1152
        "uniqueItems.json"
miloyip's avatar
miloyip committed
1153 1154
    };

1155 1156 1157
    const char* onlyRunDescription = 0;
    //const char* onlyRunDescription = "a string is a string";

miloyip's avatar
miloyip committed
1158 1159 1160
    unsigned testCount = 0;
    unsigned passCount = 0;

1161 1162
    typedef GenericSchemaDocument<Value, MemoryPoolAllocator<> > SchemaDocumentType;
    RemoteSchemaDocumentProvider<SchemaDocumentType> provider;
miloyip's avatar
miloyip committed
1163

1164
    char jsonBuffer[65536];
1165
    char documentBuffer[65536];
1166
    char documentStackBuffer[65536];
1167
    char schemaBuffer[65536];
1168
    char validatorBuffer[65536];
1169
    MemoryPoolAllocator<> jsonAllocator(jsonBuffer, sizeof(jsonBuffer));
1170 1171 1172 1173
    MemoryPoolAllocator<> documentAllocator(documentBuffer, sizeof(documentBuffer));
    MemoryPoolAllocator<> documentStackAllocator(documentStackBuffer, sizeof(documentStackBuffer));
    MemoryPoolAllocator<> schemaAllocator(schemaBuffer, sizeof(schemaBuffer));
    MemoryPoolAllocator<> validatorAllocator(validatorBuffer, sizeof(validatorBuffer));
1174

miloyip's avatar
miloyip committed
1175
    for (size_t i = 0; i < sizeof(filenames) / sizeof(filenames[0]); i++) {
miloyip's avatar
miloyip committed
1176 1177
        char filename[FILENAME_MAX];
        sprintf(filename, "jsonschema/tests/draft4/%s", filenames[i]);
1178
        char* json = ReadFile(filename, jsonAllocator);
miloyip's avatar
miloyip committed
1179 1180 1181 1182 1183
        if (!json) {
            printf("json test suite file %s not found", filename);
            ADD_FAILURE();
        }
        else {
1184
            GenericDocument<UTF8<>, MemoryPoolAllocator<>, MemoryPoolAllocator<> > d(&documentAllocator, 1024, &documentStackAllocator);
miloyip's avatar
miloyip committed
1185 1186 1187 1188 1189 1190 1191
            d.Parse(json);
            if (d.HasParseError()) {
                printf("json test suite file %s has parse error", filename);
                ADD_FAILURE();
            }
            else {
                for (Value::ConstValueIterator schemaItr = d.Begin(); schemaItr != d.End(); ++schemaItr) {
1192
                    {
1193 1194
                        SchemaDocumentType schema((*schemaItr)["schema"], &provider, &schemaAllocator);
                        GenericSchemaValidator<SchemaDocumentType, BaseReaderHandler<UTF8<> >, MemoryPoolAllocator<> > validator(schema, &validatorAllocator);
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
                        const char* description1 = (*schemaItr)["description"].GetString();
                        const Value& tests = (*schemaItr)["tests"];
                        for (Value::ConstValueIterator testItr = tests.Begin(); testItr != tests.End(); ++testItr) {
                            const char* description2 = (*testItr)["description"].GetString();
                            if (!onlyRunDescription || strcmp(description2, onlyRunDescription) == 0) {
                                const Value& data = (*testItr)["data"];
                                bool expected = (*testItr)["valid"].GetBool();
                                testCount++;
                                validator.Reset();
                                bool actual = data.Accept(validator);
                                if (expected != actual)
                                    printf("Fail: %30s \"%s\" \"%s\"\n", filename, description1, description2);
                                else
                                    passCount++;
                            }
miloyip's avatar
miloyip committed
1210
                        }
1211
                        //printf("%zu %zu %zu\n", documentAllocator.Size(), schemaAllocator.Size(), validatorAllocator.Size());
miloyip's avatar
miloyip committed
1212
                    }
1213
                    schemaAllocator.Clear();
1214
                    validatorAllocator.Clear();
miloyip's avatar
miloyip committed
1215 1216 1217
                }
            }
        }
1218
        documentAllocator.Clear();
1219 1220
        MemoryPoolAllocator<>::Free(json);
        jsonAllocator.Clear();
miloyip's avatar
miloyip committed
1221 1222
    }
    printf("%d / %d passed (%2d%%)\n", passCount, testCount, passCount * 100 / testCount);
1223 1224
    // if (passCount != testCount)
    //     ADD_FAILURE();
1225 1226
}

1227
TEST(SchemaValidatingReader, Simple) {
1228 1229 1230 1231 1232 1233 1234 1235 1236
    Document sd;
    sd.Parse("{ \"type\": \"string\", \"enum\" : [\"red\", \"amber\", \"green\"] }");
    SchemaDocument s(sd);

    Document d;
    StringStream ss("\"red\"");
    SchemaValidatingReader<kParseDefaultFlags, StringStream, UTF8<> > reader(ss, s);
    d.Populate(reader);
    EXPECT_TRUE(reader.GetParseResult());
1237
    EXPECT_TRUE(reader.IsValid());
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
    EXPECT_TRUE(d.IsString());
    EXPECT_STREQ("red", d.GetString());
}

TEST(SchemaValidatingReader, Invalid) {
    Document sd;
    sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}");
    SchemaDocument s(sd);

    Document d;
    StringStream ss("\"ABCD\"");
    SchemaValidatingReader<kParseDefaultFlags, StringStream, UTF8<> > reader(ss, s);
    d.Populate(reader);
    EXPECT_FALSE(reader.GetParseResult());
1252
    EXPECT_FALSE(reader.IsValid());
1253 1254 1255 1256 1257 1258 1259
    EXPECT_EQ(kParseErrorTermination, reader.GetParseResult().Code());
    EXPECT_STREQ("maxLength", reader.GetInvalidSchemaKeyword());
    EXPECT_TRUE(reader.GetInvalidSchemaPointer() == SchemaDocument::PointerType(""));
    EXPECT_TRUE(reader.GetInvalidDocumentPointer() == SchemaDocument::PointerType(""));
    EXPECT_TRUE(d.IsNull());
}

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
TEST(SchemaValidatingWriter, Simple) {
    Document sd;
    sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}");
    SchemaDocument s(sd);

    Document d;
    StringBuffer sb;
    Writer<StringBuffer> writer(sb);
    GenericSchemaValidator<SchemaDocument, Writer<StringBuffer> > validator(s, writer);

    d.Parse("\"red\"");
    EXPECT_TRUE(d.Accept(validator));
    EXPECT_TRUE(validator.IsValid());
    EXPECT_STREQ("\"red\"", sb.GetString());

    sb.Clear();
    validator.Reset();
    d.Parse("\"ABCD\"");
    EXPECT_FALSE(d.Accept(validator));
    EXPECT_FALSE(validator.IsValid());
Milo Yip's avatar
Milo Yip committed
1280 1281
    EXPECT_TRUE(validator.GetInvalidSchemaPointer() == SchemaDocument::PointerType(""));
    EXPECT_TRUE(validator.GetInvalidDocumentPointer() == SchemaDocument::PointerType(""));
1282 1283
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS

static SchemaDocument ReturnSchemaDocument() {
    Document sd;
    sd.Parse("{ \"type\": [\"number\", \"string\"] }");
    SchemaDocument s(sd);
    return s;
}

TEST(Schema, Issue552) {
    SchemaDocument s = ReturnSchemaDocument();
    VALIDATE(s, "42", true);
Milo Yip's avatar
Milo Yip committed
1296 1297
    VALIDATE(s, "\"Life, the universe, and everything\"", true);
    INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", "");
1298 1299 1300 1301
}

#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS

Milo Yip's avatar
Milo Yip committed
1302 1303 1304 1305 1306 1307 1308 1309 1310
TEST(SchemaValidator, Issue608) {
    Document sd;
    sd.Parse("{\"required\": [\"a\", \"b\"] }");
    SchemaDocument s(sd);

    VALIDATE(s, "{\"a\" : null, \"b\": null}", true);
    INVALIDATE(s, "{\"a\" : null, \"a\" : null}", "", "required", "");
}

1311 1312 1313
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif