github.com/emc-cmd/terraform@v0.7.8-0.20161101145618-f16309630e7c/helper/validation/validation_test.go (about) 1 package validation 2 3 import ( 4 "regexp" 5 "testing" 6 7 "github.com/hashicorp/terraform/helper/schema" 8 ) 9 10 type testCase struct { 11 val interface{} 12 f schema.SchemaValidateFunc 13 expectedErr *regexp.Regexp 14 } 15 16 func TestValidationIntBetween(t *testing.T) { 17 runTestCases(t, []testCase{ 18 { 19 val: 1, 20 f: IntBetween(1, 1), 21 }, 22 { 23 val: 1, 24 f: IntBetween(0, 2), 25 }, 26 { 27 val: 1, 28 f: IntBetween(2, 3), 29 expectedErr: regexp.MustCompile("expected [\\w]+ to be in the range \\(2 - 3\\), got 1"), 30 }, 31 { 32 val: "1", 33 f: IntBetween(2, 3), 34 expectedErr: regexp.MustCompile("expected type of [\\w]+ to be int"), 35 }, 36 }) 37 } 38 39 func TestValidationSringInSlice(t *testing.T) { 40 runTestCases(t, []testCase{ 41 { 42 val: "ValidValue", 43 f: StringInSlice([]string{"ValidValue", "AnotherValidValue"}, false), 44 }, 45 // ignore case 46 { 47 val: "VALIDVALUE", 48 f: StringInSlice([]string{"ValidValue", "AnotherValidValue"}, true), 49 }, 50 { 51 val: "VALIDVALUE", 52 f: StringInSlice([]string{"ValidValue", "AnotherValidValue"}, false), 53 expectedErr: regexp.MustCompile("expected [\\w]+ to be one of \\[ValidValue AnotherValidValue\\], got VALIDVALUE"), 54 }, 55 { 56 val: "InvalidValue", 57 f: StringInSlice([]string{"ValidValue", "AnotherValidValue"}, false), 58 expectedErr: regexp.MustCompile("expected [\\w]+ to be one of \\[ValidValue AnotherValidValue\\], got InvalidValue"), 59 }, 60 { 61 val: 1, 62 f: StringInSlice([]string{"ValidValue", "AnotherValidValue"}, false), 63 expectedErr: regexp.MustCompile("expected type of [\\w]+ to be string"), 64 }, 65 }) 66 } 67 68 func runTestCases(t *testing.T, cases []testCase) { 69 matchErr := func(errs []error, r *regexp.Regexp) bool { 70 // err must match one provided 71 for _, err := range errs { 72 if r.MatchString(err.Error()) { 73 return true 74 } 75 } 76 77 return false 78 } 79 80 for i, tc := range cases { 81 _, errs := tc.f(tc.val, "test_property") 82 83 if len(errs) == 0 && tc.expectedErr == nil { 84 continue 85 } 86 87 if !matchErr(errs, tc.expectedErr) { 88 t.Fatalf("expected test case %d to produce error matching \"%s\", got %v", i, tc.expectedErr, errs) 89 } 90 } 91 }