@@ -2,6 +2,8 @@ package utils
22
33import (
44 "encoding/json"
5+ "github.com/hashicorp/go-cty/cty"
6+ "github.com/hashicorp/terraform-plugin-sdk/v2/diag"
57 "log"
68 "reflect"
79 "strings"
@@ -474,3 +476,56 @@ func TestLinksValue(t *testing.T) {
474476 })
475477 }
476478}
479+
480+ func TestStrMaxLength (t * testing.T ) {
481+ tests := []struct {
482+ name string
483+ input interface {}
484+ max int
485+ expectError bool
486+ }{
487+ {
488+ name : "valid ascii under max" ,
489+ input : "hello world" ,
490+ max : 50 ,
491+ expectError : false ,
492+ },
493+ {
494+ name : "valid multibyte under max" ,
495+ input : "こんにちは世界" , // 7 runes
496+ max : 50 ,
497+ expectError : false ,
498+ },
499+ {
500+ name : "ascii over max" ,
501+ input : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,
502+ max : 50 , // 52 runes
503+ expectError : true ,
504+ },
505+ {
506+ name : "multibyte over max" ,
507+ input : "あいうえおかきくけこさしすせそたちつてと" , // 20 runes
508+ max : 10 ,
509+ expectError : true ,
510+ },
511+ }
512+
513+ for _ , tt := range tests {
514+ t .Run (tt .name , func (t * testing.T ) {
515+ validator := StrMaxLength (tt .max )
516+ path := cty.Path {cty.GetAttrStep {Name : "name" }}
517+ diags := validator (tt .input , path )
518+
519+ gotError := false
520+ for _ , d := range diags {
521+ if d .Severity == diag .Error {
522+ gotError = true
523+ break
524+ }
525+ }
526+ if gotError != tt .expectError {
527+ t .Errorf ("expected error: %v, got: %v, input: %#v" , tt .expectError , gotError , tt .input )
528+ }
529+ })
530+ }
531+ }
0 commit comments