|
| 1 | +package stringvalidator_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/hashicorp/terraform-plugin-framework/path" |
| 8 | + "github.com/hashicorp/terraform-plugin-framework/schema/validator" |
| 9 | + "github.com/hashicorp/terraform-plugin-framework/types" |
| 10 | + |
| 11 | + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" |
| 12 | +) |
| 13 | + |
| 14 | +func TestUTF8LengthAtLeastValidator(t *testing.T) { |
| 15 | + t.Parallel() |
| 16 | + |
| 17 | + type testCase struct { |
| 18 | + val types.String |
| 19 | + minLength int |
| 20 | + expectError bool |
| 21 | + } |
| 22 | + tests := map[string]testCase{ |
| 23 | + "unknown": { |
| 24 | + val: types.StringUnknown(), |
| 25 | + minLength: 1, |
| 26 | + }, |
| 27 | + "null": { |
| 28 | + val: types.StringNull(), |
| 29 | + minLength: 1, |
| 30 | + }, |
| 31 | + "valid single byte characters": { |
| 32 | + val: types.StringValue("ok"), |
| 33 | + minLength: 1, |
| 34 | + }, |
| 35 | + "valid mixed byte characters": { |
| 36 | + // Rightwards Arrow Over Leftwards Arrow (U+21C4; 3 bytes) |
| 37 | + val: types.StringValue("test⇄test"), |
| 38 | + minLength: 9, |
| 39 | + }, |
| 40 | + "valid multiple byte characters": { |
| 41 | + // Rightwards Arrow Over Leftwards Arrow (U+21C4; 3 bytes) |
| 42 | + val: types.StringValue("⇄"), |
| 43 | + minLength: 1, |
| 44 | + }, |
| 45 | + "invalid single byte characters": { |
| 46 | + val: types.StringValue("ok"), |
| 47 | + minLength: 3, |
| 48 | + expectError: true, |
| 49 | + }, |
| 50 | + "invalid mixed byte characters": { |
| 51 | + // Rightwards Arrow Over Leftwards Arrow (U+21C4; 3 bytes) |
| 52 | + val: types.StringValue("test⇄test"), |
| 53 | + minLength: 10, |
| 54 | + expectError: true, |
| 55 | + }, |
| 56 | + "invalid multiple byte characters": { |
| 57 | + // Rightwards Arrow Over Leftwards Arrow (U+21C4; 3 bytes) |
| 58 | + val: types.StringValue("⇄"), |
| 59 | + minLength: 2, |
| 60 | + expectError: true, |
| 61 | + }, |
| 62 | + } |
| 63 | + |
| 64 | + for name, test := range tests { |
| 65 | + name, test := name, test |
| 66 | + t.Run(name, func(t *testing.T) { |
| 67 | + request := validator.StringRequest{ |
| 68 | + Path: path.Root("test"), |
| 69 | + PathExpression: path.MatchRoot("test"), |
| 70 | + ConfigValue: test.val, |
| 71 | + } |
| 72 | + response := validator.StringResponse{} |
| 73 | + stringvalidator.UTF8LengthAtLeast(test.minLength).ValidateString(context.Background(), request, &response) |
| 74 | + |
| 75 | + if !response.Diagnostics.HasError() && test.expectError { |
| 76 | + t.Fatal("expected error, got no error") |
| 77 | + } |
| 78 | + |
| 79 | + if response.Diagnostics.HasError() && !test.expectError { |
| 80 | + t.Fatalf("got unexpected error: %s", response.Diagnostics) |
| 81 | + } |
| 82 | + }) |
| 83 | + } |
| 84 | +} |
0 commit comments