diff --git a/.changelog/37.txt b/.changelog/37.txt new file mode 100644 index 00000000..45554f5f --- /dev/null +++ b/.changelog/37.txt @@ -0,0 +1,3 @@ +```release-note:feature +Introduced `listvalidator` package with `ValuesAre()` validation functions +``` \ No newline at end of file diff --git a/.changelog/41.txt b/.changelog/41.txt new file mode 100644 index 00000000..b53f5164 --- /dev/null +++ b/.changelog/41.txt @@ -0,0 +1,3 @@ +```release-note:feature +Added `SizeAtLeast()`, `SizeAtMost()` and `SizeBetween` validation functions to `listvalidator` package +``` \ No newline at end of file diff --git a/listvalidator/doc.go b/listvalidator/doc.go new file mode 100644 index 00000000..48476987 --- /dev/null +++ b/listvalidator/doc.go @@ -0,0 +1,2 @@ +// Package listvalidator provides validators for types.List attributes. +package listvalidator diff --git a/listvalidator/size_at_least.go b/listvalidator/size_at_least.go new file mode 100644 index 00000000..372a3785 --- /dev/null +++ b/listvalidator/size_at_least.go @@ -0,0 +1,58 @@ +package listvalidator + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + + "github.com/hashicorp/terraform-plugin-framework-validators/validatordiag" +) + +var _ tfsdk.AttributeValidator = sizeAtLeastValidator{} + +// sizeAtLeastValidator validates that list contains at least min elements. +type sizeAtLeastValidator struct { + min int +} + +// Description describes the validation in plain text formatting. +func (v sizeAtLeastValidator) Description(ctx context.Context) string { + return fmt.Sprintf("list must contain at least %d elements", v.min) +} + +// MarkdownDescription describes the validation in Markdown formatting. +func (v sizeAtLeastValidator) MarkdownDescription(ctx context.Context) string { + return v.Description(ctx) +} + +// Validate performs the validation. +func (v sizeAtLeastValidator) Validate(ctx context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) { + elems, ok := validateList(ctx, req, resp) + if !ok { + return + } + + if len(elems) < v.min { + resp.Diagnostics.Append(validatordiag.AttributeValueDiagnostic( + req.AttributePath, + v.Description(ctx), + fmt.Sprintf("%d", len(elems)), + )) + + return + } +} + +// SizeAtLeast returns an AttributeValidator which ensures that any configured +// attribute value: +// +// - Is a List. +// - Contains at least min elements. +// +// Null (unconfigured) and unknown (known after apply) values are skipped. +func SizeAtLeast(min int) tfsdk.AttributeValidator { + return sizeAtLeastValidator{ + min: min, + } +} diff --git a/listvalidator/size_at_least_test.go b/listvalidator/size_at_least_test.go new file mode 100644 index 00000000..c9d4cf01 --- /dev/null +++ b/listvalidator/size_at_least_test.go @@ -0,0 +1,90 @@ +package listvalidator + +import ( + "context" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-go/tftypes" +) + +func TestSizeAtLeastValidator(t *testing.T) { + t.Parallel() + + type testCase struct { + val attr.Value + min int + expectError bool + } + tests := map[string]testCase{ + "not a List": { + val: types.Bool{Value: true}, + expectError: true, + }, + "List unknown": { + val: types.List{ + Unknown: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List null": { + val: types.List{ + Null: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List size greater than min": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + min: 1, + expectError: false, + }, + "List size equal to min": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + }, + }, + min: 1, + expectError: false, + }, + "List size less than min": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{}, + }, + min: 1, + expectError: true, + }, + } + + for name, test := range tests { + name, test := name, test + t.Run(name, func(t *testing.T) { + request := tfsdk.ValidateAttributeRequest{ + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + AttributeConfig: test.val, + } + response := tfsdk.ValidateAttributeResponse{} + SizeAtLeast(test.min).Validate(context.TODO(), request, &response) + + if !response.Diagnostics.HasError() && test.expectError { + t.Fatal("expected error, got no error") + } + + if response.Diagnostics.HasError() && !test.expectError { + t.Fatalf("got unexpected error: %s", response.Diagnostics) + } + }) + } +} diff --git a/listvalidator/size_at_most.go b/listvalidator/size_at_most.go new file mode 100644 index 00000000..42bbc8be --- /dev/null +++ b/listvalidator/size_at_most.go @@ -0,0 +1,58 @@ +package listvalidator + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + + "github.com/hashicorp/terraform-plugin-framework-validators/validatordiag" +) + +var _ tfsdk.AttributeValidator = sizeAtMostValidator{} + +// sizeAtMostValidator validates that list contains at most max elements. +type sizeAtMostValidator struct { + max int +} + +// Description describes the validation in plain text formatting. +func (v sizeAtMostValidator) Description(ctx context.Context) string { + return fmt.Sprintf("list must contain at most %d elements", v.max) +} + +// MarkdownDescription describes the validation in Markdown formatting. +func (v sizeAtMostValidator) MarkdownDescription(ctx context.Context) string { + return v.Description(ctx) +} + +// Validate performs the validation. +func (v sizeAtMostValidator) Validate(ctx context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) { + elems, ok := validateList(ctx, req, resp) + if !ok { + return + } + + if len(elems) > v.max { + resp.Diagnostics.Append(validatordiag.AttributeValueDiagnostic( + req.AttributePath, + v.Description(ctx), + fmt.Sprintf("%d", len(elems)), + )) + + return + } +} + +// SizeAtMost returns an AttributeValidator which ensures that any configured +// attribute value: +// +// - Is a List. +// - Contains at most max elements. +// +// Null (unconfigured) and unknown (known after apply) values are skipped. +func SizeAtMost(max int) tfsdk.AttributeValidator { + return sizeAtMostValidator{ + max: max, + } +} diff --git a/listvalidator/size_at_most_test.go b/listvalidator/size_at_most_test.go new file mode 100644 index 00000000..62cc40d7 --- /dev/null +++ b/listvalidator/size_at_most_test.go @@ -0,0 +1,93 @@ +package listvalidator + +import ( + "context" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-go/tftypes" +) + +func TestSizeAtMostValidator(t *testing.T) { + t.Parallel() + + type testCase struct { + val attr.Value + max int + expectError bool + } + tests := map[string]testCase{ + "not a List": { + val: types.Bool{Value: true}, + expectError: true, + }, + "List unknown": { + val: types.List{ + Unknown: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List null": { + val: types.List{ + Null: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List size less than max": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + }, + }, + max: 2, + expectError: false, + }, + "List size equal to max": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + max: 2, + expectError: false, + }, + "List size greater than max": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + types.String{Value: "third"}, + }}, + max: 2, + expectError: true, + }, + } + + for name, test := range tests { + name, test := name, test + t.Run(name, func(t *testing.T) { + request := tfsdk.ValidateAttributeRequest{ + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + AttributeConfig: test.val, + } + response := tfsdk.ValidateAttributeResponse{} + SizeAtMost(test.max).Validate(context.TODO(), request, &response) + + if !response.Diagnostics.HasError() && test.expectError { + t.Fatal("expected error, got no error") + } + + if response.Diagnostics.HasError() && !test.expectError { + t.Fatalf("got unexpected error: %s", response.Diagnostics) + } + }) + } +} diff --git a/listvalidator/size_between.go b/listvalidator/size_between.go new file mode 100644 index 00000000..3e3ded12 --- /dev/null +++ b/listvalidator/size_between.go @@ -0,0 +1,61 @@ +package listvalidator + +import ( + "context" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + + "github.com/hashicorp/terraform-plugin-framework-validators/validatordiag" +) + +var _ tfsdk.AttributeValidator = sizeBetweenValidator{} + +// sizeBetweenValidator validates that list contains at least min elements +// and at most max elements. +type sizeBetweenValidator struct { + min int + max int +} + +// Description describes the validation in plain text formatting. +func (v sizeBetweenValidator) Description(ctx context.Context) string { + return fmt.Sprintf("list must contain at least %d elements and at most %d elements", v.min, v.max) +} + +// MarkdownDescription describes the validation in Markdown formatting. +func (v sizeBetweenValidator) MarkdownDescription(ctx context.Context) string { + return v.Description(ctx) +} + +// Validate performs the validation. +func (v sizeBetweenValidator) Validate(ctx context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) { + elems, ok := validateList(ctx, req, resp) + if !ok { + return + } + + if len(elems) < v.min || len(elems) > v.max { + resp.Diagnostics.Append(validatordiag.AttributeValueDiagnostic( + req.AttributePath, + v.Description(ctx), + fmt.Sprintf("%d", len(elems)), + )) + + return + } +} + +// SizeBetween returns an AttributeValidator which ensures that any configured +// attribute value: +// +// - Is a List. +// - Contains at least min elements and at most max elements. +// +// Null (unconfigured) and unknown (known after apply) values are skipped. +func SizeBetween(min, max int) tfsdk.AttributeValidator { + return sizeBetweenValidator{ + min: min, + max: max, + } +} diff --git a/listvalidator/size_between_test.go b/listvalidator/size_between_test.go new file mode 100644 index 00000000..9aa29dc7 --- /dev/null +++ b/listvalidator/size_between_test.go @@ -0,0 +1,133 @@ +package listvalidator + +import ( + "context" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-go/tftypes" +) + +func TestSizeBetweenValidator(t *testing.T) { + t.Parallel() + + type testCase struct { + val attr.Value + min int + max int + expectError bool + } + tests := map[string]testCase{ + "not a List": { + val: types.Bool{Value: true}, + expectError: true, + }, + "List unknown": { + val: types.List{ + Unknown: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List null": { + val: types.List{ + Null: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List size greater than min": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + min: 1, + max: 3, + expectError: false, + }, + "List size equal to min": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + }, + }, + min: 1, + max: 3, + expectError: false, + }, + "List size less than max": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + min: 1, + max: 3, + expectError: false, + }, + "List size equal to max": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + types.String{Value: "third"}, + }, + }, + min: 1, + max: 3, + expectError: false, + }, + "List size less than min": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{}, + }, + min: 1, + max: 3, + expectError: true, + }, + "List size greater than max": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + types.String{Value: "third"}, + types.String{Value: "fourth"}, + }, + }, + min: 1, + max: 3, + expectError: true, + }, + } + + for name, test := range tests { + name, test := name, test + t.Run(name, func(t *testing.T) { + request := tfsdk.ValidateAttributeRequest{ + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + AttributeConfig: test.val, + } + response := tfsdk.ValidateAttributeResponse{} + SizeBetween(test.min, test.max).Validate(context.TODO(), request, &response) + + if !response.Diagnostics.HasError() && test.expectError { + t.Fatal("expected error, got no error") + } + + if response.Diagnostics.HasError() && !test.expectError { + t.Fatalf("got unexpected error: %s", response.Diagnostics) + } + }) + } +} diff --git a/listvalidator/type_validation.go b/listvalidator/type_validation.go new file mode 100644 index 00000000..4ebeae23 --- /dev/null +++ b/listvalidator/type_validation.go @@ -0,0 +1,28 @@ +package listvalidator + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" +) + +// validateList ensures that the request contains a List value. +func validateList(ctx context.Context, request tfsdk.ValidateAttributeRequest, response *tfsdk.ValidateAttributeResponse) ([]attr.Value, bool) { + var l types.List + + diags := tfsdk.ValueAs(ctx, request.AttributeConfig, &l) + + if diags.HasError() { + response.Diagnostics = append(response.Diagnostics, diags...) + + return nil, false + } + + if l.Unknown || l.Null { + return nil, false + } + + return l.Elems, true +} diff --git a/listvalidator/type_validation_test.go b/listvalidator/type_validation_test.go new file mode 100644 index 00000000..fe082dd8 --- /dev/null +++ b/listvalidator/type_validation_test.go @@ -0,0 +1,82 @@ +package listvalidator + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-go/tftypes" +) + +func TestValidateList(t *testing.T) { + t.Parallel() + + testCases := map[string]struct { + request tfsdk.ValidateAttributeRequest + expectedListElems []attr.Value + expectedOk bool + }{ + "invalid-type": { + request: tfsdk.ValidateAttributeRequest{ + AttributeConfig: types.Bool{Value: true}, + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + }, + expectedListElems: nil, + expectedOk: false, + }, + "list-null": { + request: tfsdk.ValidateAttributeRequest{ + AttributeConfig: types.List{Null: true}, + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + }, + expectedListElems: nil, + expectedOk: false, + }, + "list-unknown": { + request: tfsdk.ValidateAttributeRequest{ + AttributeConfig: types.List{Unknown: true}, + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + }, + expectedListElems: nil, + expectedOk: false, + }, + "list-value": { + request: tfsdk.ValidateAttributeRequest{ + AttributeConfig: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + }, + expectedListElems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + expectedOk: true, + }, + } + + for name, testCase := range testCases { + name, testCase := name, testCase + + t.Run(name, func(t *testing.T) { + t.Parallel() + + gotListElems, gotOk := validateList(context.Background(), testCase.request, &tfsdk.ValidateAttributeResponse{}) + + if diff := cmp.Diff(gotListElems, testCase.expectedListElems); diff != "" { + t.Errorf("unexpected float64 difference: %s", diff) + } + + if diff := cmp.Diff(gotOk, testCase.expectedOk); diff != "" { + t.Errorf("unexpected ok difference: %s", diff) + } + }) + } +} diff --git a/listvalidator/values_are.go b/listvalidator/values_are.go new file mode 100644 index 00000000..ac8e06bd --- /dev/null +++ b/listvalidator/values_are.go @@ -0,0 +1,64 @@ +package listvalidator + +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-framework/tfsdk" +) + +var _ tfsdk.AttributeValidator = valuesAreValidator{} + +// valuesAreValidator validates that each list member validates against each of the value validators. +type valuesAreValidator struct { + valueValidators []tfsdk.AttributeValidator +} + +// Description describes the validation in plain text formatting. +func (v valuesAreValidator) Description(ctx context.Context) string { + var descriptions []string + for _, validator := range v.valueValidators { + descriptions = append(descriptions, validator.Description(ctx)) + } + + return fmt.Sprintf("value must satisfy all validations: %s", strings.Join(descriptions, " + ")) +} + +// MarkdownDescription describes the validation in Markdown formatting. +func (v valuesAreValidator) MarkdownDescription(ctx context.Context) string { + return v.Description(ctx) +} + +// Validate performs the validation. +func (v valuesAreValidator) Validate(ctx context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) { + elems, ok := validateList(ctx, req, resp) + if !ok { + return + } + + for k, elem := range elems { + request := tfsdk.ValidateAttributeRequest{ + AttributePath: req.AttributePath.WithElementKeyInt(k), + AttributeConfig: elem, + Config: req.Config, + } + + for _, validator := range v.valueValidators { + validator.Validate(ctx, request, resp) + } + } +} + +// ValuesAre returns an AttributeValidator which ensures that any configured +// attribute value: +// +// - Is a List. +// - That contains list elements, each of which validate against each value validator. +// +// Null (unconfigured) and unknown (known after apply) values are skipped. +func ValuesAre(valueValidators ...tfsdk.AttributeValidator) tfsdk.AttributeValidator { + return valuesAreValidator{ + valueValidators: valueValidators, + } +} diff --git a/listvalidator/values_are_test.go b/listvalidator/values_are_test.go new file mode 100644 index 00000000..b5732fa8 --- /dev/null +++ b/listvalidator/values_are_test.go @@ -0,0 +1,119 @@ +package listvalidator + +import ( + "context" + "testing" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-go/tftypes" + + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" +) + +func TestValuesAreValidator(t *testing.T) { + t.Parallel() + + type testCase struct { + val attr.Value + valuesAreValidators []tfsdk.AttributeValidator + expectError bool + } + tests := map[string]testCase{ + "not List": { + val: types.Set{ + ElemType: types.StringType, + }, + expectError: true, + }, + "List unknown": { + val: types.List{ + Unknown: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List null": { + val: types.List{ + Null: true, + ElemType: types.StringType, + }, + expectError: false, + }, + "List elems invalid": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + valuesAreValidators: []tfsdk.AttributeValidator{ + stringvalidator.LengthAtLeast(6), + }, + expectError: true, + }, + "List elems invalid for second validator": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + valuesAreValidators: []tfsdk.AttributeValidator{ + stringvalidator.LengthAtLeast(2), + stringvalidator.LengthAtLeast(6), + }, + expectError: true, + }, + "List elems wrong type for validator": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + valuesAreValidators: []tfsdk.AttributeValidator{ + int64validator.AtLeast(6), + }, + expectError: true, + }, + "List elems valid": { + val: types.List{ + ElemType: types.StringType, + Elems: []attr.Value{ + types.String{Value: "first"}, + types.String{Value: "second"}, + }, + }, + valuesAreValidators: []tfsdk.AttributeValidator{ + stringvalidator.LengthAtLeast(5), + }, + expectError: false, + }, + } + + for name, test := range tests { + name, test := name, test + t.Run(name, func(t *testing.T) { + request := tfsdk.ValidateAttributeRequest{ + AttributePath: tftypes.NewAttributePath().WithAttributeName("test"), + AttributeConfig: test.val, + } + response := tfsdk.ValidateAttributeResponse{} + ValuesAre(test.valuesAreValidators...).Validate(context.TODO(), request, &response) + + if !response.Diagnostics.HasError() && test.expectError { + t.Fatal("expected error, got no error") + } + + if response.Diagnostics.HasError() && !test.expectError { + t.Fatalf("got unexpected error: %s", response.Diagnostics) + } + }) + } +}