Skip to content

Commit

Permalink
Added FloatBetween validation func
Browse files Browse the repository at this point in the history
Added lower bound inclusion test for FloatBetween
  • Loading branch information
craigdbarber committed Aug 6, 2018
1 parent c0793c8 commit 7df15ad
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
19 changes: 19 additions & 0 deletions helper/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,22 @@ func ValidateRFC3339TimeString(v interface{}, k string) (ws []string, errors []e
}
return
}

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

if v < min || v > max {
es = append(es, fmt.Errorf("expected %s to be in the range (%f - %f), got %f", k, min, max, v))
return
}

return
}
}
43 changes: 43 additions & 0 deletions helper/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,3 +373,46 @@ func runTestCases(t *testing.T, cases []testCase) {
}
}
}

func TestFloatBetween(t *testing.T) {
cases := map[string]struct {
Value interface{}
ValidateFunc schema.SchemaValidateFunc
ExpectValidationErrors bool
}{
"accept valid value": {
Value: 1.5,
ValidateFunc: FloatBetween(1.0, 2.0),
ExpectValidationErrors: false,
},
"accept valid value inclusive upper bound": {
Value: 1.0,
ValidateFunc: FloatBetween(0.0, 1.0),
ExpectValidationErrors: false,
},
"accept valid value inclusive lower bound": {
Value: 0.0,
ValidateFunc: FloatBetween(0.0, 1.0),
ExpectValidationErrors: false,
},
"reject out of range value": {
Value: -1.0,
ValidateFunc: FloatBetween(0.0, 1.0),
ExpectValidationErrors: true,
},
"reject incorrectly typed value": {
Value: 1,
ValidateFunc: FloatBetween(0.0, 1.0),
ExpectValidationErrors: true,
},
}

for tn, tc := range cases {
_, errors := tc.ValidateFunc(tc.Value, tn)
if len(errors) > 0 && !tc.ExpectValidationErrors {
t.Errorf("%s: unexpected errors %s", tn, errors)
} else if len(errors) == 0 && tc.ExpectValidationErrors {
t.Errorf("%s: expected errors but got none", tn)
}
}
}

0 comments on commit 7df15ad

Please sign in to comment.