-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrequest_id_test.go
83 lines (66 loc) · 2.62 KB
/
request_id_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
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
type mockRequestIDNextHandler struct {
called int
request *http.Request
}
func (h *mockRequestIDNextHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
h.called++
h.request = r
}
func TestRequestIDHandler_ServeHTTP(t *testing.T) {
const genExtReqID = "generated-external-request-id"
const genIntReqID = "generated-internal-request-id"
reqIDOpts := RequestIDOpts{
GenerateID: func() string { return genExtReqID },
GenerateInternalID: func() string { return genIntReqID },
}
t.Run("use external requestID from request", func(t *testing.T) {
const headerReqID = "header-request-id"
next := &mockRequestIDNextHandler{}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(headerRequestID, headerReqID)
req.Header.Set(headerInternalRequestID, headerReqID)
h := RequestIDWithOpts(reqIDOpts)(next)
resp := httptest.NewRecorder()
h.ServeHTTP(resp, req)
assert.Equal(t, 1, next.called)
assert.Equal(t, headerReqID, GetRequestIDFromContext(next.request.Context()))
assert.Equal(t, headerReqID, resp.Header().Get(headerRequestID))
assert.Equal(t, genIntReqID, GetInternalRequestIDFromContext(next.request.Context()))
assert.Equal(t, genIntReqID, resp.Header().Get(headerInternalRequestID))
})
t.Run("generate new external requestID", func(t *testing.T) {
next := &mockRequestIDNextHandler{}
req := httptest.NewRequest(http.MethodGet, "/", nil)
h := RequestIDWithOpts(reqIDOpts)(next)
resp := httptest.NewRecorder()
h.ServeHTTP(resp, req)
assert.Equal(t, 1, next.called)
assert.Equal(t, genExtReqID, GetRequestIDFromContext(next.request.Context()))
assert.Equal(t, genExtReqID, resp.Header().Get(headerRequestID))
assert.Equal(t, genIntReqID, GetInternalRequestIDFromContext(next.request.Context()))
assert.Equal(t, genIntReqID, resp.Header().Get(headerInternalRequestID))
})
t.Run("generate external and internal requestIDs using default (xid) alg", func(t *testing.T) {
next := &mockRequestIDNextHandler{}
req := httptest.NewRequest(http.MethodGet, "/", nil)
h := RequestID()(next)
resp := httptest.NewRecorder()
h.ServeHTTP(resp, req)
assert.Equal(t, 1, next.called)
assert.Greater(t, len(GetRequestIDFromContext(next.request.Context())), 0)
assert.Greater(t, len(resp.Header().Get(headerRequestID)), 0)
assert.Greater(t, len(GetInternalRequestIDFromContext(next.request.Context())), 0)
assert.Greater(t, len(resp.Header().Get(headerInternalRequestID)), 0)
})
}