test_: add test TestSafeGo
This commit is contained in:
parent
f612dd828f
commit
a1fa91839f
|
@ -20,6 +20,10 @@ var ErrInvalidDisplayNameNotAllowed = errors.New("name is not allowed")
|
|||
|
||||
var DISPLAY_NAME_EXT = []string{"_eth", ".eth", "-eth"}
|
||||
|
||||
var defaultPanicFunc func(any) = func(err any) {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
func RecoverKey(m *protobuf.ApplicationMetadataMessage) (*ecdsa.PublicKey, error) {
|
||||
if m.Signature == nil {
|
||||
return nil, nil
|
||||
|
@ -95,7 +99,7 @@ func SafeGo(f func(), panicHandlers ...func(interface{})) {
|
|||
for _, handler := range panicHandlers {
|
||||
handler(err)
|
||||
}
|
||||
panic(err)
|
||||
defaultPanicFunc(err)
|
||||
}
|
||||
}()
|
||||
f()
|
||||
|
|
|
@ -0,0 +1,50 @@
|
|||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSafeGo(t *testing.T) {
|
||||
// Test that SafeGo recovers from panic
|
||||
paniced := false
|
||||
panicErr := "test panic"
|
||||
defaultPanicFunc = func(err any) {
|
||||
require.NotNil(t, err)
|
||||
paniced = true
|
||||
}
|
||||
recovered := make(chan bool, 1)
|
||||
SafeGo(func() {
|
||||
panic(panicErr)
|
||||
}, func(err any) {
|
||||
recovered <- true
|
||||
if err != panicErr {
|
||||
t.Errorf("Expected panic with 'test panic', got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
timeout := 5 * time.Second
|
||||
select {
|
||||
case <-recovered:
|
||||
// Panic was recovered successfully
|
||||
case <-time.After(timeout):
|
||||
t.Error("SafeGo did not recover from panic within the timeout")
|
||||
}
|
||||
|
||||
require.True(t, paniced)
|
||||
|
||||
// Test that SafeGo executes normally when no panic occurs
|
||||
executed := make(chan bool, 1)
|
||||
SafeGo(func() {
|
||||
executed <- true
|
||||
})
|
||||
|
||||
select {
|
||||
case <-executed:
|
||||
// Function executed successfully
|
||||
case <-time.After(timeout):
|
||||
t.Error("SafeGo did not execute the function within the timeout")
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue