-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_test.go
87 lines (62 loc) · 1.67 KB
/
context_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
package summer
import (
"github.com/stretchr/testify/require"
"net/http"
"net/http/httptest"
"testing"
)
func TestBind(t *testing.T) {
var hello string
a := Basic()
a.HandleFunc("/test", func(c Context) {
args := Bind[struct {
Hello string `json:"query_hello"`
}](c)
hello = args.Hello
})
req := httptest.NewRequest("GET", "https://example.com/test?hello=world", nil)
a.ServeHTTP(httptest.NewRecorder(), req)
require.Equal(t, "world", hello)
}
func TestContext(t *testing.T) {
req := httptest.NewRequest("GET", "https://example.com/get?aaa=bbb", nil)
rw := httptest.NewRecorder()
ctx := BasicContext(rw, req)
func() {
defer ctx.Perform()
type Request struct {
AAA string `json:"aaa"`
}
var r Request
ctx.Bind(&r)
require.Equal(t, "bbb", r.AAA)
ctx.Code(http.StatusTeapot)
ctx.Text("OK")
}()
rw.Flush()
require.Equal(t, http.StatusTeapot, rw.Code)
require.Equal(t, "text/plain; charset=utf-8", rw.Header().Get("Content-Type"))
require.Equal(t, "2", rw.Header().Get("Content-Length"))
require.Equal(t, "OK", rw.Body.String())
}
func TestContextPanic(t *testing.T) {
req := httptest.NewRequest("GET", "https://example.com/get?aaa=bbb", nil)
rw := httptest.NewRecorder()
ctx := BasicContext(rw, req)
func() {
defer ctx.Perform()
type Request struct {
AAA string `json:"aaa"`
}
var r Request
ctx.Bind(&r)
require.Equal(t, "bbb", r.AAA)
panic("WWW")
ctx.Code(http.StatusTeapot)
ctx.Text("OK")
}()
rw.Flush()
require.Equal(t, http.StatusInternalServerError, rw.Code)
require.Equal(t, "application/json; charset=utf-8", rw.Header().Get("Content-Type"))
require.Equal(t, `{"message":"panic: WWW"}`, rw.Body.String())
}