Debian Codegraph @

json_test.go

raw symbols SCIP
1 // Copyright 2014 Martini Authors
2 // Copyright 2014 The Macaron Authors
3 // Copyright 2024 The Forgejo Authors
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License"): you may
6 // not use this file except in compliance with the License. You may obtain
7 // a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 // License for the specific language governing permissions and limitations
15 // under the License.
16
17 package binding
18
19 import (
20 "fmt"
21 "io"
22 "net/http"
23 "net/http/httptest"
24 "reflect"
25 "runtime"
26 "strings"
27 "testing"
28
29 chi "github.com/go-chi/chi/v5"
30 "github.com/stretchr/testify/assert"
31 )
32
33 var jsonTestCases = []jsonTestCase{
34 {
35 description: "Happy path",
36 shouldSucceedOnJSON: true,
37 payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`,
38 contentType: jsonContentType,
39 expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"},
40 },
41 {
42 description: "Happy path with interface",
43 shouldSucceedOnJSON: true,
44 withInterface: true,
45 payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`,
46 contentType: jsonContentType,
47 expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"},
48 },
49 {
50 description: "Nil payload",
51 shouldSucceedOnJSON: false,
52 payload: `-nil-`,
53 contentType: jsonContentType,
54 expected: Post{},
55 },
56 {
57 description: "Empty payload",
58 shouldSucceedOnJSON: false,
59 payload: ``,
60 contentType: jsonContentType,
61 expected: Post{},
62 },
63 {
64 description: "Empty content type",
65 shouldSucceedOnJSON: true,
66 shouldFailOnBind: true,
67 payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`,
68 contentType: ``,
69 expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"},
70 },
71 {
72 description: "Unsupported content type",
73 shouldSucceedOnJSON: true,
74 shouldFailOnBind: true,
75 payload: `{"title": "Glorious Post Title", "content": "Lorem ipsum dolor sit amet"}`,
76 contentType: `BoGuS`,
77 expected: Post{Title: "Glorious Post Title", Content: "Lorem ipsum dolor sit amet"},
78 },
79 {
80 description: "Malformed JSON",
81 shouldSucceedOnJSON: false,
82 payload: `{"title":"foo"`,
83 contentType: jsonContentType,
84 expected: Post{Title: "foo"},
85 },
86 {
87 description: "Deserialization with nested and embedded struct",
88 shouldSucceedOnJSON: true,
89 payload: `{"title":"Glorious Post Title", "id":1, "author":{"name":"Matt Holt"}}`,
90 contentType: jsonContentType,
91 expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}},
92 },
93 {
94 description: "Deserialization with nested and embedded struct with interface",
95 shouldSucceedOnJSON: true,
96 withInterface: true,
97 payload: `{"title":"Glorious Post Title", "id":1, "author":{"name":"Matt Holt"}}`,
98 contentType: jsonContentType,
99 expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1, Author: Person{Name: "Matt Holt"}},
100 },
101 {
102 description: "Required nested struct field not specified",
103 shouldSucceedOnJSON: false,
104 payload: `{"title":"Glorious Post Title", "id":1, "author":{}}`,
105 contentType: jsonContentType,
106 expected: BlogPost{Post: Post{Title: "Glorious Post Title"}, Id: 1},
107 },
108 {
109 description: "Required embedded struct field not specified",
110 shouldSucceedOnJSON: false,
111 payload: `{"id":1, "author":{"name":"Matt Holt"}}`,
112 contentType: jsonContentType,
113 expected: BlogPost{Id: 1, Author: Person{Name: "Matt Holt"}},
114 },
115 {
116 description: "Slice of Posts",
117 shouldSucceedOnJSON: true,
118 payload: `[{"title": "First Post"}, {"title": "Second Post"}]`,
119 contentType: jsonContentType,
120 expected: []Post{{Title: "First Post"}, {Title: "Second Post"}},
121 },
122 {
123 description: "Slice of structs",
124 shouldSucceedOnJSON: true,
125 payload: `{"name": "group1", "people": [{"name":"awoods"}, {"name": "anthony"}]}`,
126 contentType: jsonContentType,
127 expected: Group{Name: "group1", People: []Person{{Name: "awoods"}, {Name: "anthony"}}},
128 },
129 }
130
131 func Test_Json(t *testing.T) {
132 for _, testCase := range jsonTestCases {
133 performJSONTest(t, JSON, testCase)
134 }
135 }
136
137 func performJSONTest(t *testing.T, binder handlerFunc, testCase jsonTestCase) {
138 fnName := runtime.FuncForPC(reflect.ValueOf(binder).Pointer()).Name()
139 t.Run(testCase.description, func(t *testing.T) {
140 var payload io.Reader
141 httpRecorder := httptest.NewRecorder()
142 m := chi.NewRouter()
143
144 jsonTestHandler := func(actual any, errs Errors) {
145 switch fnName {
146 case "JSON":
147 if testCase.shouldSucceedOnJSON {
148 assert.Empty(t, errs, errs)
149 assert.Equal(t, fmt.Sprintf("%+v", testCase.expected), fmt.Sprintf("%+v", actual))
150 } else {
151 assert.NotEmpty(t, errs)
152 }
153 case "Bind":
154 if !testCase.shouldFailOnBind {
155 assert.Empty(t, errs, errs)
156 } else {
157 assert.NotEmpty(t, errs)
158 assert.Equal(t, fmt.Sprintf("%+v", testCase.expected), fmt.Sprintf("%+v", actual))
159 }
160 }
161 }
162
163 switch p := testCase.expected.(type) {
164 case []Post:
165 if testCase.withInterface {
166 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
167 var actual []Post
168 errs := binder(req, &actual)
169 for i, a := range actual {
170 assert.Equal(t, p[i].Title, a.Title)
171 jsonTestHandler(a, errs)
172 }
173 })
174 } else {
175 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
176 var actual []Post
177 errs := binder(req, &actual)
178 jsonTestHandler(actual, errs)
179 })
180 }
181
182 case Post:
183 if testCase.withInterface {
184 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
185 var actual Post
186 errs := binder(req, &actual)
187 assert.Equal(t, p.Title, actual.Title)
188 jsonTestHandler(actual, errs)
189 })
190 } else {
191 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
192 var actual Post
193 errs := binder(req, &actual)
194 jsonTestHandler(actual, errs)
195 })
196 }
197
198 case BlogPost:
199 if testCase.withInterface {
200 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
201 var actual BlogPost
202 errs := binder(req, &actual)
203 assert.Equal(t, p.Title, actual.Title)
204 jsonTestHandler(actual, errs)
205 })
206 } else {
207 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
208 var actual BlogPost
209 errs := binder(req, &actual)
210 jsonTestHandler(actual, errs)
211 })
212 }
213 case Group:
214 if testCase.withInterface {
215 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
216 var actual Group
217 errs := binder(req, &actual)
218 assert.Equal(t, p.Name, actual.Name)
219 jsonTestHandler(actual, errs)
220 })
221 } else {
222 m.Post(testRoute, func(_ http.ResponseWriter, req *http.Request) {
223 var actual Group
224 errs := binder(req, &actual)
225 jsonTestHandler(actual, errs)
226 })
227 }
228 }
229
230 if testCase.payload == "-nil-" {
231 payload = nil
232 } else {
233 payload = strings.NewReader(testCase.payload)
234 }
235
236 req, err := http.NewRequest("POST", testRoute, payload)
237 if err != nil {
238 panic(err)
239 }
240 req.Header.Set("Content-Type", testCase.contentType)
241
242 m.ServeHTTP(httpRecorder, req)
243
244 switch httpRecorder.Code {
245 case http.StatusNotFound:
246 panic("Routing is messed up in test fixture (got 404): check method and path")
247 case http.StatusInternalServerError:
248 panic("Something bad happened on '" + testCase.description + "'")
249 default:
250 if testCase.shouldSucceedOnJSON &&
251 httpRecorder.Code != http.StatusOK &&
252 !testCase.shouldFailOnBind {
253 assert.Equal(t, http.StatusOK, httpRecorder.Code)
254 }
255 }
256 })
257 }
258
259 type (
260 jsonTestCase struct {
261 description string
262 withInterface bool
263 shouldSucceedOnJSON bool
264 shouldFailOnBind bool
265 payload string
266 contentType string
267 expected any
268 }
269 )