add ToString() helper (#2100)

This commit is contained in:
blotus 2023-03-16 15:20:31 +01:00 committed by GitHub
parent b1f2063a9a
commit 94c7efdb5b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 0 deletions

View file

@ -121,6 +121,7 @@ func GetExprEnv(ctx map[string]interface{}) map[string]interface{} {
"TrimPrefix": strings.TrimPrefix,
"TrimSuffix": strings.TrimSuffix,
"Get": Get,
"String": ToString,
"Distance": Distance,
}
for k, v := range ctx {
@ -484,3 +485,11 @@ func ParseUnix(value string) string {
}
return t.Format(time.RFC3339)
}
func ToString(value interface{}) string {
s, ok := value.(string)
if !ok {
return ""
}
return s
}

View file

@ -1131,3 +1131,40 @@ func TestIsIp(t *testing.T) {
})
}
}
func TestToString(t *testing.T) {
tests := []struct {
name string
value interface{}
expected string
}{
{
name: "ToString() test: valid string",
value: "foo",
expected: "foo",
},
{
name: "ToString() test: valid string",
value: interface{}("foo"),
expected: "foo",
},
{
name: "ToString() test: invalid type",
value: 1,
expected: "",
},
{
name: "ToString() test: invalid type 2",
value: interface{}(nil),
expected: "",
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
output := ToString(tc.value)
require.Equal(t, tc.expected, output)
})
}
}