Debian Codegraph @

multipart_test.go

raw symbols SCIP
1 // Copyright 2014 Martini Authors
2 // Copyright 2014 The Macaron Authors
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License"): you may
5 // not use this file except in compliance with the License. You may obtain
6 // a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 // License for the specific language governing permissions and limitations
14 // under the License.
15
16 package binding
17
18 import (
19 "bytes"
20 "fmt"
21 "mime/multipart"
22 "net/http"
23 "net/http/httptest"
24 "strconv"
25 "testing"
26
27 chi "github.com/go-chi/chi/v5"
28 "github.com/stretchr/testify/assert"
29 )
30
31 var multipartFormTestCases = []multipartFormTestCase{
32 {
33 description: "Happy multipart form path",
34 shouldSucceed: true,
35 inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}},
36 },
37 {
38 description: "FormValue called before req.MultipartReader(); see https://github.com/martini-contrib/csrf/issues/6",
39 shouldSucceed: true,
40 callFormValueBefore: true,
41 inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}},
42 },
43 {
44 description: "Empty payload",
45 shouldSucceed: false,
46 inputAndExpected: BlogPost{},
47 },
48 {
49 description: "Missing required field (Id)",
50 shouldSucceed: false,
51 inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Author: Person{Name: "Matt Holt"}},
52 },
53 {
54 description: "Required embedded struct field not specified",
55 shouldSucceed: false,
56 inputAndExpected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}},
57 },
58 {
59 description: "Required nested struct field not specified",
60 shouldSucceed: false,
61 inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1},
62 },
63 {
64 description: "Multiple values",
65 shouldSucceed: true,
66 inputAndExpected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}, Ratings: []int{3, 5, 4}},
67 },
68 {
69 description: "Bad multipart encoding",
70 shouldSucceed: false,
71 malformEncoding: true,
72 },
73 }
74
75 func Test_MultipartForm(t *testing.T) {
76 for _, testCase := range multipartFormTestCases {
77 performMultipartFormTest(t, MultipartForm, testCase)
78 }
79 }
80
81 func performMultipartFormTest(t *testing.T, binder handlerFunc, testCase multipartFormTestCase) {
82 httpRecorder := httptest.NewRecorder()
83 m := chi.NewRouter()
84
85 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
86 var actual BlogPost
87 errs := binder(req, &actual)
88 if testCase.shouldSucceed {
89 assert.Empty(t, errs)
90 } else if !testCase.shouldSucceed {
91 assert.NotEmpty(t, errs)
92 }
93 assert.Equal(t, fmt.Sprintf("%+v", testCase.inputAndExpected), fmt.Sprintf("%+v", actual))
94 })
95
96 multipartPayload, mpWriter := makeMultipartPayload(testCase)
97
98 req, err := http.NewRequest("POST", testRoute, multipartPayload)
99 if err != nil {
100 panic(err)
101 }
102
103 req.Header.Add("Content-Type", mpWriter.FormDataContentType())
104
105 err = mpWriter.Close()
106 if err != nil {
107 panic(err)
108 }
109
110 if testCase.callFormValueBefore {
111 req.FormValue("foo")
112 }
113
114 m.ServeHTTP(httpRecorder, req)
115
116 switch httpRecorder.Code {
117 case http.StatusNotFound:
118 panic("Routing is messed up in test fixture (got 404): check methods and paths")
119 case http.StatusInternalServerError:
120 panic("Something bad happened on '" + testCase.description + "'")
121 }
122 }
123
124 // Writes the input from a test case into a buffer using the multipart writer.
125 func makeMultipartPayload(testCase multipartFormTestCase) (*bytes.Buffer, *multipart.Writer) {
126 body := &bytes.Buffer{}
127 writer := multipart.NewWriter(body)
128 if testCase.malformEncoding {
129 // TODO: Break the multipart form parser which is apparently impervious!!
130 // (Get it to return an error. Trying to get 100% test coverage.)
131 body.Write([]byte(`--` + writer.Boundary() + `\nContent-Disposition: form-data; name="foo"\n\n--` + writer.Boundary() + `--`))
132 return body, writer
133 }
134 _ = writer.WriteField("title", testCase.inputAndExpected.Title)
135 _ = writer.WriteField("content", testCase.inputAndExpected.Content)
136 _ = writer.WriteField("id", strconv.Itoa(testCase.inputAndExpected.Id))
137 _ = writer.WriteField("ignored", testCase.inputAndExpected.Ignored)
138 for _, value := range testCase.inputAndExpected.Ratings {
139 _ = writer.WriteField("rating", strconv.Itoa(value))
140 }
141 _ = writer.WriteField("name", testCase.inputAndExpected.Author.Name)
142 _ = writer.WriteField("email", testCase.inputAndExpected.Author.Email)
143 return body, writer
144 }
145
146 type (
147 multipartFormTestCase struct {
148 description string
149 shouldSucceed bool
150 inputAndExpected BlogPost
151 malformEncoding bool
152 callFormValueBefore bool
153 }
154 )