github.com/hashicorp/packer@v1.14.3/hcl2template/function/starts_with_test.go (about)

     1  package function
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/zclconf/go-cty/cty"
     8  )
     9  
    10  func TestStartsWith(t *testing.T) {
    11  	tests := []struct {
    12  		String, Prefix cty.Value
    13  		Want           cty.Value
    14  	}{
    15  		{
    16  			cty.StringVal("hello world"),
    17  			cty.StringVal("hello"),
    18  			cty.True,
    19  		},
    20  		{
    21  			cty.StringVal("hey world"),
    22  			cty.StringVal("hello"),
    23  			cty.False,
    24  		},
    25  		{
    26  			cty.StringVal(""),
    27  			cty.StringVal(""),
    28  			cty.True,
    29  		},
    30  		{
    31  			cty.StringVal(""),
    32  			cty.StringVal(" "),
    33  			cty.False,
    34  		},
    35  		{
    36  			cty.StringVal("a"),
    37  			cty.StringVal(""),
    38  			cty.True,
    39  		},
    40  		{
    41  			cty.StringVal(""),
    42  			cty.StringVal("a"),
    43  			cty.False,
    44  		},
    45  
    46  		{
    47  			// Unicode combining characters edge-case: we match the prefix
    48  			// in terms of unicode code units rather than grapheme clusters,
    49  			// which is inconsistent with our string processing elsewhere but
    50  			// would be a breaking change to fix that bug now.
    51  			cty.StringVal("\U0001f937\u200d\u2642"), // "Man Shrugging" is encoded as "Person Shrugging" followed by zero-width joiner and then the masculine gender presentation modifier
    52  			cty.StringVal("\U0001f937"),             // Just the "Person Shrugging" character without any modifiers
    53  			cty.True,
    54  		},
    55  		{
    56  			cty.StringVal("hello world"),
    57  			cty.StringVal(" "),
    58  			cty.False,
    59  		},
    60  		{
    61  			cty.StringVal(" "),
    62  			cty.StringVal(""),
    63  			cty.True,
    64  		},
    65  		{
    66  			cty.StringVal(" "),
    67  			cty.StringVal("hello"),
    68  			cty.False,
    69  		},
    70  		{
    71  			cty.UnknownVal(cty.String),
    72  			cty.StringVal("a"),
    73  			cty.UnknownVal(cty.Bool).RefineNotNull(),
    74  		},
    75  		{
    76  			cty.UnknownVal(cty.String),
    77  			cty.StringVal(""),
    78  			cty.UnknownVal(cty.Bool).RefineNotNull(),
    79  		},
    80  	}
    81  
    82  	for _, test := range tests {
    83  		t.Run(fmt.Sprintf("StartsWith(%#v, %#v)", test.String, test.Prefix), func(t *testing.T) {
    84  			got, err := StartsWithFunc.Call([]cty.Value{test.String, test.Prefix})
    85  
    86  			if err != nil {
    87  				t.Fatalf("unexpected error: %s", err)
    88  			}
    89  
    90  			if !got.RawEquals(test.Want) {
    91  				t.Errorf(
    92  					"wrong result\nstring: %#v\nprefix: %#v\ngot:    %#v\nwant:   %#v",
    93  					test.String, test.Prefix, got, test.Want,
    94  				)
    95  			}
    96  		})
    97  	}
    98  }