-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutput_test.go
363 lines (308 loc) · 12 KB
/
output_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// SPDX-FileCopyrightText: 2018-2024 caixw
//
// SPDX-License-Identifier: MIT
package web
import (
"bytes"
"compress/flate"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/issue9/assert/v4"
"github.com/issue9/mux/v9/header"
"github.com/issue9/mux/v9/types"
"golang.org/x/text/language"
"github.com/issue9/web/internal/qheader"
)
type response struct {
http.ResponseWriter
w io.Writer
}
func (r *response) Write(data []byte) (int, error) { return r.w.Write(data) }
func TestContext_Render(t *testing.T) {
a := assert.New(t, false)
srv := newTestServer(a)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.ContentType, header.JSON)
r.Header.Set(header.Accept, header.JSON)
ctx := srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx)
ctx.Render(http.StatusCreated, objectInst)
a.Equal(w.Result().StatusCode, http.StatusCreated).
Equal(w.Header().Get(header.ContentType), qheader.BuildContentType(header.JSON, header.UTF8)).
Equal(w.Header().Get(header.ContentLanguage), "zh-Hans")
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "")
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx)
ctx.Render(http.StatusCreated, objectInst)
a.Equal(w.Result().StatusCode, http.StatusCreated).
Equal(w.Header().Get(header.ContentLanguage), language.SimplifiedChinese.String()).
Equal(w.Body.String(), objectJSONString)
// 输出 nil,content-type 和 content-language 均为空
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "zh-hans")
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx)
ctx.Render(http.StatusCreated, nil)
a.Equal(w.Result().StatusCode, http.StatusCreated).
Equal(w.Header().Get(header.ContentLanguage), ""). // 指定了输出语言,也返回空。
Equal(w.Header().Get(header.ContentType), "")
// accept,accept-language,accept-charset
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "zh-hans")
r.Header.Set(header.AcceptCharset, "gbk")
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx)
ctx.Render(http.StatusCreated, objectInst)
a.Equal(w.Body.Bytes(), objectGBKBytes)
// 同时指定了 accept,accept-language,accept-charset 和 accept-encoding
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "zh-hans")
r.Header.Set(header.AcceptCharset, "gbk")
r.Header.Set(header.AcceptEncoding, "deflate")
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx)
ctx.Render(http.StatusCreated, objectInst)
srv.freeContext(ctx)
a.Equal(w.Result().StatusCode, http.StatusCreated).
Equal(w.Header().Get(header.ContentEncoding), "deflate")
data, err := io.ReadAll(flate.NewReader(w.Body))
a.NotError(err).Equal(data, objectGBKBytes)
// 同时通过 ctx.Write 和 ctx.Marshal 输出内容
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx)
n, err := ctx.Write([]byte("123"))
a.NotError(err).True(n > 0)
a.PanicString(func() {
ctx.Render(http.StatusCreated, "456")
}, "已有状态码 200,再次设置无效 201")
srv.freeContext(ctx)
a.Equal(w.Result().StatusCode, http.StatusOK).Equal(w.Body.String(), `123`)
// ctx.Write 在 ctx.Marshal 之后可以正常调用。
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
ctx = srv.NewContext(w, r, types.NewContext())
ctx.Render(http.StatusCreated, "123")
n, err = ctx.Write([]byte("123"))
a.NotError(err)
srv.freeContext(ctx)
a.True(n > 0).
Equal(w.Body.String(), `"123"123`)
// outputMimetype.Marshal 返回 ErrUnsupported
srv.logBuf.Reset()
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, "application/test")
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx, srv.logBuf.String()).
Equal(ctx.Mimetype(false), "application/test").
Equal(ctx.Charset(), header.UTF8)
ctx.Render(http.StatusCreated, "任意值")
srv.freeContext(ctx)
a.Equal(w.Result().StatusCode, http.StatusNotAcceptable)
// outputMimetype.Marshal 返回错误
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, "application/test")
ctx = srv.NewContext(w, r, types.NewContext())
a.NotNil(ctx).
Equal(ctx.Mimetype(false), "application/test").
Equal(ctx.Charset(), header.UTF8)
ctx.Render(http.StatusCreated, errors.New("error"))
srv.freeContext(ctx)
a.Equal(w.Result().StatusCode, http.StatusNotAcceptable)
}
func TestContext_Wrap(t *testing.T) {
a := assert.New(t, false)
s := newTestServer(a)
// 输出内容之后,不能调用 Wrap
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "cmn-hant")
ctx := s.NewContext(w, r, types.NewContext())
_, err := ctx.Write([]byte("abc"))
a.NotError(err)
a.PanicString(func() {
buf := &bytes.Buffer{}
ctx.Wrap(func(w http.ResponseWriter) http.ResponseWriter { return &response{w: buf, ResponseWriter: w} })
}, "已有内容输出,不可再更改!")
a.Equal(w.Body.String(), "abc")
// 调用 Wrap 之后修改了报头内容
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "cmn-hant")
r.Header.Set(header.AcceptEncoding, "")
ctx = s.NewContext(w, r, types.NewContext())
ctx.Header().Set("h1", "v1")
buf := &bytes.Buffer{}
ctx.Wrap(func(w http.ResponseWriter) http.ResponseWriter { return &response{w: buf, ResponseWriter: w} })
ctx.Header().Set("h2", "v2")
_, err = ctx.Write([]byte("abc"))
a.NotError(err).Equal(buf.String(), "abc").
Equal(w.Header().Get("h1"), "v1").
Equal(w.Header().Get("h2"), "v2").
Empty(w.Body.String())
// 多次调用 Wrap
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p1", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "cmn-hant")
r.Header.Set(header.AcceptEncoding, "")
ctx = s.NewContext(w, r, types.NewContext())
a.PanicString(func() { // Wrap(nil)
ctx.Wrap(nil)
}, "参数 f 不能为空")
buf1 := &bytes.Buffer{}
buf2 := &bytes.Buffer{}
ctx.Wrap(func(w http.ResponseWriter) http.ResponseWriter { return &response{w: buf1, ResponseWriter: w} })
ctx.Wrap(func(w http.ResponseWriter) http.ResponseWriter { return &response{w: buf2, ResponseWriter: w} })
_, err = ctx.Write([]byte("abc"))
a.NotError(err).Equal(buf2.String(), "abc").Empty(buf1.String()).
True(w.Result().StatusCode > 199).
Empty(w.Body.String())
}
func TestContext_LocalePrinter(t *testing.T) {
a := assert.New(t, false)
srv := newTestServer(a)
b := srv.Locale()
a.NotError(b.SetString(language.MustParse("cmn-hans"), "test", "测试"))
a.NotError(b.SetString(language.MustParse("cmn-hant"), "test", "測試"))
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "cmn-hant")
ctx := srv.NewContext(w, r, types.NewContext())
ctx.Render(http.StatusOK, ctx.Sprintf("test"))
a.Equal(w.Body.String(), `"測試"`)
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.Accept, header.JSON)
r.Header.Set(header.AcceptLanguage, "cmn-hans")
ctx = srv.NewContext(w, r, types.NewContext())
n, err := ctx.LocalePrinter().Fprintf(ctx, "test")
a.NotError(err).Equal(n, len("测试")).Equal(w.Body.String(), "测试")
}
func TestNotModified(t *testing.T) {
a := assert.New(t, false)
s := newTestServer(a)
// weak
const body = "string"
nm := NotModified(
func() (string, bool) { return body, true },
func() (any, error) { return body, nil },
)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p", nil)
s.NewContext(w, r, types.NewContext()).apply(nm)
tag := w.Header().Get(header.ETag)
a.Equal(w.Result().StatusCode, http.StatusOK).NotEmpty(tag).
Equal(w.Result().Header.Get("Content-Type"), "application/json; charset=utf-8")
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.IfNoneMatch, tag)
s.NewContext(w, r, types.NewContext()).apply(nm)
a.Equal(w.Result().StatusCode, http.StatusNotModified)
// Post 不启用
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodPost, "/p", nil)
s.NewContext(w, r, types.NewContext()).apply(nm)
tag = w.Header().Get(header.ETag)
a.Equal(w.Result().StatusCode, http.StatusOK).Empty(tag)
// weak=false
nm = NotModified(
func() (string, bool) { return body, false },
func() (any, error) { return []byte(body), nil },
)
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
s.NewContext(w, r, types.NewContext()).apply(nm)
tag = w.Header().Get(header.ETag)
a.Equal(w.Result().StatusCode, http.StatusOK).NotEmpty(tag)
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.IfNoneMatch, tag)
s.NewContext(w, r, types.NewContext()).apply(nm)
a.Equal(w.Result().StatusCode, http.StatusNotModified)
// error
nm = NotModified(
func() (string, bool) { return body, false },
func() (any, error) { return nil, errors.New("500") },
)
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
s.NewContext(w, r, types.NewContext()).apply(nm)
a.Equal(w.Result().StatusCode, http.StatusInternalServerError)
}
func TestCreated(t *testing.T) {
a := assert.New(t, false)
s := newTestServer(a)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.Accept, header.JSON)
s.NewContext(w, r, types.NewContext()).
apply(Created(nil, ""))
a.Equal(w.Result().StatusCode, http.StatusCreated).
Empty(w.Body.String())
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.Accept, header.JSON)
s.NewContext(w, r, types.NewContext()).
apply(Created(objectInst, ""))
a.Equal(w.Result().StatusCode, http.StatusCreated).
Equal(w.Body.String(), objectJSONString).
Empty(w.Header().Get(header.Location))
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.Accept, header.JSON)
s.NewContext(w, r, types.NewContext()).
apply(Created(objectInst, "/p2"))
a.Equal(w.Result().StatusCode, http.StatusCreated).
Equal(w.Body.String(), objectJSONString).
Equal(w.Header().Get(header.Location), "/p2")
}
func TestRedirect(t *testing.T) {
a := assert.New(t, false)
s := newTestServer(a)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p", nil)
ctx := s.NewContext(w, r, types.NewContext())
ctx.apply(ctx.NotImplemented())
a.Equal(w.Result().StatusCode, http.StatusNotImplemented)
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/p", nil)
Redirect(http.StatusMovedPermanently, "http://example.com")
s.NewContext(w, r, types.NewContext()).
apply(Redirect(http.StatusMovedPermanently, "http://example.com"))
a.Equal(w.Result().StatusCode, http.StatusMovedPermanently).
Equal(w.Header().Get(header.Location), "http://example.com")
}
func TestNoContent(t *testing.T) {
// 检测 204 是否存在 http: request method or response status code does not allow body
a := assert.New(t, false)
s := newTestServer(a)
s.logBuf.Reset()
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/p", nil)
r.Header.Set(header.AcceptEncoding, "gzip") // 服务端不应该构建压缩对象
r.Header.Set(header.Accept, header.JSON)
s.NewContext(w, r, types.NewContext()).apply(NoContent())
a.NotContains(s.logBuf.String(), "request method or response status code does not allow body")
}