-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrorswithstack_test.go
82 lines (68 loc) · 1.72 KB
/
errorswithstack_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
package errors
import (
"fmt"
"strings"
"testing"
)
const errorMessage = "Thrown from bottom of the stack"
func bottom() error {
return New(errorMessage)
}
func middle() error {
return bottom()
}
func top() error {
return middle()
}
func TestNew(t *testing.T) {
type args struct {
msg string
}
tests := []struct {
name string
args args
wantErr bool
enableStackTrace bool
}{
{"Error with stack trace", args{"Testing errors with a stack"}, true, true},
{"Error without stack trace", args{"Testing errors without a stack"}, true, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.enableStackTrace {
EnableStackTraces()
} else {
DisableStackTraces()
}
if err := New(tt.args.msg); (err != nil) != tt.wantErr {
t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
}
err := top()
if err == nil {
t.Errorf("expected call to top() to return an error with a stack trace formatted in the message")
}
msg := err.Error()
var searchFor string
if tt.enableStackTrace {
searchFor = "Stack Trace:"
if !strings.Contains(msg, searchFor) {
t.Errorf("Expected stack trace to contain %s, got: %s", searchFor, msg)
}
searchFor = errorMessage
if !strings.Contains(msg, searchFor) {
t.Errorf("Expected stack trace to contain %s, got: %s", searchFor, msg)
}
} else {
if msg != errorMessage {
t.Errorf("Expected Error() to return %s, got: %s", errorMessage, msg)
}
}
})
}
}
func errorIfMissing(msg string, searchFor string) string {
if !strings.Contains(msg, searchFor) {
return fmt.Sprintf("Expected stack trace to contain %s, got: %s", searchFor, msg)
}
return ""
}