From 94c7efdb5bd8c31a760fcf476801c4dd888d6ea1 Mon Sep 17 00:00:00 2001 From: blotus Date: Thu, 16 Mar 2023 15:20:31 +0100 Subject: [PATCH] add ToString() helper (#2100) --- pkg/exprhelpers/exprlib.go | 9 ++++++++ pkg/exprhelpers/exprlib_test.go | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/pkg/exprhelpers/exprlib.go b/pkg/exprhelpers/exprlib.go index 6e4081ae8..ec1fa6357 100644 --- a/pkg/exprhelpers/exprlib.go +++ b/pkg/exprhelpers/exprlib.go @@ -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 +} diff --git a/pkg/exprhelpers/exprlib_test.go b/pkg/exprhelpers/exprlib_test.go index 20927a65d..3413bc068 100644 --- a/pkg/exprhelpers/exprlib_test.go +++ b/pkg/exprhelpers/exprlib_test.go @@ -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) + }) + } + +}