From 9d32c5a29b31ce1c1234ea6d85f9ea6ac9873ab7 Mon Sep 17 00:00:00 2001 From: Michael Jerger Date: Tue, 14 May 2024 08:31:34 +0200 Subject: [PATCH] added validation fixes --- modules/validation/validatable.go | 19 ++++++++++++++++++- modules/validation/validatable_test.go | 6 +++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/modules/validation/validatable.go b/modules/validation/validatable.go index fc38ad2524..94b5cc135c 100644 --- a/modules/validation/validatable.go +++ b/modules/validation/validatable.go @@ -6,20 +6,37 @@ package validation import ( "fmt" + "reflect" "strings" "unicode/utf8" "code.gitea.io/gitea/modules/timeutil" ) +// ErrNotValid represents an validation error +type ErrNotValid struct { + Message string +} + +func (err ErrNotValid) Error() string { + return fmt.Sprintf("Validation Error: %v", err.Message) +} + +// IsErrNotValid checks if an error is a ErrNotValid. +func IsErrNotValid(err error) bool { + _, ok := err.(ErrNotValid) + return ok +} + type Validateable interface { Validate() []string } func IsValid(v Validateable) (bool, error) { if err := v.Validate(); len(err) > 0 { + typeof := reflect.TypeOf(v) errString := strings.Join(err, "\n") - return false, fmt.Errorf(errString) + return false, ErrNotValid{fmt.Sprint(typeof, ": ", errString)} } return true, nil diff --git a/modules/validation/validatable_test.go b/modules/validation/validatable_test.go index fdc21f3223..919f5a3183 100644 --- a/modules/validation/validatable_test.go +++ b/modules/validation/validatable_test.go @@ -26,9 +26,13 @@ func Test_IsValid(t *testing.T) { t.Errorf("sut expected to be valid: %v\n", sut.Validate()) } sut = Sut{valid: false} - if res, _ := IsValid(sut); res { + res, err := IsValid(sut) + if res { t.Errorf("sut expected to be invalid: %v\n", sut.Validate()) } + if err == nil || !IsErrNotValid(err) || err.Error() != "Validation Error: validation.Sut: invalid" { + t.Errorf("validation error expected, but was %v", err) + } } func Test_ValidateNotEmpty_ForString(t *testing.T) {