Skip to content

Commit

Permalink
Added IntAtLeast and IntAtMost validation functions. (#15403)
Browse files Browse the repository at this point in the history
  • Loading branch information
rileykarson authored and stack72 committed Jun 27, 2017
1 parent 4e175cc commit 8cf04f8
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
38 changes: 38 additions & 0 deletions helper/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,44 @@ func IntBetween(min, max int) schema.SchemaValidateFunc {
}
}

// IntAtLeast returns a SchemaValidateFunc which tests if the provided value
// is of type int and is at least min (inclusive)
func IntAtLeast(min int) schema.SchemaValidateFunc {
return func(i interface{}, k string) (s []string, es []error) {
v, ok := i.(int)
if !ok {
es = append(es, fmt.Errorf("expected type of %s to be int", k))
return
}

if v < min {
es = append(es, fmt.Errorf("expected %s to be at least (%d), got %d", k, min, v))
return
}

return
}
}

// IntAtMost returns a SchemaValidateFunc which tests if the provided value
// is of type int and is at most max (inclusive)
func IntAtMost(max int) schema.SchemaValidateFunc {
return func(i interface{}, k string) (s []string, es []error) {
v, ok := i.(int)
if !ok {
es = append(es, fmt.Errorf("expected type of %s to be int", k))
return
}

if v > max {
es = append(es, fmt.Errorf("expected %s to be at most (%d), got %d", k, max, v))
return
}

return
}
}

// StringInSlice returns a SchemaValidateFunc which tests if the provided value
// is of type string and matches the value of an element in the valid slice
// will test with in lower case if ignoreCase is true
Expand Down
46 changes: 46 additions & 0 deletions helper/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,52 @@ func TestValidationIntBetween(t *testing.T) {
})
}

func TestValidationIntAtLeast(t *testing.T) {
runTestCases(t, []testCase{
{
val: 1,
f: IntAtLeast(1),
},
{
val: 1,
f: IntAtLeast(0),
},
{
val: 1,
f: IntAtLeast(2),
expectedErr: regexp.MustCompile("expected [\\w]+ to be at least \\(2\\), got 1"),
},
{
val: "1",
f: IntAtLeast(2),
expectedErr: regexp.MustCompile("expected type of [\\w]+ to be int"),
},
})
}

func TestValidationIntAtMost(t *testing.T) {
runTestCases(t, []testCase{
{
val: 1,
f: IntAtMost(1),
},
{
val: 1,
f: IntAtMost(2),
},
{
val: 1,
f: IntAtMost(0),
expectedErr: regexp.MustCompile("expected [\\w]+ to be at most \\(0\\), got 1"),
},
{
val: "1",
f: IntAtMost(0),
expectedErr: regexp.MustCompile("expected type of [\\w]+ to be int"),
},
})
}

func TestValidationStringInSlice(t *testing.T) {
runTestCases(t, []testCase{
{
Expand Down

0 comments on commit 8cf04f8

Please sign in to comment.