Repository navigation
Expand file tree
/
Copy pathlogger_test.go
More file actions
85 lines (79 loc) · 1.98 KB
/
Copy pathlogger_test.go
File metadata and controls
85 lines (79 loc) · 1.98 KB
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
package logger
import (
"context"
"math/rand"
"net/http"
"testing"
)
func TestReqID(t *testing.T) {
t.Run("check exist key", func(t *testing.T) {
reqID := randString(16)
r, err := http.NewRequest("GET", "http://localhost/test", nil)
if err != nil {
t.Fatal(err)
}
r.Header.Set("x-request-id", reqID)
r = ReqWithLoggerContext(r)
ctxVal := r.Context().Value(requestIDKey{})
if ctxVal == nil {
t.Fatal("key not found")
}
result, ok := ctxVal.(string)
if !ok {
t.Fatal("incorrect key type")
}
if result != reqID {
t.Fatal("result is incorrect")
}
Logger()
})
t.Run("check correct key value", func(t *testing.T) {
reqID := randString(16)
r, err := http.NewRequest("GET", "http://localhost/test", nil)
if err != nil {
t.Fatal(err)
}
r.Header.Set("x-request-id", reqID)
type testType struct{}
r = r.WithContext(context.WithValue(context.Background(), testType{}, "test"))
r = ReqWithLoggerContext(r)
r = r.WithContext(context.WithValue(r.Context(), testType{}, "test2"))
ctxVal := r.Context().Value(requestIDKey{})
if ctxVal == nil {
t.Fatal("key not found")
}
result, ok := ctxVal.(string)
if !ok {
t.Fatal("incorrect key type")
}
if result != reqID {
t.Fatal("result is incorrect")
}
})
t.Run("outcome request", func(t *testing.T) {
reqID := randString(16)
r, err := http.NewRequest("GET", "http://localhost/test", nil)
if err != nil {
t.Fatal(err)
}
r.Header.Set("x-request-id", reqID)
r = ReqWithLoggerContext(r)
outReq, err := http.NewRequest("GET", "http://localhost/test", nil)
if err != nil {
t.Fatal(err)
}
AddHeadersFromContext(outReq.Header, r.Context())
result := outReq.Header.Get("x-request-id")
if result != reqID {
t.Fatal("no request ID in result")
}
})
}
func randString(n int) string {
b := make([]byte, n)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}