Merge pull request #19122 from hashicorp/f-helper-validation-Any

helper/validation: Add Any() SchemaValidateFunc
This commit is contained in:
Brian Flad 2018-10-19 15:11:33 -04:00 committed by GitHub
commit 62bf23850b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 0 deletions

View File

@ -28,6 +28,24 @@ func All(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc {
} }
} }
// Any returns a SchemaValidateFunc which tests if the provided value
// passes any of the provided SchemaValidateFunc
func Any(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc {
return func(i interface{}, k string) ([]string, []error) {
var allErrors []error
var allWarnings []string
for _, validator := range validators {
validatorWarnings, validatorErrors := validator(i, k)
if len(validatorWarnings) == 0 && len(validatorErrors) == 0 {
return []string{}, []error{}
}
allWarnings = append(allWarnings, validatorWarnings...)
allErrors = append(allErrors, validatorErrors...)
}
return allWarnings, allErrors
}
}
// IntBetween returns a SchemaValidateFunc which tests if the provided value // IntBetween returns a SchemaValidateFunc which tests if the provided value
// is of type int and is between min and max (inclusive) // is of type int and is between min and max (inclusive)
func IntBetween(min, max int) schema.SchemaValidateFunc { func IntBetween(min, max int) schema.SchemaValidateFunc {

View File

@ -41,6 +41,41 @@ func TestValidationAll(t *testing.T) {
}) })
} }
func TestValidationAny(t *testing.T) {
runTestCases(t, []testCase{
{
val: 43,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
},
{
val: 4,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
},
{
val: 7,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
expectedErr: regexp.MustCompile("expected [\\w]+ to be at least \\(42\\), got 7"),
},
{
val: 7,
f: Any(
IntAtLeast(42),
IntAtMost(5),
),
expectedErr: regexp.MustCompile("expected [\\w]+ to be at most \\(5\\), got 7"),
},
})
}
func TestValidationIntBetween(t *testing.T) { func TestValidationIntBetween(t *testing.T) {
runTestCases(t, []testCase{ runTestCases(t, []testCase{
{ {