Merge pull request #3367 from lavalamp/fix

improve validation error message printing
This commit is contained in:
Dawn Chen 2015-01-09 13:26:44 -08:00
commit a5c117f405
2 changed files with 36 additions and 6 deletions

View File

@ -20,6 +20,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/davecgh/go-spew/spew"
"github.com/golang/glog" "github.com/golang/glog"
) )
@ -51,8 +52,8 @@ const (
ValidationErrorTypeForbidden ValidationErrorType = "FieldValueForbidden" ValidationErrorTypeForbidden ValidationErrorType = "FieldValueForbidden"
) )
// ValueOf converts a ValidationErrorType into its corresponding error message. // String converts a ValidationErrorType into its corresponding error message.
func ValueOf(t ValidationErrorType) string { func (t ValidationErrorType) String() string {
switch t { switch t {
case ValidationErrorTypeNotFound: case ValidationErrorTypeNotFound:
return "not found" return "not found"
@ -83,7 +84,7 @@ type ValidationError struct {
var _ error = &ValidationError{} var _ error = &ValidationError{}
func (v *ValidationError) Error() string { func (v *ValidationError) Error() string {
s := fmt.Sprintf("%s: %s '%v'", v.Field, ValueOf(v.Type), v.BadValue) s := spew.Sprintf("%s: %s '%+v'", v.Field, v.Type, v.BadValue)
if v.Detail != "" { if v.Detail != "" {
s += fmt.Sprintf(": %s", v.Detail) s += fmt.Sprintf(": %s", v.Detail)
} }

View File

@ -56,10 +56,39 @@ func TestMakeFuncs(t *testing.T) {
} }
} }
func TestValidationError(t *testing.T) { func TestValidationErrorUsefulMessage(t *testing.T) {
s := NewFieldInvalid("foo", "bar", "deet").Error() s := NewFieldInvalid("foo", "bar", "deet").Error()
if !strings.Contains(s, "foo") || !strings.Contains(s, "bar") || !strings.Contains(s, "deet") || !strings.Contains(s, ValueOf(ValidationErrorTypeInvalid)) { t.Logf("message: %v", s)
t.Errorf("error message did not contain expected values, got %s", s) for _, part := range []string{"foo", "bar", "deet", ValidationErrorTypeInvalid.String()} {
if !strings.Contains(s, part) {
t.Errorf("error message did not contain expected part '%v'", part)
}
}
type complicated struct {
Baz int
Qux string
Inner interface{}
KV map[string]int
}
s = NewFieldRequired(
"foo",
&complicated{
Baz: 1,
Qux: "aoeu",
Inner: &complicated{Qux: "asdf"},
KV: map[string]int{"Billy": 2},
},
).Error()
t.Logf("message: %v", s)
for _, part := range []string{
"foo", ValidationErrorTypeRequired.String(),
"Baz", "Qux", "Inner", "KV",
"1", "aoeu", "asdf", "Billy", "2",
} {
if !strings.Contains(s, part) {
t.Errorf("error message did not contain expected part '%v'", part)
}
} }
} }