forked from newrelic/go-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
internal_errors_stacktrace_test.go
79 lines (66 loc) · 2.27 KB
/
internal_errors_stacktrace_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
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// +build go1.7
package newrelic
import (
"runtime"
"strings"
"testing"
)
// The use of runtime.CallersFrames requires Go 1.7+.
func topFrameFunction(stack []uintptr) string {
var frame runtime.Frame
frames := runtime.CallersFrames(stack)
if nil != frames {
frame, _ = frames.Next()
}
return frame.Function
}
type withStackAndCause struct {
cause error
stack []uintptr
}
type withStack struct {
stack []uintptr
}
func (e withStackAndCause) Error() string { return e.cause.Error() }
func (e withStackAndCause) StackTrace() []uintptr { return e.stack }
func (e withStackAndCause) Unwrap() error { return e.cause }
func (e withStack) Error() string { return "something went wrong" }
func (e withStack) StackTrace() []uintptr { return e.stack }
func generateStack() []uintptr {
skip := 2 // skip runtime.Callers and this function.
callers := make([]uintptr, 20)
written := runtime.Callers(skip, callers)
return callers[:written]
}
func alpha() []uintptr { return generateStack() }
func beta() []uintptr { return generateStack() }
func TestStackTrace(t *testing.T) {
// First choice is any StackTrace() of the immediate error.
// Second choice is any StackTrace() of the error's cause.
// Final choice is stack trace of the current location.
testcases := []struct {
Error error
ExpectTopFrame string
}{
{Error: basicError{}, ExpectTopFrame: "internal.GetStackTrace"},
{Error: withStack{stack: alpha()}, ExpectTopFrame: "alpha"},
{Error: withStack{stack: nil}, ExpectTopFrame: "internal.GetStackTrace"},
{Error: withStackAndCause{stack: alpha(), cause: basicError{}}, ExpectTopFrame: "alpha"},
{Error: withStackAndCause{stack: nil, cause: withStack{stack: beta()}}, ExpectTopFrame: "beta"},
{Error: withStackAndCause{stack: nil, cause: withStack{stack: nil}}, ExpectTopFrame: "internal.GetStackTrace"},
}
for idx, tc := range testcases {
data, err := errDataFromError(tc.Error)
if err != nil {
t.Errorf("testcase %d: got error: %v", idx, err)
continue
}
fn := topFrameFunction(data.Stack)
if !strings.Contains(fn, tc.ExpectTopFrame) {
t.Errorf("testcase %d: expected %s got %s",
idx, tc.ExpectTopFrame, fn)
}
}
}