test_: add test TestSafeGo

This commit is contained in:
frank 2024-09-18 18:37:03 +08:00
parent f612dd828f
commit a1fa91839f
No known key found for this signature in database
GPG Key ID: B56FA1FC264D28FD
2 changed files with 55 additions and 1 deletions

View File

@ -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()

50
common/utils_test.go Normal file
View File

@ -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")
}
}