From e3bb34851d02b04671be2792153eb2eff5c05c56 Mon Sep 17 00:00:00 2001 From: Aleksey Levenstein Date: Mon, 27 Feb 2023 17:16:00 +0200 Subject: [PATCH] fix: expose error instance path instead of schema path (#177) --- pkg/validator/validator.go | 2 +- pkg/validator/validator_test.go | 56 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/pkg/validator/validator.go b/pkg/validator/validator.go index c7a430d7..f4827c89 100644 --- a/pkg/validator/validator.go +++ b/pkg/validator/validator.go @@ -197,7 +197,7 @@ func (val *v) ValidateResource(res resource.Resource) Result { if errors.As(err, &e) { for _, ve := range e.Causes { validationErrors = append(validationErrors, ValidationError{ - Path: ve.KeywordLocation, + Path: ve.InstanceLocation, Msg: ve.Message, }) } diff --git a/pkg/validator/validator_test.go b/pkg/validator/validator_test.go index 16f2c6ad..07762539 100644 --- a/pkg/validator/validator_test.go +++ b/pkg/validator/validator_test.go @@ -1,6 +1,7 @@ package validator import ( + "reflect" "testing" "github.com/yannh/kubeconform/pkg/registry" @@ -379,3 +380,58 @@ lastName: bar } } } + +func TestValidationErrors(t *testing.T) { + rawResource := []byte(` +kind: name +apiVersion: v1 +firstName: foo +age: not a number +`) + + schema := []byte(`{ + "title": "Example Schema", + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "age": { + "description": "Age in years", + "type": "integer", + "minimum": 0 + } + }, + "required": ["firstName", "lastName"] +}`) + + expectedErrors := []ValidationError{ + {Path: "", Msg: "missing properties: 'lastName'"}, + {Path: "/age", Msg: "expected integer, but got string"}, + } + + val := v{ + opts: Opts{ + SkipKinds: map[string]struct{}{}, + RejectKinds: map[string]struct{}{}, + }, + schemaCache: nil, + schemaDownload: downloadSchema, + regs: []registry.Registry{ + newMockRegistry(func() (string, []byte, error) { + return "", schema, nil + }), + }, + } + + got := val.ValidateResource(resource.Resource{Bytes: rawResource}) + if !reflect.DeepEqual(expectedErrors, got.ValidationErrors) { + t.Errorf("Expected %+v, got %+v", expectedErrors, got.ValidationErrors) + } +}