-
Notifications
You must be signed in to change notification settings - Fork 2
/
errors_test.go
92 lines (79 loc) · 1.96 KB
/
errors_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
package errors
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"testing"
)
func TestError(t *testing.T) {
err := New("test")
if m := err.Message(); m != "test" {
t.Errorf("expected %q, got %q", "test", m)
}
if i := err.Inner(); i != nil {
t.Errorf("unexpected inner error %q", i)
}
if s := err.Stack(); s == nil {
t.Error("empty stack trace")
}
if s := err.Error(); strings.Index(s, "test") != 0 {
t.Errorf("expected string to start with %q", "test")
}
}
func TestNew(t *testing.T) {
for _, message := range []string{
"foo",
"bar",
"baz",
} {
if New(message).Error() != message {
t.Errorf("expected error to be equal to %q", message)
}
}
}
func TestErrorf(t *testing.T) {
for message, args := range map[string][]interface{}{
"foo %s": {"f"},
"bar %s %s %s": {"b", "a", "r"},
"baz %s %s": {"b", "z"},
} {
expected := fmt.Sprintf(message, args...)
err := Errorf(message, args...)
if err.Error() != expected {
t.Errorf("unexpected error output %s", err.Error())
}
expected = fmt.Sprintf("%s. x", expected)
err = Wrapf(New("x"), message, args...)
if err.Error() != expected {
t.Error("unexpected error output %s", err.Error())
}
}
}
func TestMarshal(t *testing.T) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(New("test"))
if err != nil {
t.Errorf("json error: %s", err)
}
if !bytes.Contains(buf.Bytes(), []byte(`"message":"test"`)) {
t.Errorf("marshaled error doesn't contain expected segment")
}
if !bytes.Contains(buf.Bytes(), []byte(`"stack":[]`)) {
t.Errorf("marshaled error doesn't contain an empty stack trace")
}
}
func TestMarshalTrace(t *testing.T) {
MarshalTrace = true
defer func() {
MarshalTrace = false
}()
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(New("test"))
if err != nil {
t.Errorf("json error: %s", err)
}
if !bytes.Contains(buf.Bytes(), []byte(`"stack":[{"file":"errors.go"`)) {
t.Errorf("marshaled error should contain a stack trace")
}
}