forked from go-chi/chi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content_type_test.go
82 lines (72 loc) · 2.05 KB
/
content_type_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
package middleware
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
)
func TestContentType(t *testing.T) {
t.Parallel()
var tests = []struct {
name string
inputValue string
allowedContentTypes []string
want int
}{
{
"should accept requests with a matching content type",
"application/json; charset=UTF-8",
[]string{"application/json"},
http.StatusOK,
},
{
"should accept requests with a matching content type no charset",
"application/json",
[]string{"application/json"},
http.StatusOK,
},
{
"should accept requests with a matching content-type with extra values",
"application/json; foo=bar; charset=UTF-8; spam=eggs",
[]string{"application/json"},
http.StatusOK,
},
{
"should accept requests with a matching content type when multiple content types are supported",
"text/xml; charset=UTF-8",
[]string{"application/json", "text/xml"},
http.StatusOK,
},
{
"should not accept requests with a mismatching content type",
"text/plain; charset=latin-1",
[]string{"application/json"},
http.StatusUnsupportedMediaType,
},
{
"should not accept requests with a mismatching content type even if multiple content types are allowed",
"text/plain; charset=Latin-1",
[]string{"application/json", "text/xml"},
http.StatusUnsupportedMediaType,
},
}
for _, tt := range tests {
var tt = tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
r := chi.NewRouter()
r.Use(AllowContentType(tt.allowedContentTypes...))
r.Post("/", func(w http.ResponseWriter, r *http.Request) {})
body := []byte("This is my content. There are many like this but this one is mine")
req := httptest.NewRequest("POST", "/", bytes.NewReader(body))
req.Header.Set("Content-Type", tt.inputValue)
r.ServeHTTP(recorder, req)
res := recorder.Result()
if res.StatusCode != tt.want {
t.Errorf("response is incorrect, got %d, want %d", recorder.Code, tt.want)
}
})
}
}