chore: enhance TopKeys function & adding test cases for malformed lines scenario in TopKeys func (#1654)

This commit is contained in:
Zubair Haque 2024-08-04 21:27:42 -04:00 committed by GitHub
parent 86664f57f6
commit dc5c4a80ba
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 35 additions and 5 deletions

View File

@ -82,12 +82,15 @@ func TopKeys(helmfileContent []byte, hasSeparator bool) []string {
clines := bytes.Split(helmfileContent, []byte("\n")) clines := bytes.Split(helmfileContent, []byte("\n"))
for _, line := range clines { for _, line := range clines {
if topConfigKeysRegex.Match(line) { lineStr := strings.TrimSpace(string(line))
lineStr := strings.Split(string(line), ":")[0] if lineStr == "" {
topKeys = append(topKeys, lineStr) continue // Skip empty lines
} }
if hasSeparator && separatorRegex.Match(line) { if hasSeparator && separatorRegex.MatchString(lineStr) {
topKeys = append(topKeys, strings.TrimSpace(string(line))) topKeys = append(topKeys, lineStr)
} else if topConfigKeysRegex.MatchString(lineStr) {
topKey := strings.SplitN(lineStr, ":", 2)[0]
topKeys = append(topKeys, topKey)
} }
} }
return topKeys return topKeys

View File

@ -239,3 +239,30 @@ func TestTopKeys(t *testing.T) {
}) })
} }
} }
func TestTopKeys_MalformedLines(t *testing.T) {
tests := []struct {
name string
helmfileContent []byte
hasSeparator bool
want []string
}{
{
name: "malformed lines with special characters",
helmfileContent: []byte("bas@es:\nenvironm*ents:\nrele#ases:\n"),
want: nil, // This test expects no valid top keys
},
{
name: "malformed lines with incomplete key",
helmfileContent: []byte("bases\nenvironments:\nreleases:\n"),
want: []string{"environments", "releases"}, // This test expects only valid top keys
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := TopKeys(tt.helmfileContent, tt.hasSeparator)
require.Equal(t, tt.want, got, "expected %v, got=%v", tt.want, got)
})
}
}