From 7a505846bddae5e405d238f642df365db783993b Mon Sep 17 00:00:00 2001 From: peefy Date: Tue, 24 Oct 2023 20:36:52 +0800 Subject: [PATCH] feat: impl validate function error message output Signed-off-by: peefy --- pkg/tools/validate/validate.go | 8 +++++++- pkg/tools/validate/validate_test.go | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) 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()) + } +}