Skip to content

Commit

Permalink
narinfo: Fix the splitOnce function (#124)
Browse files Browse the repository at this point in the history
* add a failing test

* fix it

* remove t.parallel call not required

* add more bound checks

---------

Co-authored-by: zimbatm <[email protected]>
  • Loading branch information
kalbasit and zimbatm authored Dec 2, 2024
1 parent 0327d78 commit bf39504
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
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)
}
})
}
}

0 comments on commit bf39504

Please sign in to comment.