Skip to content

Commit

Permalink
Fix slice bounds out of range [:5]
Browse files Browse the repository at this point in the history
When the capacity of the given byte slice is less than 5 the `getTestID`
function panics with:

```
panic: runtime error: slice bounds out of range [:5] with capacity 1 [recovered]
	panic: runtime error: slice bounds out of range [:5] with capacity 1
```

This uses `bytes.HasPrefix` instead which will check the bounds of the
slice before comparing.
  • Loading branch information
zregvart committed Apr 22, 2024
1 parent e31ee30 commit 0890b47
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion snaps/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func getTestID(b []byte) (string, bool) {
}

// needs to start with [Test and end with ]
if !bytes.Equal(b[0:5], []byte("[Test")) || b[len(b)-1] != ']' {
if !bytes.HasPrefix(b, []byte("[Test")) || b[len(b)-1] != ']' {
return "", false
}

Expand Down
5 changes: 4 additions & 1 deletion snaps/clean_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@ func TestGetTestID(t *testing.T) {
// must have dash between test name and number
{"[Test something 10]", "", false},
{"[Test/something - not a number]", "", false},
{"s", "", false},
}

for _, tc := range testCases {
Expand All @@ -456,7 +457,9 @@ func TestGetTestID(t *testing.T) {
t.Run(tc.input, func(t *testing.T) {
t.Parallel()

id, ok := getTestID([]byte(tc.input))
b := make([]byte, 0, len(tc.input))
b = append(b, []byte(tc.input)...)
id, ok := getTestID(b)

test.Equal(t, tc.valid, ok)
test.Equal(t, tc.expectedID, id)
Expand Down

0 comments on commit 0890b47

Please sign in to comment.