1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 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 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
|
package jsonschema_test
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/santhosh-tekuri/jsonschema/v5"
_ "github.com/santhosh-tekuri/jsonschema/v5/httploader"
)
var skipTests = map[string]map[string][]string{
"TestDraft4/optional/zeroTerminatedFloats.json": {
"some languages do not distinguish between different types of numeric value": {}, // this behavior is changed in new drafts
},
"TestDraft4/optional/ecmascript-regex.json": {
"ECMA 262 \\s matches whitespace": {
"Line tabulation matches", // \s does not match vertical tab
"latin-1 non-breaking-space matches", // \s does not match unicode whitespace
"zero-width whitespace matches", // \s does not match unicode whitespace
"paragraph separator matches (line terminator)", // \s does not match unicode whitespace
"EM SPACE matches (Space_Separator)", // \s does not match unicode whitespace
},
"ECMA 262 \\S matches everything but whitespace": {
"Line tabulation does not match", // \S matches unicode whitespace
"latin-1 non-breaking-space does not match", // \S matches unicode whitespace
"zero-width whitespace does not match", // \S matches unicode whitespace
"paragraph separator does not match (line terminator)", // \S matches unicode whitespace
"EM SPACE does not match (Space_Separator)", // \S matches unicode whitespace
},
"ECMA 262 regex escapes control codes with \\c and upper letter": {}, // \cX is not supported
"ECMA 262 regex escapes control codes with \\c and lower letter": {}, // \cX is not supported
"patterns always use unicode semantics with pattern": {}, // invalid regex "\\p{Letter}cole"
"pattern with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patternProperties with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patterns always use unicode semantics with patternProperties": {}, // invalid regex "\\p{Letter}cole"
},
//
"TestDraft6/optional/ecmascript-regex.json": {
"ECMA 262 \\s matches whitespace": {
"Line tabulation matches", // \s does not match vertical tab
"latin-1 non-breaking-space matches", // \s does not match unicode whitespace
"zero-width whitespace matches", // \s does not match unicode whitespace
"paragraph separator matches (line terminator)", // \s does not match unicode whitespace
"EM SPACE matches (Space_Separator)", // \s does not match unicode whitespace
},
"ECMA 262 \\S matches everything but whitespace": {
"Line tabulation does not match", // \S matches unicode whitespace
"latin-1 non-breaking-space does not match", // \S matches unicode whitespace
"zero-width whitespace does not match", // \S matches unicode whitespace
"paragraph separator does not match (line terminator)", // \S matches unicode whitespace
"EM SPACE does not match (Space_Separator)", // \S matches unicode whitespace
},
"ECMA 262 regex escapes control codes with \\c and upper letter": {}, // \cX is not supported
"ECMA 262 regex escapes control codes with \\c and lower letter": {}, // \cX is not supported
"patterns always use unicode semantics with pattern": {}, // invalid regex "\\p{Letter}cole"
"pattern with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patternProperties with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patterns always use unicode semantics with patternProperties": {}, // invalid regex "\\p{Letter}cole"
},
//
"TestDraft7/optional/format/idn-hostname.json": {}, // idn-hostname format is not implemented
"TestDraft7/optional/format/idn-email.json": {}, // idn-email format is not implemented
"TestDraft7/optional/ecmascript-regex.json": {
"ECMA 262 \\s matches whitespace": {
"Line tabulation matches", // \s does not match vertical tab
"latin-1 non-breaking-space matches", // \s does not match unicode whitespace
"zero-width whitespace matches", // \s does not match unicode whitespace
"paragraph separator matches (line terminator)", // \s does not match unicode whitespace
"EM SPACE matches (Space_Separator)", // \s does not match unicode whitespace
},
"ECMA 262 \\S matches everything but whitespace": {
"Line tabulation does not match", // \S matches unicode whitespace
"latin-1 non-breaking-space does not match", // \S matches unicode whitespace
"zero-width whitespace does not match", // \S matches unicode whitespace
"paragraph separator does not match (line terminator)", // \S matches unicode whitespace
"EM SPACE does not match (Space_Separator)", // \S matches unicode whitespace
},
"ECMA 262 regex escapes control codes with \\c and upper letter": {}, // \cX is not supported
"ECMA 262 regex escapes control codes with \\c and lower letter": {}, // \cX is not supported
"patterns always use unicode semantics with pattern": {}, // invalid regex "\\p{Letter}cole"
"pattern with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patternProperties with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patterns always use unicode semantics with patternProperties": {}, // invalid regex "\\p{Letter}cole"
},
//
"TestDraft2019/optional/format/idn-hostname.json": {}, // idn-hostname format is not implemented
"TestDraft2019/optional/format/idn-email.json": {}, // idn-email format is not implemented
"TestDraft2019/optional/ecmascript-regex.json": {
"ECMA 262 \\s matches whitespace": {
"Line tabulation matches", // \s does not match vertical tab
"latin-1 non-breaking-space matches", // \s does not match unicode whitespace
"zero-width whitespace matches", // \s does not match unicode whitespace
"paragraph separator matches (line terminator)", // \s does not match unicode whitespace
"EM SPACE matches (Space_Separator)", // \s does not match unicode whitespace
},
"ECMA 262 \\S matches everything but whitespace": {
"Line tabulation does not match", // \S matches unicode whitespace
"latin-1 non-breaking-space does not match", // \S matches unicode whitespace
"zero-width whitespace does not match", // \S matches unicode whitespace
"paragraph separator does not match (line terminator)", // \S matches unicode whitespace
"EM SPACE does not match (Space_Separator)", // \S matches unicode whitespace
},
"ECMA 262 regex escapes control codes with \\c and upper letter": {}, // \cX is not supported
"ECMA 262 regex escapes control codes with \\c and lower letter": {}, // \cX is not supported
"patterns always use unicode semantics with pattern": {}, // invalid regex "\\p{Letter}cole"
"pattern with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patternProperties with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patterns always use unicode semantics with patternProperties": {}, // invalid regex "\\p{Letter}cole"
},
//
"TestDraft2020/optional/format/idn-hostname.json": {}, // idn-hostname format is not implemented
"TestDraft2020/optional/format/idn-email.json": {}, // idn-email format is not implemented
"TestDraft2020/optional/ecmascript-regex.json": {
"ECMA 262 \\s matches whitespace": {
"Line tabulation matches", // \s does not match vertical tab
"latin-1 non-breaking-space matches", // \s does not match unicode whitespace
"zero-width whitespace matches", // \s does not match unicode whitespace
"paragraph separator matches (line terminator)", // \s does not match unicode whitespace
"EM SPACE matches (Space_Separator)", // \s does not match unicode whitespace
},
"ECMA 262 \\S matches everything but whitespace": {
"Line tabulation does not match", // \S matches unicode whitespace
"latin-1 non-breaking-space does not match", // \S matches unicode whitespace
"zero-width whitespace does not match", // \S matches unicode whitespace
"paragraph separator does not match (line terminator)", // \S matches unicode whitespace
"EM SPACE does not match (Space_Separator)", // \S matches unicode whitespace
},
"ECMA 262 regex escapes control codes with \\c and upper letter": {}, // \cX is not supported
"ECMA 262 regex escapes control codes with \\c and lower letter": {}, // \cX is not supported
"patterns always use unicode semantics with pattern": {}, // invalid regex "\\p{Letter}cole"
"\\a is not an ECMA 262 control escape": {}, // \a is valid control sequence in go-regex
"pattern with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patternProperties with non-ASCII digits": {}, // invalid regex "^\\p{digit}+$"
"patterns always use unicode semantics with patternProperties": {}, // invalid regex "\\p{Letter}cole"
},
}
func TestDraft4(t *testing.T) {
t.Skip("SKIP test for Debian because of missing file")
testFolder(t, "testdata/JSON-Schema-Test-Suite/tests/draft4", jsonschema.Draft4)
}
func TestDraft6(t *testing.T) {
t.Skip("SKIP test for Debian because of missing file")
testFolder(t, "testdata/JSON-Schema-Test-Suite/tests/draft6", jsonschema.Draft6)
}
func TestDraft7(t *testing.T) {
t.Skip("SKIP test for Debian because of missing file")
testFolder(t, "testdata/JSON-Schema-Test-Suite/tests/draft7", jsonschema.Draft7)
}
func TestDraft2019(t *testing.T) {
t.Skip("SKIP test for Debian because of missing file")
testFolder(t, "testdata/JSON-Schema-Test-Suite/tests/draft2019-09", jsonschema.Draft2019)
}
func TestDraft2020(t *testing.T) {
t.Skip("SKIP test for Debian because of missing file")
testFolder(t, "testdata/JSON-Schema-Test-Suite/tests/draft2020-12", jsonschema.Draft2020)
}
func TestExtra(t *testing.T) {
t.Run("draft7", func(t *testing.T) {
testFolder(t, "testdata/tests/draft7", jsonschema.Draft7)
})
t.Run("draft2020", func(t *testing.T) {
testFolder(t, "testdata/tests/draft2020", jsonschema.Draft2020)
})
}
type testGroup struct {
Description string
Schema json.RawMessage
Tests []struct {
Description string
Data json.RawMessage
Valid bool
Skip *string
}
}
func TestMain(m *testing.M) {
server1 := &http.Server{Addr: "localhost:1234", Handler: http.FileServer(http.Dir("testdata/JSON-Schema-Test-Suite/remotes"))}
go func() {
if err := server1.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}()
server2 := &http.Server{Addr: "localhost:1235", Handler: http.FileServer(http.Dir("testdata/remotes"))}
go func() {
if err := server2.ListenAndServe(); err != http.ErrServerClosed {
panic(err)
}
}()
os.Exit(m.Run())
}
func testFolder(t *testing.T, folder string, draft *jsonschema.Draft) {
fis, err := ioutil.ReadDir(folder)
if err != nil {
t.Fatal(err)
}
for _, fi := range fis {
if fi.IsDir() {
t.Run(fi.Name(), func(t *testing.T) {
testFolder(t, path.Join(folder, fi.Name()), draft)
})
continue
}
if path.Ext(fi.Name()) != ".json" {
continue
}
t.Run(fi.Name(), func(t *testing.T) {
skip := skipTests[t.Name()]
if skip != nil && len(skip) == 0 {
t.Skip()
}
f, err := os.Open(path.Join(folder, fi.Name()))
if err != nil {
t.Fatal(err)
}
defer f.Close()
var tg []struct {
Description string
Schema json.RawMessage
Tests []struct {
Description string
Data interface{}
Valid bool
}
}
dec := json.NewDecoder(f)
dec.UseNumber()
if err = dec.Decode(&tg); err != nil {
t.Fatal(err)
}
for _, group := range tg {
t.Run(group.Description, func(t *testing.T) {
skip := skip[group.Description]
if skip != nil && len(skip) == 0 {
t.Skip()
}
c := jsonschema.NewCompiler()
c.Draft = draft
if strings.Index(folder, "optional") != -1 {
c.AssertFormat = true
c.AssertContent = true
}
if err := c.AddResource("schema.json", bytes.NewReader(group.Schema)); err != nil {
t.Fatal(err)
}
schema, err := c.Compile("schema.json")
if err != nil {
t.Fatalf("%#v", err)
}
for _, test := range group.Tests {
t.Run(test.Description, func(t *testing.T) {
for _, desc := range skip {
if test.Description == desc {
t.Skip()
}
}
err = schema.Validate(test.Data)
valid := err == nil
if !valid {
if _, ok := err.(*jsonschema.ValidationError); ok {
for _, line := range strings.Split(err.(*jsonschema.ValidationError).GoString(), "\n") {
t.Logf("%s", line)
}
} else {
t.Fatalf("got: %#v, want: *jsonschema.ValidationError", err)
}
}
if test.Valid != valid {
t.Fatalf("valid: got %v, want %v", valid, test.Valid)
}
})
}
})
}
})
}
}
func TestMustCompile(t *testing.T) {
t.Run("invalid", func(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("panic expected")
}
}()
jsonschema.MustCompile("testdata/invalid_schema.json")
})
t.Run("valid", func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Error("panic not expected")
t.Log(r)
}
}()
jsonschema.MustCompile("testdata/person_schema.json")
})
}
func TestInvalidSchema(t *testing.T) {
t.Run("invalid json", func(t *testing.T) {
if err := jsonschema.NewCompiler().AddResource("test.json", strings.NewReader("{")); err == nil {
t.Error("error expected")
} else {
t.Logf("%v", err)
}
})
t.Run("multiple json", func(t *testing.T) {
if err := jsonschema.NewCompiler().AddResource("test.json", strings.NewReader("{}{}")); err == nil {
t.Error("error expected")
} else {
t.Logf("%v", err)
}
})
httpURL, httpsURL, cleanup := runHTTPServers()
defer cleanup()
invalidTests := []struct {
description string
url string
}{
{"syntax error", "testdata/syntax_error.json"},
{"missing filepath", "testdata/missing.json"},
{"missing fileurl", toFileURL("testdata/missing.json")},
{"missing httpurl", httpURL + "/missing.json"},
{"missing httpsurl", httpsURL + "/missing.json"},
}
for _, test := range invalidTests {
t.Run(test.description, func(t *testing.T) {
if _, err := jsonschema.Compile(test.url); err == nil {
t.Error("expected error")
} else {
t.Logf("%v", err)
}
})
}
type test struct {
Description string
Schema json.RawMessage
Fragment string
}
data, err := ioutil.ReadFile("testdata/invalid_schemas.json")
if err != nil {
t.Fatal(err)
}
var tests []test
if err = json.Unmarshal(data, &tests); err != nil {
t.Fatal(err)
}
for _, test := range tests {
t.Run(test.Description, func(t *testing.T) {
c := jsonschema.NewCompiler()
url := "test.json"
if err := c.AddResource(url, bytes.NewReader(test.Schema)); err != nil {
t.Fatal(err)
}
if len(test.Fragment) > 0 {
url += test.Fragment
}
if _, err = c.Compile(url); err == nil {
t.Error("error expected")
} else {
t.Logf("%#v", err)
}
})
}
}
func TestCompileURL(t *testing.T) {
httpURL, httpsURL, cleanup := runHTTPServers()
defer cleanup()
validTests := []struct {
schema, doc string
}{
//{"testdata/customer_schema.json#/0", "testdata/customer.json"},
//{toFileURL("testdata/customer_schema.json") + "#/0", "testdata/customer.json"},
//{httpURL + "/customer_schema.json#/0", "testdata/customer.json"},
//{httpsURL + "/customer_schema.json#/0", "testdata/customer.json"},
{toFileURL("testdata/empty schema.json"), "testdata/empty schema.json"},
{httpURL + "/empty schema.json", "testdata/empty schema.json"},
{httpsURL + "/empty schema.json", "testdata/empty schema.json"},
}
for i, test := range validTests {
t.Run(test.schema, func(t *testing.T) {
s, err := jsonschema.Compile(test.schema)
if err != nil {
t.Errorf("valid #%d: %v", i, err)
return
}
f, err := os.Open(test.doc)
if err != nil {
t.Errorf("valid #%d: %v", i, err)
return
}
err = s.Validate(f)
_ = f.Close()
if err != nil {
t.Errorf("valid #%d: %v", i, err)
}
})
}
}
func TestInvalidJsonTypeError(t *testing.T) {
compiler := jsonschema.NewCompiler()
err := compiler.AddResource("test.json", strings.NewReader(`{ "type": "string"}`))
if err != nil {
t.Fatalf("addResource failed. reason: %v\n", err)
}
schema, err := compiler.Compile("test.json")
if err != nil {
t.Fatalf("schema compilation failed. reason: %v\n", err)
}
v := struct{ name string }{"hello world"}
err = schema.Validate(v)
switch err.(type) {
case jsonschema.InvalidJSONTypeError:
// passed: struct is not valid json type
default:
t.Fatalf("got %v. want InvalidJSONTypeErr", err)
}
}
func TestInfiniteLoopError(t *testing.T) {
t.Run("compile", func(t *testing.T) {
compiler := jsonschema.NewCompiler()
_, err := compiler.Compile("testdata/loop-compile.json")
if err == nil {
t.Fatal("error expected")
}
switch err := err.(*jsonschema.SchemaError).Err.(type) {
case jsonschema.InfiniteLoopError:
suffix := "testdata/loop-compile.json#/$ref/$ref/not/$ref/allOf/0/$ref/anyOf/0/$ref/oneOf/0/$ref/dependencies/prop/$ref/dependentSchemas/prop/$ref/then/$ref/else/$ref"
if !strings.HasSuffix(string(err), suffix) {
t.Errorf(" got: %s", string(err))
t.Errorf("want-suffix: %s", suffix)
}
default:
t.Fatalf("got %#v. want InfiniteLoopTypeErr", err)
}
})
t.Run("validate", func(t *testing.T) {
compiler := jsonschema.NewCompiler()
schema, err := compiler.Compile("testdata/loop-validate.json")
if err != nil {
t.Fatal(err)
}
err = schema.Validate(decodeString(t, `{"prop": 1}`))
switch err := err.(type) {
case jsonschema.InfiniteLoopError:
suffix := "testdata/loop-validate.json#/$ref/$ref/not/$ref/allOf/0/$ref/anyOf/0/$ref/oneOf/0/$ref/dependencies/prop/$ref/dependentSchemas/prop/$ref/then/$ref/else/$dynamicRef/$ref"
if !strings.HasSuffix(string(err), suffix) {
t.Errorf(" got: %s", string(err))
t.Errorf("want-suffix: %s", suffix)
}
default:
t.Fatalf("got %#v. want InfiniteLoopTypeErr", err)
}
})
}
func TestExtractAnnotations(t *testing.T) {
str := `{
"title": "this is title",
"description": "this is description",
"$comment": "this is comment",
"format": "date-time",
"examples": ["2019-04-09T21:54:56.052Z"],
"readOnly": true,
"writeOnly": true,
"deprecated": true
}`
t.Run("false", func(t *testing.T) {
compiler := jsonschema.NewCompiler()
err := compiler.AddResource("test.json", strings.NewReader(str))
if err != nil {
t.Fatalf("addResource failed. reason: %v\n", err)
}
schema, err := compiler.Compile("test.json")
if err != nil {
t.Fatalf("schema compilation failed. reason: %v\n", err)
}
if schema.Title != "" {
t.Error("title should not be extracted")
}
if schema.Description != "" {
t.Error("description should not be extracted")
}
if schema.Comment != "" {
t.Error("comment should not be extracted")
}
if len(schema.Examples) != 0 {
t.Error("examples should not be extracted")
}
if schema.ReadOnly {
t.Error("readOnly should not be extracted")
}
if schema.WriteOnly {
t.Error("writeOnly should not be extracted")
}
if schema.Deprecated {
t.Error("Deprecated should not be extracted")
}
})
t.Run("true", func(t *testing.T) {
compiler := jsonschema.NewCompiler()
compiler.ExtractAnnotations = true
err := compiler.AddResource("test.json", strings.NewReader(str))
if err != nil {
t.Fatalf("addResource failed. reason: %v\n", err)
}
schema, err := compiler.Compile("test.json")
if err != nil {
t.Fatalf("schema compilation failed. reason: %v\n", err)
}
if schema.Title != "this is title" {
t.Errorf("title: got %q, want %q", schema.Title, "this is title")
}
if schema.Description != "this is description" {
t.Errorf("description: got %q, want %q", schema.Description, "this is description")
}
if schema.Comment != "this is comment" {
t.Errorf("$comment: got %q, want %q", schema.Comment, "this is comment")
}
if schema.Examples[0] != "2019-04-09T21:54:56.052Z" {
t.Errorf("example: got %q, want %q", schema.Examples[0], "2019-04-09T21:54:56.052Z")
}
if !schema.ReadOnly {
t.Error("readOnly should be extracted")
}
if !schema.WriteOnly {
t.Error("writeOnly should be extracted")
}
if !schema.Deprecated {
t.Error("Deprecated should be extracted")
}
})
}
func toFileURL(path string) string {
path, err := filepath.Abs(path)
if err != nil {
panic(err)
}
path = filepath.ToSlash(path)
if runtime.GOOS == "windows" {
path = "/" + path
}
u, err := url.Parse("file://" + path)
if err != nil {
panic(err)
}
return u.String()
}
// TestPanic tests https://github.com/santhosh-tekuri/jsonschema/issues/18
func TestPanic(t *testing.T) {
schema_d := `
{
"type": "object",
"properties": {
"myid": { "type": "integer" },
"otype": { "$ref": "defs.json#someid" }
}
}
`
defs_d := `
{
"definitions": {
"stt": {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "#someid",
"type": "object",
"enum": [ { "name": "stainless" }, { "name": "zinc" } ]
}
}
}
`
c := jsonschema.NewCompiler()
c.Draft = jsonschema.Draft7
if err := c.AddResource("schema.json", strings.NewReader(schema_d)); err != nil {
t.Fatal(err)
}
if err := c.AddResource("defs.json", strings.NewReader(defs_d)); err != nil {
t.Fatal(err)
}
if _, err := c.Compile("schema.json"); err != nil {
t.Fatal(err)
}
}
func TestNonStringFormat(t *testing.T) {
jsonschema.Formats["even-number"] = func(v interface{}) bool {
switch v := v.(type) {
case int:
return v%2 == 0
default:
return false
}
}
schema := `{"type": "integer", "format": "even-number"}`
c := jsonschema.NewCompiler()
c.AssertFormat = true
if err := c.AddResource("schema.json", strings.NewReader(schema)); err != nil {
t.Fatal(err)
}
s, err := c.Compile("schema.json")
if err != nil {
t.Fatal(err)
}
if err = s.Validate(5); err == nil {
t.Fatal("error expected")
}
if err = s.Validate(6); err != nil {
t.Fatalf("%#v", err)
}
}
func TestCompiler_LoadURL(t *testing.T) {
const (
base = `{ "type": "string" }`
schema = `{ "allOf": [{ "$ref": "base.json" }, { "maxLength": 3 }] }`
)
c := jsonschema.NewCompiler()
c.LoadURL = func(s string) (io.ReadCloser, error) {
switch s {
case "map:///base.json":
return ioutil.NopCloser(strings.NewReader(base)), nil
case "map:///schema.json":
return ioutil.NopCloser(strings.NewReader(schema)), nil
default:
return nil, errors.New("unsupported schema")
}
}
s, err := c.Compile("map:///schema.json")
if err != nil {
t.Fatal(err)
}
if err = s.Validate("foo"); err != nil {
t.Fatal(err)
}
if err = s.Validate("long"); err == nil {
t.Fatal("error expected")
}
}
func TestFilePathSpaces(t *testing.T) {
if _, err := jsonschema.Compile("testdata/person schema.json"); err != nil {
t.Fatal(err)
}
}
func TestSchemaDraftFeild(t *testing.T) {
var schemas = map[string]string{
"main.json": `{"$schema": "https://json-schema.org/draft/2020-12/schema", "$ref":"obj.json"}`,
"obj.json": `{"$schema": "https://json-schema.org/draft/2019-09/schema", "type":"object"}`,
}
jsonschema.Loaders["map"] = func(url string) (io.ReadCloser, error) {
schema, ok := schemas[strings.TrimPrefix(url, "map:///")]
if !ok {
return nil, fmt.Errorf("%q not found", url)
}
return ioutil.NopCloser(strings.NewReader(schema)), nil
}
sch, err := jsonschema.Compile("map:///main.json")
if err != nil {
t.Fatalf("%+v", err)
}
if sch.Draft != jsonschema.Draft2020 {
t.Errorf("got: %s, want: %s", sch.Draft, jsonschema.Draft2020)
}
if sch.Ref.Draft != jsonschema.Draft2019 {
t.Errorf("got: %s, want: %s", sch.Ref.Draft, jsonschema.Draft2019)
}
}
func runHTTPServers() (httpURL, httpsURL string, cleanup func()) {
tr := http.DefaultTransport.(*http.Transport)
if tr.TLSClientConfig == nil {
tr.TLSClientConfig = &tls.Config{}
}
tr.TLSClientConfig.InsecureSkipVerify = true
handler := http.FileServer(http.Dir("testdata"))
httpServer := httptest.NewServer(handler)
httpsServer := httptest.NewTLSServer(handler)
return httpServer.URL, httpsServer.URL, func() {
httpServer.Close()
httpsServer.Close()
}
}
func decodeString(t *testing.T, s string) interface{} {
t.Helper()
return decodeReader(t, strings.NewReader(s))
}
func decodeReader(t *testing.T, r io.Reader) interface{} {
t.Helper()
decoder := json.NewDecoder(r)
decoder.UseNumber()
var doc interface{}
if err := decoder.Decode(&doc); err != nil {
t.Fatal("invalid json:", err)
}
return doc
}
|