...
1 package emperror
2
3 import (
4 "fmt"
5 "testing"
6 )
7
8 func createRecoverFunc(p interface{}) func() error {
9 return func() (err error) {
10 defer func() {
11 err = Recover(recover())
12 }()
13
14 panic(p)
15 }
16 }
17
18 func assertRecoveredError(t *testing.T, err error, msg string) {
19 t.Helper()
20
21 st, ok := StackTrace(err)
22 if !ok {
23 t.Fatal("error is expected to carry a stack trace")
24 }
25
26 if got, want := fmt.Sprintf("%n", st[0]), "createRecoverFunc.func1"; got != want {
27 t.Errorf("function name does not match the expected one\nactual: %s\nexpected: %s", got, want)
28 }
29
30 if got, want := fmt.Sprintf("%s", st[0]), "recover_test.go"; got != want {
31 t.Errorf("file name does not match the expected one\nactual: %s\nexpected: %s", got, want)
32 }
33
34 if got, want := fmt.Sprintf("%d", st[0]), "14"; got != want {
35 t.Errorf("line number does not match the expected one\nactual: %s\nexpected: %s", got, want)
36 }
37
38 if got, want := err.Error(), msg; got != want {
39 t.Errorf("error message does not match the expected one\nactual: %s\nexpected: %s", got, want)
40 }
41 }
42
43 func TestRecover_ErrorPanic(t *testing.T) {
44 err := fmt.Errorf("internal error")
45
46 f := createRecoverFunc(err)
47
48 v := f()
49
50 assertRecoveredError(t, v, "internal error")
51 }
52
53 func TestRecover_StringPanic(t *testing.T) {
54 f := createRecoverFunc("internal error")
55
56 v := f()
57
58 assertRecoveredError(t, v, "internal error")
59 }
60
61 func TestRecover_AnyPanic(t *testing.T) {
62 f := createRecoverFunc(123)
63
64 v := f()
65
66 assertRecoveredError(t, v, "unknown panic, received: 123")
67 }
68
69 func TestRecover_Nil(t *testing.T) {
70 f := createRecoverFunc(nil)
71
72 v := f()
73
74 if got, want := v, error(nil); got != want {
75 t.Errorf("the recovered value is expected to be nil\nactual: %v", got)
76 }
77 }
78
View as plain text