-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttpmiddleware_test.go
182 lines (156 loc) · 4.68 KB
/
httpmiddleware_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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
// Package httpmiddleware contains HTTP middlewares.
package httpmiddleware
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/go-faster/sdk/zctx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
)
type testHandler struct{}
func (*testHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
type testMiddleware struct{}
func (*testMiddleware) ServeHTTP(http.ResponseWriter, *http.Request) {}
func TestInjectLogger(t *testing.T) {
core, logs := observer.New(zapcore.DebugLevel)
h := Wrap(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lg := zctx.From(r.Context())
lg.Info("Hello")
}),
InjectLogger(zap.New(core)),
)
h.ServeHTTP(nil, &http.Request{})
entries := logs.FilterLevelExact(zapcore.InfoLevel).All()
require.Len(t, entries, 1)
entry := entries[0]
require.Equal(t, "Hello", entry.Message)
}
type testOgenServer struct{}
func (*testOgenServer) FindPath(method string, u *url.URL) (r testOgenRoute, _ bool) {
if method != http.MethodGet || u.Path != "/foo" {
return r, false
}
return r, true
}
type testOgenRoute struct{}
func (testOgenRoute) Name() string { return "TestRoute" }
func (testOgenRoute) OperationID() string { return "testRoute" }
func (testOgenRoute) PathPattern() string { return "/foo" }
func TestLogRequests(t *testing.T) {
core, logs := observer.New(zapcore.DebugLevel)
h := Wrap(&testHandler{},
InjectLogger(zap.New(core)),
LogRequests(MakeRouteFinder(&testOgenServer{})),
)
h.ServeHTTP(nil, &http.Request{
Method: http.MethodPost,
URL: &url.URL{
Path: "/unknown_path",
},
})
h.ServeHTTP(nil, &http.Request{
Method: http.MethodGet,
URL: &url.URL{
Path: "/foo",
},
})
entries := logs.FilterLevelExact(zapcore.InfoLevel).All()
require.Len(t, entries, 2)
entry := entries[0]
require.Equal(t, "Got request", entry.Message)
fields := entry.ContextMap()
require.Len(t, fields, 2)
require.Equal(t, http.MethodPost, fields["method"])
require.Equal(t, "/unknown_path", fields["url"])
entry = entries[1]
require.Equal(t, "Got request", entry.Message)
fields = entry.ContextMap()
require.Len(t, fields, 4)
require.Equal(t, http.MethodGet, fields["method"])
require.Equal(t, "/foo", fields["url"])
require.Equal(t, "TestRoute", fields["operationName"])
require.Equal(t, "testRoute", fields["operationId"])
}
func TestWrap(t *testing.T) {
endpoint := &testHandler{}
// Check case with zero middlewares.
result := Wrap(endpoint)
require.Equal(t, endpoint, result)
// Check case with one middleware.
middleware := &testMiddleware{}
result = Wrap(endpoint, func(h http.Handler) http.Handler {
return middleware
})
require.Equal(t, middleware, result)
// Ensure order of wrapping.
var (
calls []int
callMiddleware = func(n int) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls = append(calls, n)
next.ServeHTTP(w, r)
})
}
}
)
result = Wrap(endpoint,
callMiddleware(1),
callMiddleware(2),
callMiddleware(3),
)
result.ServeHTTP(nil, nil)
require.Equal(t, []int{1, 2, 3}, calls)
}
func TestInstrumentation(t *testing.T) {
provider := NewProvider()
tracer := provider.Tracer("test")
fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
t.Logf("Handler(ctx).IsValid(): %v", trace.SpanContextFromContext(ctx).IsValid())
assert.True(t, trace.SpanContextFromContext(ctx).IsValid())
_, span := tracer.Start(r.Context(), "Handler")
defer span.End()
w.WriteHeader(http.StatusOK)
})
h := Wrap(fn,
otelhttp.NewMiddleware("otelhttp.Middleware",
otelhttp.WithTracerProvider(provider),
),
func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sc := trace.SpanContextFromContext(ctx)
t.Logf("after(ctx).IsValid(): %v (%s)", sc.IsValid(), sc.TraceID())
assert.True(t, sc.IsValid(), "Middleware span should be valid")
ctx, span := tracer.Start(ctx, "After")
defer span.End()
handler.ServeHTTP(w, r.WithContext(ctx))
})
},
)
rw := httptest.NewRecorder()
req := &http.Request{
Method: http.MethodGet,
URL: &url.URL{
Path: "/foo",
},
}
h.ServeHTTP(rw, req.WithContext(context.Background()))
require.Equal(t, http.StatusOK, rw.Code)
provider.Flush()
spans := provider.Exporter.GetSpans()
assert.Len(t, spans, 3)
for _, s := range spans {
t.Logf("%s [%s]", s.Name, s.SpanContext.TraceID())
}
}