File: content_type_test.go

package info (click to toggle)
golang-github-go-chi-chi 5.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 644 kB
  • sloc: makefile: 19
file content (82 lines) | stat: -rw-r--r-- 2,095 bytes parent folder | download | duplicates (2)
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)
			}
		})
	}
}