Skip to content

Commit

Permalink
Add validate method to check non zero values
Browse files Browse the repository at this point in the history
  • Loading branch information
anuptalwalkar committed May 23, 2017
1 parent 4bf24e3 commit f22b09e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
13 changes: 13 additions & 0 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ var (
errReturnCount = errors.New("constructor function must one or two values")
errReturnKind = errors.New("constructor return type must be a pointer")
errArgKind = errors.New("constructor arguments must be pointers")
errZeroVal = errors.New("Object is a zero value")

_typeOfError = reflect.TypeOf((*error)(nil)).Elem()

Expand Down Expand Up @@ -157,3 +158,15 @@ func (c *Container) Resolve(objs ...interface{}) (err error) {
}
return nil
}

// Validate accepts objects to be validated from constructor and returns an error
// if any of the provided object is a zero value object
func Validate(values ...interface{}) error {
for _, val := range values {
v := reflect.ValueOf(val)
if v == reflect.Zero(v.Type()) {
return errors.Wrapf(errZeroVal, "%v", v.Type())
}
}
return nil
}
26 changes: 26 additions & 0 deletions container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -564,3 +564,29 @@ func TestMultiObjectRegisterResolve(t *testing.T) {
require.NotNil(t, second, "Child2 must have been registered")
require.NotNil(t, third, "Child3 must have been registered")
}

func Test_ZeroValueObjectValidationSuccess(t *testing.T) {
t.Parallel()
c := New()

c.Provide(&Parent1{})
err := c.Invoke(func(p1 *Parent1) {
er := Validate(p1)
require.NoError(t, er)
})
require.Nil(t, err)
}

func Test_ZeroValueObjectValidationError(t *testing.T) {
t.Parallel()
c := New()

var zeroP12 *Parent12
err := c.Invoke(func(p12 *Parent12) {
er := Validate(p12)
require.Error(t, er)
require.Contains(t, er.Error(), errZeroVal.Error())
zeroP12 = p12
})
require.Nil(t, err)
}

0 comments on commit f22b09e

Please sign in to comment.