mirror of
https://github.com/libp2p/go-libp2p-core.git
synced 2024-12-26 23:30:27 +08:00
648dc3fba2
* feat: harden encoding/decoding functions against panics Part of https://github.com/libp2p/go-libp2p/issues/1389 These kinds of functions: 1. Handle user input. 2. Often have out-of-bounds, null pointer, etc bugs. 3. Have completely isolated logic where local panics are unlikely to cause memory corruption elsewhere. * test: add a panic catcher test
29 lines
540 B
Go
29 lines
540 B
Go
package catch
|
|
|
|
import (
|
|
"bytes"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestCatch(t *testing.T) {
|
|
buf := new(bytes.Buffer)
|
|
|
|
oldPanicWriter := panicWriter
|
|
t.Cleanup(func() { panicWriter = oldPanicWriter })
|
|
panicWriter = buf
|
|
|
|
panicAndCatch := func() (err error) {
|
|
defer func() { HandlePanic(recover(), &err, "somewhere") }()
|
|
|
|
panic("here")
|
|
}
|
|
|
|
err := panicAndCatch()
|
|
require.Error(t, err)
|
|
require.Contains(t, err.Error(), "panic in somewhere: here")
|
|
|
|
require.Contains(t, buf.String(), "caught panic: here")
|
|
}
|