added validation fixes

This commit is contained in:
Michael Jerger 2024-05-14 08:31:34 +02:00
parent fc38e56373
commit 9d32c5a29b
2 changed files with 23 additions and 2 deletions

View file

@ -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

View file

@ -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) {