Skip to content

Commit

Permalink
pass 10
Browse files Browse the repository at this point in the history
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
  • Loading branch information
fredbi committed Jan 22, 2024
1 parent 3b98928 commit 0f077a3
Show file tree
Hide file tree
Showing 16 changed files with 119 additions and 91 deletions.
4 changes: 2 additions & 2 deletions formats.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (f *formatValidator) SetPath(path string) {
}

func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool {
if source == nil {
if source == nil || f.KnownFormats == nil {
return false
}

Expand All @@ -74,7 +74,7 @@ func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool {
}

func (f *formatValidator) Validate(val interface{}) *Result {
if f.Options.recycleValidators && !f.Options.skipRedeemOnValidate {
if f.Options.recycleValidators {
defer func() {
f.redeem()
}()
Expand Down
7 changes: 4 additions & 3 deletions formats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import (
// Validator for string formats
func TestFormatValidator_EdgeCases(t *testing.T) {
// Apply
v := formatValidator{
KnownFormats: strfmt.Default,
}
v := newFormatValidator(
"", "", "", strfmt.Default, nil,
)
v.SetPath("a.b.c")

// formatValidator applies to: Items, Parameter,Schema

Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
module github.com/go-openapi/validate

replace github.com/go-openapi/swag => github.com/fredbi/swag v0.22.8-fred2

require (
github.com/go-openapi/analysis v0.22.0
github.com/go-openapi/errors v0.21.0
github.com/go-openapi/jsonpointer v0.20.2
github.com/go-openapi/loads v0.21.5
github.com/go-openapi/spec v0.20.14
github.com/go-openapi/strfmt v0.22.0
github.com/go-openapi/swag v0.22.7
github.com/go-openapi/swag v0.22.8
github.com/stretchr/testify v1.8.4
gopkg.in/yaml.v3 v3.0.1
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3d
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fredbi/swag v0.22.8-fred2 h1:6mm1vWEsjFhgiI0XIUjgR+YkpklZYDPxGLgFcGtIE/0=
github.com/fredbi/swag v0.22.8-fred2/go.mod h1:6QT22icPLEqAM/z/TChgb4WAveCHF92+2gF0CNjHpPI=
github.com/go-openapi/analysis v0.22.0 h1:wQ/d07nf78HNj4u+KiSY0sT234IAyePPbMgpUjUJQR0=
github.com/go-openapi/analysis v0.22.0/go.mod h1:acDnkkCI2QxIo8sSIPgmp1wUlRohV7vfGtAIVae73b0=
github.com/go-openapi/errors v0.21.0 h1:FhChC/duCnfoLj1gZ0BgaBmzhJC2SL/sJr8a2vAobSY=
Expand All @@ -18,6 +16,8 @@ github.com/go-openapi/spec v0.20.14 h1:7CBlRnw+mtjFGlPDRZmAMnq35cRzI91xj03HVyUi/
github.com/go-openapi/spec v0.20.14/go.mod h1:8EOhTpBoFiask8rrgwbLC3zmJfz4zsCUueRuPM6GNkw=
github.com/go-openapi/strfmt v0.22.0 h1:Ew9PnEYc246TwrEspvBdDHS4BVKXy/AOVsfqGDgAcaI=
github.com/go-openapi/strfmt v0.22.0/go.mod h1:HzJ9kokGIju3/K6ap8jL+OlGAbjpSv27135Yr9OivU4=
github.com/go-openapi/swag v0.22.8 h1:/9RjDSQ0vbFR+NyjGMkFTsA1IA0fmhKSThmfGZjicbw=
github.com/go-openapi/swag v0.22.8/go.mod h1:6QT22icPLEqAM/z/TChgb4WAveCHF92+2gF0CNjHpPI=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
Expand Down
8 changes: 4 additions & 4 deletions object_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ func newObjectValidator(path, in string,
additionalProperties *spec.SchemaOrBool, patternProperties spec.SchemaProperties,
root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *objectValidator {
if opts == nil {
opts = &SchemaValidatorOptions{}
opts = new(SchemaValidatorOptions)
}

var v *objectValidator
if opts.recycleValidators {
v = poolOfObjectValidators.BorrowValidator()
} else {
v = &objectValidator{}
v = new(objectValidator)
}

v.Path = path
Expand Down Expand Up @@ -138,7 +138,7 @@ func (o *objectValidator) precheck(res *Result, val map[string]interface{}) {
}

func (o *objectValidator) Validate(data interface{}) *Result {
if o.Options.recycleValidators && !o.Options.skipRedeemOnValidate {
if o.Options.recycleValidators {
defer func() {
o.redeem()
}()
Expand Down Expand Up @@ -343,7 +343,7 @@ func (o *objectValidator) validatePropertiesSchema(val map[string]interface{}, r
// if a default value is defined, creates the property from defaults
// NOTE: JSON schema does not enforce default values to be valid against schema. Swagger does.
createdFromDefaults[pName] = struct{}{}
res.addPropertySchemata(val, pName, pSchema) // TODO(fred): issue there reusing a pointer
res.addPropertySchemata(val, pName, pSchema) // this shallow-clones the content of the pSchema pointer
}
}

Expand Down
6 changes: 4 additions & 2 deletions result.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,14 @@ func (r *Result) addRootObjectSchemata(s *spec.Schema) {
}

// addPropertySchemata adds the given schemata for the object and field.
// The slice schemata might be reused. I.e. do not modify it after being added to a result.
//
// Since the slice schemata might be reused, it is shallow-cloned before saving it into the result.
func (r *Result) addPropertySchemata(obj map[string]interface{}, fld string, schema *spec.Schema) {
if r.fieldSchemata == nil {
r.fieldSchemata = make([]fieldSchemata, 0, len(obj))
}
r.fieldSchemata = append(r.fieldSchemata, fieldSchemata{obj: obj, field: fld, schemata: schemata{one: schema}})
clone := *schema
r.fieldSchemata = append(r.fieldSchemata, fieldSchemata{obj: obj, field: fld, schemata: schemata{one: &clone}})
}

/*
Expand Down
14 changes: 8 additions & 6 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ type SchemaValidator struct {
//
// When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example.
func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry, options ...Option) error {
res := NewSchemaValidator(schema, nil, "", formats, append(options, WithRecycleValidators(true))...).Validate(data)
res := NewSchemaValidator(schema, nil, "", formats,
append(options, WithRecycleValidators(true))...,
).Validate(data)
if res.HasErrors() {
return errors.CompositeValidationError(res.Errors...)
}
Expand All @@ -50,7 +52,7 @@ func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registr
//
// Panics if the provided schema is invalid.
func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, options ...Option) *SchemaValidator {
opts := &SchemaValidatorOptions{}
opts := new(SchemaValidatorOptions)
for _, o := range options {
o(opts)
}
Expand All @@ -76,7 +78,7 @@ func newSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string
}

if opts == nil {
opts = &SchemaValidatorOptions{}
opts = new(SchemaValidatorOptions)
}

var s *SchemaValidator
Expand Down Expand Up @@ -132,7 +134,7 @@ func (s *SchemaValidator) Validate(data interface{}) *Result {
result = &Result{data: data}
}

if s.Options.recycleValidators && !s.Options.skipRedeemOnValidate {
if s.Options.recycleValidators {
defer func() {
s.redeem() // one-time use validator
}()
Expand All @@ -147,7 +149,7 @@ func (s *SchemaValidator) Validate(data interface{}) *Result {
result.Merge(s.validators[0].Validate(data)) // type validator
result.Merge(s.validators[6].Validate(data)) // common validator

if s.Options.recycleValidators && !s.Options.skipRedeemOnValidate {
if s.Options.recycleValidators {
s.validators[0] = nil
s.validators[6] = nil
s.redeemChildren()
Expand Down Expand Up @@ -200,7 +202,7 @@ func (s *SchemaValidator) Validate(data interface{}) *Result {

for idx, v := range s.validators {
if !v.Applies(s.Schema, kind) {
if s.Options.recycleValidators && !s.Options.skipRedeemOnValidate {
if s.Options.recycleValidators {
// Validate won't be called, so relinquish this validator
if redeemableChildren, ok := v.(interface{ redeemChildren() }); ok {
redeemableChildren.redeemChildren()
Expand Down
28 changes: 0 additions & 28 deletions schema_option.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ type SchemaValidatorOptions struct {
EnableObjectArrayTypeCheck bool
EnableArrayMustHaveItemsCheck bool
recycleValidators bool
skipRedeemOnValidate bool // internal use for slice validation
recycleResult bool
intern intern
}
Expand Down Expand Up @@ -57,32 +56,6 @@ func WithRecycleValidators(enable bool) Option {
}
}

func withSkipRedeemOnValidate(enable bool) Option {
return func(svo *SchemaValidatorOptions) {
svo.skipRedeemOnValidate = enable
}
}

func withOptions(o SchemaValidatorOptions) Option {
return func(svo *SchemaValidatorOptions) {
*svo = o
}
}

func withOptionsForceNoSkip(o SchemaValidatorOptions) Option {
return func(svo *SchemaValidatorOptions) {
*svo = o
svo.skipRedeemOnValidate = false
}
}

func withOptionsForceSkip(o SchemaValidatorOptions) Option {
return func(svo *SchemaValidatorOptions) {
*svo = o
svo.skipRedeemOnValidate = true
}
}

func withRecycleResults(enable bool) Option {
return func(svo *SchemaValidatorOptions) {
svo.recycleResult = enable
Expand All @@ -103,6 +76,5 @@ func (svo SchemaValidatorOptions) Options() []Option {
EnableObjectArrayTypeCheck(svo.EnableObjectArrayTypeCheck),
EnableArrayMustHaveItemsCheck(svo.EnableArrayMustHaveItemsCheck),
WithRecycleValidators(svo.recycleValidators),

Check warning on line 78 in schema_option.go

View check run for this annotation

Codecov / codecov/patch

schema_option.go#L78

Added line #L78 was not covered by tests
withSkipRedeemOnValidate(svo.skipRedeemOnValidate),
}
}
4 changes: 2 additions & 2 deletions schema_props.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func newSchemaPropsValidator(
path string, in string, allOf, oneOf, anyOf []spec.Schema, not *spec.Schema, deps spec.Dependencies, root interface{}, formats strfmt.Registry,
opts *SchemaValidatorOptions) *schemaPropsValidator {
if opts == nil {
opts = &SchemaValidatorOptions{}
opts = new(SchemaValidatorOptions)
}

anyValidators := make([]*SchemaValidator, 0, len(anyOf))
Expand Down Expand Up @@ -113,7 +113,7 @@ func (s *schemaPropsValidator) Validate(data interface{}) *Result {
keepResultOneOf := poolOfResults.BorrowResult()
keepResultAllOf := poolOfResults.BorrowResult()

if s.Options.recycleValidators && !s.Options.skipRedeemOnValidate {
if s.Options.recycleValidators {
defer func() {
s.redeem()

Expand Down
4 changes: 3 additions & 1 deletion schema_props_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ package validate
import (
"testing"

"github.com/go-openapi/strfmt"
"github.com/stretchr/testify/assert"
)

// Test edge cases in schema_props_validator which are difficult
// to simulate with specs
// (this one is a trivial, just to check all methods are filled)
func TestSchemaPropsValidator_EdgeCases(t *testing.T) {
s := schemaPropsValidator{}
s := newSchemaPropsValidator(
"", "", nil, nil, nil, nil, nil, nil, strfmt.Default, nil)
s.SetPath("path")
assert.Equal(t, "path", s.Path)
}
4 changes: 2 additions & 2 deletions slice_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func newSliceValidator(path, in string,
additionalItems *spec.SchemaOrBool, items *spec.SchemaOrArray,
root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *schemaSliceValidator {
if opts == nil {
opts = &SchemaValidatorOptions{}
opts = new(SchemaValidatorOptions)
}

var v *schemaSliceValidator
Expand Down Expand Up @@ -75,7 +75,7 @@ func (s *schemaSliceValidator) Applies(source interface{}, kind reflect.Kind) bo
}

func (s *schemaSliceValidator) Validate(data interface{}) *Result {
if s.Options.recycleValidators && !s.Options.skipRedeemOnValidate {
if s.Options.recycleValidators {
defer func() {
s.redeem()
}()
Expand Down
2 changes: 1 addition & 1 deletion spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ type SpecValidator struct {
// NewSpecValidator creates a new swagger spec validator instance
func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator {
// schema options that apply to all called validators
schemaOptions := &SchemaValidatorOptions{}
schemaOptions := new(SchemaValidatorOptions)
for _, o := range []Option{
SwaggerSchema(true),
WithRecycleValidators(true),
Expand Down
4 changes: 2 additions & 2 deletions type.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type typeValidator struct {

func newTypeValidator(path, in string, typ spec.StringOrArray, nullable bool, format string, opts *SchemaValidatorOptions) *typeValidator {
if opts == nil {
opts = &SchemaValidatorOptions{}
opts = new(SchemaValidatorOptions)
}

var t *typeValidator
Expand Down Expand Up @@ -162,7 +162,7 @@ func (t *typeValidator) Applies(source interface{}, _ reflect.Kind) bool {
}

func (t *typeValidator) Validate(data interface{}) *Result {
if t.Options.recycleValidators && !t.Options.skipRedeemOnValidate {
if t.Options.recycleValidators {
defer func() {
t.redeem()
}()
Expand Down
11 changes: 10 additions & 1 deletion type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ package validate

import (
"io"
"reflect"
"testing"
"time"

"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type expectedJSONType struct {
Expand Down Expand Up @@ -263,7 +265,14 @@ func TestType_schemaInfoForType(t *testing.T) {
*/
}

v := &typeValidator{}
v := newTypeValidator(
"", "", nil, false, "", nil,
)

t.Run("should not apply", func(t *testing.T) {
require.False(t, v.Applies("x", reflect.Map))
})

for _, x := range testTypes {
value := x.value

Expand Down
Loading

0 comments on commit 0f077a3

Please sign in to comment.