-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanics_test.go
62 lines (56 loc) · 1.68 KB
/
panics_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package errs
import (
"errors"
"testing"
)
type stringer string
func (s stringer) String() string { return string(s) }
func TestAsError(t *testing.T) {
tests := []struct {
name string
input any
wantErr error
}{
{name: "nil", input: nil, wantErr: nil},
{name: "error", input: errors.New("error"), wantErr: errors.New("error")},
{name: "errors", input: []error{errors.New("a"), errors.New("a")}, wantErr: errors.Join(errors.New("a"), errors.New("a"))},
{name: "string", input: "string", wantErr: errors.New("string")},
{name: "stringer", input: stringer("stringer"), wantErr: errors.New("stringer")},
{name: "int", input: 666, wantErr: errors.New("666")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := AsError(tt.input)
if ((err == nil) != (tt.wantErr == nil)) || (tt.wantErr != nil && err.Error() != tt.wantErr.Error()) {
t.Errorf("AsError() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestRecoverPanicAsError(t *testing.T) {
f := func(p any) (err error) {
defer RecoverPanicAsError(&err)
if p != nil {
panic(p)
}
return nil
}
tests := []struct {
name string
panic any
wantErr error
}{
{name: "nil", panic: nil, wantErr: nil},
// TODO normalize callstack because paths are on local machine
// {name: "string", panic: "string", wantErr: errors.New("string")},
// {name: "int", panic: 666, wantErr: errors.New("666")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := f(tt.panic)
if ((err == nil) != (tt.wantErr == nil)) || (tt.wantErr != nil && err.Error() != tt.wantErr.Error()) {
t.Errorf("AsError() error = %s, wantErr %s", err, tt.wantErr)
}
})
}
}