This repository was archived by the owner on Aug 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecover_test.go
77 lines (55 loc) · 1.75 KB
/
recover_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package emperror
import (
"fmt"
"testing"
)
func createRecoverFunc(p interface{}) func() error {
return func() (err error) {
defer func() {
err = Recover(recover())
}()
panic(p)
}
}
func assertRecoveredError(t *testing.T, err error, msg string) {
t.Helper()
st, ok := StackTrace(err)
if !ok {
t.Fatal("error is expected to carry a stack trace")
}
if got, want := fmt.Sprintf("%n", st[0]), "createRecoverFunc.func1"; got != want { // nolint: govet
t.Errorf("function name does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
if got, want := fmt.Sprintf("%s", st[0]), "recover_test.go"; got != want { // nolint: govet
t.Errorf("file name does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
if got, want := fmt.Sprintf("%d", st[0]), "14"; got != want { // nolint: govet
t.Errorf("line number does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
if got, want := err.Error(), msg; got != want {
t.Errorf("error message does not match the expected one\nactual: %s\nexpected: %s", got, want)
}
}
func TestRecover_ErrorPanic(t *testing.T) {
err := fmt.Errorf("internal error")
f := createRecoverFunc(err)
v := f()
assertRecoveredError(t, v, "internal error")
}
func TestRecover_StringPanic(t *testing.T) {
f := createRecoverFunc("internal error")
v := f()
assertRecoveredError(t, v, "internal error")
}
func TestRecover_AnyPanic(t *testing.T) {
f := createRecoverFunc(123)
v := f()
assertRecoveredError(t, v, "unknown panic, received: 123")
}
func TestRecover_Nil(t *testing.T) {
f := createRecoverFunc(nil)
v := f()
if got, want := v, error(nil); got != want { // nolint: govet
t.Errorf("the recovered value is expected to be nil\nactual: %v", got)
}
}