Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added FloatBetween validation function. #18614

Merged
merged 1 commit into from
May 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
}