-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_test.go
110 lines (101 loc) · 2.84 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package governor
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestMiddleware(t *testing.T) {
t.Parallel()
t.Run("compressorWriter", func(t *testing.T) {
t.Parallel()
defaultCompressibleMediaTypesSet := make(map[string]struct{}, len(defaultCompressibleMediaTypes))
for _, i := range defaultCompressibleMediaTypes {
defaultCompressibleMediaTypesSet[i] = struct{}{}
}
for _, tc := range []struct {
Test string
ReqHeaders map[string]string
ResHeaders map[string]string
Status int
Encoding string
}{
{
Test: "selects first compression algorithm",
ReqHeaders: map[string]string{
headerAcceptEncoding: encodingKindGzip + ", " + encodingKindZlib,
},
ResHeaders: map[string]string{
headerContentType: "application/json; charset=utf-8",
headerContentLength: "123",
},
Status: http.StatusOK,
Encoding: encodingKindGzip,
},
{
Test: "does not re-compress compressed data",
ReqHeaders: map[string]string{
headerAcceptEncoding: encodingKindGzip + ", " + encodingKindZlib,
},
ResHeaders: map[string]string{
headerContentType: "application/json; charset=utf-8",
headerContentEncoding: encodingKindZstd,
},
Status: http.StatusOK,
Encoding: encodingKindZstd,
},
{
Test: "does not re-compress switched protocol data",
ReqHeaders: map[string]string{
headerAcceptEncoding: encodingKindGzip + ", " + encodingKindZlib,
},
ResHeaders: map[string]string{
headerContentType: "application/json; charset=utf-8",
},
Status: http.StatusSwitchingProtocols,
Encoding: "",
},
{
Test: "does not compress incompressable content type",
ReqHeaders: map[string]string{
headerAcceptEncoding: encodingKindGzip + ", " + encodingKindZlib,
},
ResHeaders: map[string]string{
headerContentType: "image/jpeg",
},
Status: http.StatusOK,
Encoding: "",
},
} {
t.Run(tc.Test, func(t *testing.T) {
t.Parallel()
assert := require.New(t)
req := httptest.NewRequest(http.MethodGet, "/api/test", nil)
for k, v := range tc.ReqHeaders {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
w := compressorWriter{
w: rec,
r: req,
status: 0,
writer: &identityWriter{
w: rec,
},
compressableMediaTypes: defaultCompressibleMediaTypesSet,
allowedEncodings: defaultAllowedEncodings,
preferredEncodings: defaultPreferredEncodings,
wroteHeader: false,
}
for k, v := range tc.ResHeaders {
w.Header().Set(k, v)
}
w.WriteHeader(tc.Status)
assert.Equal(tc.Encoding, rec.Result().Header.Get(headerContentEncoding))
if tc.Encoding != "" {
assert.Equal("", rec.Result().Header.Get(headerContentLength))
}
})
}
})
}