-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_test.go
120 lines (105 loc) · 2.38 KB
/
handler_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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package prommetrics
import (
"errors"
"net/http"
"reflect"
"testing"
"net/http/httptest"
"github.com/caddyserver/caddy/v2"
)
func next(w http.ResponseWriter, r *http.Request) error {
return nil
}
func TestMetrics_ServeHTTP(t *testing.T) {
successRequest, err := http.NewRequest("GET", "http://test.com/success", nil)
errorRequest, err := http.NewRequest("GET", "http://test.com/error", nil)
proxyRequest, err := http.NewRequest("GET", "http://test.com/proxy", nil)
// proxyErrorRequest, err := http.NewRequest("GET", "http://test.com/proxyerror", nil)
if err != nil {
t.Fatal(err)
}
type args struct {
w http.ResponseWriter
r *http.Request
}
tests := []struct {
name string
args args
want observed
wantErr bool
}{
{
name: "200 handler response",
args: args{
w: httptest.NewRecorder(),
r: successRequest,
},
want: observed{status: "2xx", path: "/success"},
wantErr: false,
},
{
name: "500 handler response",
args: args{
w: httptest.NewRecorder(),
r: errorRequest,
},
want: observed{status: "5xx"},
wantErr: false,
},
{
name: "proxy handler response",
args: args{
w: httptest.NewRecorder(),
r: proxyRequest,
},
want: observed{status: "5xx"},
wantErr: false,
},
// {
// name: "proxy error handler response",
// args: args{
// w: httptest.NewRecorder(),
// r: proxyErrorRequest,
// },
// want: observed{},
// wantErr: true,
// },
}
o := &observed{}
mockObserver := func(obs *observed) {
o = obs
}
m := &Metrics{
regex: `^/([^/]*).*$`,
observer: mockObserver,
}
// Compiles regex
m.Provision(caddy.Context{})
for i, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := m.ServeHTTP(tt.args.w, tt.args.r, testHandler{})
if (err != nil) != tt.wantErr {
t.Errorf("Test %d: Metrics.ServeHTTP() error = %v, wantErr %v", i, err, tt.wantErr)
return
}
if reflect.DeepEqual(o, tt.want) {
t.Errorf("Test %d: Metrics.ServeHTTP() = %+v, want %+v", i, o, tt.want)
}
})
}
}
type testHandler struct{}
func (h testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
var err error
switch r.URL.Path {
case "/success":
w.WriteHeader(200)
w.Write([]byte{})
case "/error":
w.WriteHeader(500)
w.Write([]byte{})
case "/proxyerror":
err = errors.New("no hosts available upstream")
}
return err
}