add ToString() helper (#2100)
This commit is contained in:
parent
b1f2063a9a
commit
94c7efdb5b
2 changed files with 46 additions and 0 deletions
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue