diff --git a/pkg/tools/validate/validate.go b/pkg/tools/validate/validate.go index 3e1ef08f..93b661ad 100644 --- a/pkg/tools/validate/validate.go +++ b/pkg/tools/validate/validate.go @@ -3,6 +3,8 @@ package validate import ( + "errors" + "kcl-lang.io/kcl-go/pkg/service" "kcl-lang.io/kcl-go/pkg/spec/gpyrpc" ) @@ -28,5 +30,9 @@ func ValidateCode(data, code string, opt *ValidateOptions) (ok bool, err error) if err != nil { return false, err } - return resp.Success, nil + var e error = nil + if resp.ErrMessage != "" { + e = errors.New(resp.ErrMessage) + } + return resp.Success, e } diff --git a/pkg/tools/validate/validate_test.go b/pkg/tools/validate/validate_test.go index adee04f8..5537de3b 100644 --- a/pkg/tools/validate/validate_test.go +++ b/pkg/tools/validate/validate_test.go @@ -3,6 +3,7 @@ package validate import ( + "strings" "testing" ) @@ -24,3 +25,21 @@ schema Person: t.Fatalf("expect: %q, got False", "True") } } + +func TestValidateCodeFail(t *testing.T) { + data := `{"k": "value"}` + code := ` +schema Person: + key: str + + check: + "value" in key # 'key' is required and 'key' must contain "value" +` + + _, err := ValidateCode(data, code, nil) + if err == nil { + t.Fatalf("expect validation error") + } else if !strings.Contains(err.Error(), "error") { + t.Fatalf("expect validation error, got %s", err.Error()) + } +}