gkampitakis / go-snaps

Jest-like snapshot testing in Golang 📸
https://pkg.go.dev/github.com/gkampitakis/go-snaps
MIT License
146 stars 6 forks source link

fix: slice bounds out of range [:5] #98

Closed zregvart closed 3 months ago

zregvart commented 3 months ago

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.

gkampitakis commented 3 months ago

Wow that's such a stupid bug I wrote there 😓 . Thanks for the pr fixing this. Also at first I didn't understand why you did this.

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

When I tried to reproduce it with[]byte(tc.input) creates a byte slice with capacity 32 😮‍💨 so even with unit test I might have not caught it, also maybe i was lucky with b := s.Bytes() reusing the slice.

zregvart commented 3 months ago

It is a very easy to make omission, I think it is very rare that the slices are created with capacity less than 5. I was surprised that something changed in our test code that triggered a panic.