// NewSchemaValidator creates a new schema validator func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry) *SchemaValidator { if schema == nil { return nil } if rootSchema == nil { rootSchema = schema } if schema.ID != "" || schema.Ref.String() != "" || schema.Ref.IsRoot() { err := spec.ExpandSchema(schema, rootSchema, nil) if err != nil { panic(err) } } s := SchemaValidator{Path: root, in: "body", Schema: schema, Root: rootSchema, KnownFormats: formats} s.validators = []valueValidator{ s.typeValidator(), s.schemaPropsValidator(), s.stringValidator(), s.formatValidator(), s.numberValidator(), s.sliceValidator(), s.commonValidator(), s.objectValidator(), } return &s }
func TestJSONSchemaSuite(t *testing.T) { go func() { err := http.ListenAndServe(":1234", http.FileServer(http.Dir(jsonSchemaFixturesPath+"/remotes"))) if err != nil { panic(err.Error()) } }() Convey("The JSON Schema test suite", t, func() { files, err := ioutil.ReadDir(jsonSchemaFixturesPath) if err != nil { t.Fatal(err) } for _, f := range files { if f.IsDir() { continue } fileName := f.Name() specName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) if isEnabled(specName) { Convey("for "+specName, func() { b, _ := ioutil.ReadFile(filepath.Join(jsonSchemaFixturesPath, fileName)) var testDescriptions []schemaTestT json.Unmarshal(b, &testDescriptions) for _, testDescription := range testDescriptions { Convey(testDescription.Description, func() { So(spec.ExpandSchema(testDescription.Schema, nil, nil /*new(noopResCache)*/), ShouldBeNil) validator := NewSchemaValidator(testDescription.Schema, nil, "data", strfmt.Default) for _, test := range testDescription.Tests { Convey(test.Description, func() { result := validator.Validate(test.Data) So(result, ShouldNotBeNil) if test.Valid { So(result.Errors, ShouldBeEmpty) } else { So(result.Errors, ShouldNotBeEmpty) } }) } }) } }) } } }) }