github.com/graywolf-at-work-2/terraform-vendor@v1.4.5/internal/lang/funcs/string_test.go (about)

     1  package funcs
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/zclconf/go-cty/cty"
     8  )
     9  
    10  func TestReplace(t *testing.T) {
    11  	tests := []struct {
    12  		String  cty.Value
    13  		Substr  cty.Value
    14  		Replace cty.Value
    15  		Want    cty.Value
    16  		Err     bool
    17  	}{
    18  		{ // Regular search and replace
    19  			cty.StringVal("hello"),
    20  			cty.StringVal("hel"),
    21  			cty.StringVal("bel"),
    22  			cty.StringVal("bello"),
    23  			false,
    24  		},
    25  		{ // Search string doesn't match
    26  			cty.StringVal("hello"),
    27  			cty.StringVal("nope"),
    28  			cty.StringVal("bel"),
    29  			cty.StringVal("hello"),
    30  			false,
    31  		},
    32  		{ // Regular expression
    33  			cty.StringVal("hello"),
    34  			cty.StringVal("/l/"),
    35  			cty.StringVal("L"),
    36  			cty.StringVal("heLLo"),
    37  			false,
    38  		},
    39  		{
    40  			cty.StringVal("helo"),
    41  			cty.StringVal("/(l)/"),
    42  			cty.StringVal("$1$1"),
    43  			cty.StringVal("hello"),
    44  			false,
    45  		},
    46  		{ // Bad regexp
    47  			cty.StringVal("hello"),
    48  			cty.StringVal("/(l/"),
    49  			cty.StringVal("$1$1"),
    50  			cty.UnknownVal(cty.String),
    51  			true,
    52  		},
    53  	}
    54  
    55  	for _, test := range tests {
    56  		t.Run(fmt.Sprintf("replace(%#v, %#v, %#v)", test.String, test.Substr, test.Replace), func(t *testing.T) {
    57  			got, err := Replace(test.String, test.Substr, test.Replace)
    58  
    59  			if test.Err {
    60  				if err == nil {
    61  					t.Fatal("succeeded; want error")
    62  				}
    63  				return
    64  			} else if err != nil {
    65  				t.Fatalf("unexpected error: %s", err)
    66  			}
    67  
    68  			if !got.RawEquals(test.Want) {
    69  				t.Errorf("wrong result\ngot:  %#v\nwant: %#v", got, test.Want)
    70  			}
    71  		})
    72  	}
    73  }