-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
96 lines (79 loc) · 2.66 KB
/
middleware_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
package tracing_test
import (
"net/http"
"net/http/httptest"
"testing"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go/mocktracer"
"github.com/stretchr/testify/assert"
"github.com/urfave/negroni"
"github.com/ory/hydra/tracing"
)
var mockedTracer *mocktracer.MockTracer
var tracer *tracing.Tracer = &tracing.Tracer{
ServiceName: "Ory Hydra Test",
Provider: "Mock Provider",
}
func init() {
mockedTracer = mocktracer.New()
opentracing.SetGlobalTracer(mockedTracer)
}
func TestTracingServeHttp(t *testing.T) {
expectedTagsSuccess := map[string]interface{}{
string(ext.HTTPStatusCode): uint16(200),
string(ext.HTTPMethod): "GET",
}
expectedTagsError := map[string]interface{}{
string(ext.HTTPStatusCode): uint16(400),
string(ext.HTTPMethod): "GET",
"error": true,
}
testCases := []struct {
httpStatus int
testDescription string
expectedTags map[string]interface{}
}{
{
testDescription: "success http response",
httpStatus: http.StatusOK,
expectedTags: expectedTagsSuccess,
},
{
testDescription: "error http response",
httpStatus: http.StatusBadRequest,
expectedTags: expectedTagsError,
},
}
for _, test := range testCases {
t.Run(test.testDescription, func(t *testing.T) {
defer mockedTracer.Reset()
request := httptest.NewRequest(http.MethodGet, "https://apis.somecompany.com/endpoint", nil)
next := func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(test.httpStatus)
}
tracer.ServeHTTP(negroni.NewResponseWriter(httptest.NewRecorder()), request, next)
spans := mockedTracer.FinishedSpans()
assert.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, test.expectedTags, span.Tags())
})
}
}
func TestShouldContinueTraceIfAlreadyPresent(t *testing.T) {
defer mockedTracer.Reset()
parentSpan := mockedTracer.StartSpan("some-operation").(*mocktracer.MockSpan)
ext.SpanKindRPCClient.Set(parentSpan)
request := httptest.NewRequest(http.MethodGet, "https://apis.somecompany.com/endpoint", nil)
carrier := opentracing.HTTPHeadersCarrier(request.Header)
// this request now contains a trace initiated by another service/process (e.g. an edge proxy that fronts Hydra)
mockedTracer.Inject(parentSpan.Context(), opentracing.HTTPHeaders, carrier)
next := func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(http.StatusOK)
}
tracer.ServeHTTP(negroni.NewResponseWriter(httptest.NewRecorder()), request, next)
spans := mockedTracer.FinishedSpans()
assert.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, parentSpan.SpanContext.SpanID, span.ParentID)
}