Skip to content

Commit 2344698

Browse files
41kstklauser
authored andcommitted
Fix set string method with single element
Fixes an issue with the Set String() method when used with a single element Set. The issue is that it would previously return the memory address instead of the value of the element. Fixes: cilium#41495 Signed-off-by: Alex Melhem <alex.melhem@datadoghq.com>
1 parent c0e2162 commit 2344698

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

pkg/container/set/set.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ func (s Set[T]) Len() int {
3434

3535
func (s Set[T]) String() string {
3636
if s.single != nil {
37-
return fmt.Sprintf("%v", s.single)
37+
return fmt.Sprintf("%v", *s.single)
3838
}
3939
res := ""
4040
for m := range s.members {

pkg/container/set/set_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package set
55

66
import (
77
"fmt"
8+
"strings"
89
"testing"
910

1011
"github.com/stretchr/testify/require"
@@ -275,3 +276,42 @@ func TestSet(t *testing.T) {
275276
}
276277
require.True(t, set2.Empty())
277278
}
279+
280+
func TestSet_String(t *testing.T) {
281+
tests := []struct {
282+
name string
283+
intSet Set[int]
284+
expected string
285+
expectedElements []string
286+
}{
287+
{
288+
name: "returns empty string on empty set",
289+
intSet: NewSet[int](),
290+
expected: "",
291+
},
292+
{
293+
name: "returns single set element as string",
294+
intSet: NewSet(1),
295+
expected: "1",
296+
},
297+
{
298+
name: "returns multi-element set as string",
299+
intSet: NewSet(1, 2, 3),
300+
expectedElements: []string{"1", "2", "3"},
301+
},
302+
}
303+
304+
for _, tt := range tests {
305+
t.Run(tt.name, func(t *testing.T) {
306+
output := tt.intSet.String()
307+
if tt.expected != "" {
308+
require.Equal(t, tt.expected, output)
309+
} else if tt.expectedElements != nil {
310+
for _, e := range tt.expectedElements {
311+
require.Contains(t, output, e)
312+
require.Len(t, strings.Split(output, ","), len(tt.expectedElements))
313+
}
314+
}
315+
})
316+
}
317+
}

0 commit comments

Comments
 (0)