Skip to content

Commit 6925b56

Browse files
committed
feat(utils): add robust SplitList utility with unit tests (Fixes litmuschaos#555)
This supersedes stale PRs litmuschaos#564 and litmuschaos#686 by introducing a centralized, tested utility. - Added SplitList function to pkg/utils/stringutils to safely handle comma-separated strings - Added unit tests covering edge cases (empty strings, trailing commas, spaces, only commas) - Verified fix for issue where empty input returned slice of length 1
1 parent 3a9a539 commit 6925b56

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

pkg/utils/stringutils/string.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package stringutils
22

33
import (
44
"math/rand"
5+
"strings"
56
"time"
67
)
78

@@ -12,6 +13,21 @@ const (
1213
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
1314
)
1415

16+
func SplitList(s string) []string {
17+
if s == "" {
18+
return []string{}
19+
}
20+
parts := strings.Split(s, ",")
21+
var result []string
22+
for _, p := range parts {
23+
trimmed := strings.TrimSpace(p)
24+
if trimmed != "" {
25+
result = append(result, trimmed)
26+
}
27+
}
28+
return result
29+
}
30+
1531
func GetRunID() string {
1632
return RandStringBytesMask(6, rand.NewSource(time.Now().UnixNano()))
1733
}

pkg/utils/stringutils/string_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,53 @@ func TestGetRunID(t *testing.T) {
6464
}
6565
}
6666
}
67+
68+
func TestSplitList(t *testing.T) {
69+
tests := []struct {
70+
name string
71+
input string
72+
expected []string
73+
}{
74+
{
75+
name: "simple comma seperation",
76+
input: "pod1,pod2,pod3",
77+
expected: []string{"pod1", "pod2", "pod3"},
78+
},
79+
{
80+
name: "seperation with spaces",
81+
input: " pod1 , pod2 , pod3 ",
82+
expected: []string{"pod1", "pod2", "pod3"},
83+
},
84+
{
85+
name: "empty string",
86+
input: "",
87+
expected: []string{},
88+
},
89+
{
90+
name: "string with empty elements",
91+
input: "pod1,,pod2, ,",
92+
expected: []string{"pod1", "pod2"},
93+
},
94+
{
95+
name: "only commas input",
96+
input: ",,,",
97+
expected: []string{},
98+
},
99+
}
100+
101+
for _, tt := range tests {
102+
t.Run(tt.name, func(t *testing.T) {
103+
got := SplitList(tt.input)
104+
if len(got) != len(tt.expected) {
105+
t.Errorf("SplitList(%q) length =%d; want %d", tt.input, len(got), len(tt.expected))
106+
return
107+
}
108+
109+
for i := range got {
110+
if got[i] != tt.expected[i] {
111+
t.Errorf("SplitList(%q)[%d] = %q; want %q", tt.input, i, got[i], tt.expected[i])
112+
}
113+
}
114+
})
115+
}
116+
}

0 commit comments

Comments
 (0)