-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanic_test.go
97 lines (82 loc) · 1.83 KB
/
panic_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright (c) 2020, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package errors
import (
stderrors "errors"
"fmt"
"testing"
"github.com/go-pogo/errors/internal"
"github.com/stretchr/testify/assert"
)
func panicOnSomething() {
panic("panic!")
}
func TestWrapPanic(t *testing.T) {
t.Run("without panic", func(t *testing.T) {
defer func() {
assert.Nil(t, recover())
}()
defer WrapPanic("wrapped")
})
t.Run("with panic", func(t *testing.T) {
defer func() {
assert.Equal(t, "wrapped: panic!", recover())
}()
defer WrapPanic("wrapped")
panicOnSomething()
})
}
func TestMust(t *testing.T) {
t.Run("nil error", func(t *testing.T) {
defer func() {
assert.Nil(t, recover())
}()
var err error
Must(true, err)
})
t.Run("panic on error", func(t *testing.T) {
errStr := "foo error"
defer func() {
assert.Contains(t, recover(), errStr)
}()
Must(false, New(errStr))
})
}
func TestCatchPanic(t *testing.T) {
internal.DisableTraceStack()
defer internal.EnableTraceStack()
val := struct{ val string }{val: "some value"}
tests := map[string]struct {
panic interface{}
wantMsg string
}{
"with string": {
panic: "paniek!",
wantMsg: "panic: paniek!",
},
"with struct": {
panic: val,
wantMsg: fmt.Sprintf("panic: %v", val),
},
"with stderror": {
panic: stderrors.New("nooo!"),
wantMsg: "panic: nooo!",
},
"with error": {
panic: New("panic error"),
wantMsg: "panic: panic error",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var have error
defer func() {
assert.Equal(t, newCommonErr(&panicError{tc.panic}, false, 1), have)
assert.Equal(t, tc.wantMsg, have.Error())
}()
defer CatchPanic(&have)
panic(tc.panic)
})
}
}