...
1 package middleware
2
3 import (
4 "bytes"
5 "net/http"
6 "net/http/httptest"
7 "testing"
8
9 "github.com/go-chi/chi"
10 )
11
12 func TestContentEncodingMiddleware(t *testing.T) {
13 t.Parallel()
14
15
16
17
18
19
20 middleware := AllowContentEncoding("deflate", "gzip")
21
22 tests := []struct {
23 name string
24 encodings []string
25 expectedStatus int
26 }{
27 {
28 name: "Support no encoding",
29 encodings: []string{},
30 expectedStatus: 200,
31 },
32 {
33 name: "Support gzip encoding",
34 encodings: []string{"gzip"},
35 expectedStatus: 200,
36 },
37 {
38 name: "No support for br encoding",
39 encodings: []string{"br"},
40 expectedStatus: 415,
41 },
42 {
43 name: "Support for gzip and deflate encoding",
44 encodings: []string{"gzip", "deflate"},
45 expectedStatus: 200,
46 },
47 {
48 name: "Support for deflate and gzip encoding",
49 encodings: []string{"deflate", "gzip"},
50 expectedStatus: 200,
51 },
52 {
53 name: "No support for deflate and br encoding",
54 encodings: []string{"deflate", "br"},
55 expectedStatus: 415,
56 },
57 }
58
59 for _, tt := range tests {
60 var tt = tt
61 t.Run(tt.name, func(t *testing.T) {
62 t.Parallel()
63
64 body := []byte("This is my content. There are many like this but this one is mine")
65 r := httptest.NewRequest("POST", "/", bytes.NewReader(body))
66 for _, encoding := range tt.encodings {
67 r.Header.Set("Content-Encoding", encoding)
68 }
69
70 w := httptest.NewRecorder()
71 router := chi.NewRouter()
72 router.Use(middleware)
73 router.Post("/", func(w http.ResponseWriter, r *http.Request) {})
74
75 router.ServeHTTP(w, r)
76 res := w.Result()
77 if res.StatusCode != tt.expectedStatus {
78 t.Errorf("response is incorrect, got %d, want %d", w.Code, tt.expectedStatus)
79 }
80 })
81 }
82 }
83
View as plain text