added validation fixes
This commit is contained in:
parent
fc38e56373
commit
9d32c5a29b
|
@ -6,20 +6,37 @@ package validation
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"code.gitea.io/gitea/modules/timeutil"
|
"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 {
|
type Validateable interface {
|
||||||
Validate() []string
|
Validate() []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsValid(v Validateable) (bool, error) {
|
func IsValid(v Validateable) (bool, error) {
|
||||||
if err := v.Validate(); len(err) > 0 {
|
if err := v.Validate(); len(err) > 0 {
|
||||||
|
typeof := reflect.TypeOf(v)
|
||||||
errString := strings.Join(err, "\n")
|
errString := strings.Join(err, "\n")
|
||||||
return false, fmt.Errorf(errString)
|
return false, ErrNotValid{fmt.Sprint(typeof, ": ", errString)}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true, nil
|
return true, nil
|
||||||
|
|
|
@ -26,9 +26,13 @@ func Test_IsValid(t *testing.T) {
|
||||||
t.Errorf("sut expected to be valid: %v\n", sut.Validate())
|
t.Errorf("sut expected to be valid: %v\n", sut.Validate())
|
||||||
}
|
}
|
||||||
sut = Sut{valid: false}
|
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())
|
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) {
|
func Test_ValidateNotEmpty_ForString(t *testing.T) {
|
||||||
|
|
Loading…
Reference in New Issue