|
| 1 | +package float64validator_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/hashicorp/terraform-plugin-framework-validators/float64validator" |
| 8 | + "github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag" |
| 9 | + "github.com/hashicorp/terraform-plugin-framework/attr" |
| 10 | + "github.com/hashicorp/terraform-plugin-framework/tfsdk" |
| 11 | + "github.com/hashicorp/terraform-plugin-framework/types" |
| 12 | +) |
| 13 | + |
| 14 | +func TestNoneOfValidator(t *testing.T) { |
| 15 | + t.Parallel() |
| 16 | + |
| 17 | + type testCase struct { |
| 18 | + in attr.Value |
| 19 | + validator tfsdk.AttributeValidator |
| 20 | + expErrors int |
| 21 | + } |
| 22 | + |
| 23 | + testCases := map[string]testCase{ |
| 24 | + "simple-match": { |
| 25 | + in: types.Float64{Value: 123.456}, |
| 26 | + validator: float64validator.NoneOf( |
| 27 | + 123.456, |
| 28 | + 234.567, |
| 29 | + 8910.11, |
| 30 | + 1213.1415, |
| 31 | + ), |
| 32 | + expErrors: 1, |
| 33 | + }, |
| 34 | + "simple-mismatch": { |
| 35 | + in: types.Float64{Value: 123.456}, |
| 36 | + validator: float64validator.NoneOf( |
| 37 | + 234.567, |
| 38 | + 8910.11, |
| 39 | + 1213.1415, |
| 40 | + ), |
| 41 | + expErrors: 0, |
| 42 | + }, |
| 43 | + "skip-validation-on-null": { |
| 44 | + in: types.Float64{Null: true}, |
| 45 | + validator: float64validator.NoneOf( |
| 46 | + 234.567, |
| 47 | + 8910.11, |
| 48 | + 1213.1415, |
| 49 | + ), |
| 50 | + expErrors: 0, |
| 51 | + }, |
| 52 | + "skip-validation-on-unknown": { |
| 53 | + in: types.Float64{Unknown: true}, |
| 54 | + validator: float64validator.NoneOf( |
| 55 | + 234.567, |
| 56 | + 8910.11, |
| 57 | + 1213.1415, |
| 58 | + ), |
| 59 | + expErrors: 0, |
| 60 | + }, |
| 61 | + } |
| 62 | + |
| 63 | + for name, test := range testCases { |
| 64 | + name, test := name, test |
| 65 | + t.Run(name, func(t *testing.T) { |
| 66 | + req := tfsdk.ValidateAttributeRequest{ |
| 67 | + AttributeConfig: test.in, |
| 68 | + } |
| 69 | + res := tfsdk.ValidateAttributeResponse{} |
| 70 | + test.validator.Validate(context.TODO(), req, &res) |
| 71 | + |
| 72 | + if test.expErrors > 0 && !res.Diagnostics.HasError() { |
| 73 | + t.Fatalf("expected %d error(s), got none", test.expErrors) |
| 74 | + } |
| 75 | + |
| 76 | + if test.expErrors > 0 && test.expErrors != validatordiag.ErrorsCount(res.Diagnostics) { |
| 77 | + t.Fatalf("expected %d error(s), got %d: %v", test.expErrors, validatordiag.ErrorsCount(res.Diagnostics), res.Diagnostics) |
| 78 | + } |
| 79 | + |
| 80 | + if test.expErrors == 0 && res.Diagnostics.HasError() { |
| 81 | + t.Fatalf("expected no error(s), got %d: %v", validatordiag.ErrorsCount(res.Diagnostics), res.Diagnostics) |
| 82 | + } |
| 83 | + }) |
| 84 | + } |
| 85 | +} |
0 commit comments