Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

narinfo: Fix the splitOnce function #124

Merged
merged 4 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkg/narinfo/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func splitOnce(s string, sep string) (string, string, error) {
return "", "", fmt.Errorf("unable to find separator '%s' in %v", sep, s)
}

if strings.Contains(s[:idx], sep) {
if strings.Contains(s[idx+1:], sep) {
return "", "", fmt.Errorf("found separator '%s' twice or more in %v", sep, s)
}

Expand Down
57 changes: 57 additions & 0 deletions pkg/narinfo/splitonce_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//nolint:testpackage
package narinfo

import (
"fmt"
"testing"
)

func TestSplitOnce(t *testing.T) {
tests := []struct {
s string
sep string
str1 string
str2 string
err string
}{
{"hello:world", ":", "hello", "world", ""},
{":helloworld", ":", "", "helloworld", ""},
{"helloworld:", ":", "helloworld", "", ""},
{"helloworld", ":", "", "", "unable to find separator ':' in helloworld"},
{"hello:wo:rld", ":", "", "", "found separator ':' twice or more in hello:wo:rld"},
{"hello::world", ":", "", "", "found separator ':' twice or more in hello::world"},
}

for _, ltest := range tests {
// TODO: This is not necessary on Go >=1.23. Remove this assignment and use
// test instead of ltest above.
test := ltest

tName := fmt.Sprintf("splitOnce(%q, %q) -> (%q, %q, %s)",
test.s, test.sep, test.str1, test.str2, test.err)

t.Run(tName, func(t *testing.T) {
t.Parallel()

str1, str2, err := splitOnce(test.s, test.sep)

if test.err == "" && err != nil {
t.Fatalf("expected no error but got %s", err)
} else if test.err != "" && err == nil {
t.Fatalf("expected an error but got none")
} else if test.err != "" && err != nil {
if want, got := test.err, err.Error(); want != got {
t.Errorf("want %q got %q", want, got)
}
}

if want, got := test.str1, str1; want != got {
t.Errorf("want %q got %q", want, got)
}

if want, got := test.str2, str2; want != got {
t.Errorf("want %q got %q", want, got)
}
})
}
}