-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreporter_test.go
100 lines (82 loc) · 2.31 KB
/
reporter_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
98
99
100
package reporter
import (
gerrors "errors"
"fmt"
"net/http"
"testing"
"context"
"github.com/remind101/pkg/httpx/errors"
)
var errBoom = gerrors.New("boom")
func TestReport(t *testing.T) {
r := ReporterFunc(func(ctx context.Context, level string, err error) error {
e := err.(*errors.Error)
if e.Request().Header.Get("Content-Type") != "application/json" {
t.Fatal("request information not set")
}
stack := e.StackTrace()
var method string
if stack != nil && len(stack) > 0 {
method = fmt.Sprintf("%n", stack[0])
}
if got, want := method, "TestReport"; got != want {
t.Fatalf("expected the first stacktrace method to be %v, got %v", want, got)
}
return nil
})
ctx := WithReporter(context.Background(), r)
req, _ := http.NewRequest("GET", "/", nil)
req.Header.Set("Content-Type", "application/json")
ctx = errors.WithRequest(ctx, req)
if err := ReportWithLevel(ctx, "error", errBoom); err != nil {
t.Fatal(err)
}
}
func TestReportWithLevel(t *testing.T) {
var calledWithLevel string
r := ReporterFunc(func(ctx context.Context, level string, err error) error {
calledWithLevel = level
return nil
})
ctx := WithReporter(context.Background(), r)
err := ReportWithLevel(ctx, "warning", errBoom)
if err != nil {
t.Fatalf("unexpected error happened %v", err)
}
if got, want := calledWithLevel, "warning"; got != want {
t.Fatalf("expected reporter to have been called with level %v, got %v", want, got)
}
}
func TestReportWithNoReporterInContext(t *testing.T) {
defer func() {
if recover() == nil {
t.Error("Expected panic due to context without reporter, got no panic")
}
}()
ctx := context.Background() // no reporter
Report(ctx, errBoom)
}
func TestMonitor(t *testing.T) {
ensureRepanicked := func() {
if v := recover(); v == nil {
t.Errorf("Must have panicked after reporting!")
}
}
var reportedError error
r := ReporterFunc(func(ctx context.Context, level string, err error) error {
reportedError = err
return nil
})
ctx := WithReporter(context.Background(), r)
done := make(chan interface{})
go func() {
defer close(done)
defer ensureRepanicked()
defer Monitor(ctx)
panic("oh noes!")
}()
<-done
if reportedError == nil || reportedError.Error() != "oh noes!" {
t.Errorf("expected panic 'oh noes!' to be reported, got %#v", reportedError)
}
}