-
Notifications
You must be signed in to change notification settings - Fork 8
/
reader_test.go
112 lines (102 loc) · 2.3 KB
/
reader_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
package routing
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
)
type FA struct {
A1 string
A2 int
}
type FB struct {
B1 string
B2 bool
B3 float64
}
func TestReadForm(t *testing.T) {
var a struct {
X1 string `form:"x1"`
FA
X2 int
B *FB
FB `form:"c"`
E FB `form:"e"`
c int
D []int
}
values := map[string][]string{
"x1": {"abc", "123"},
"A1": {"a1"},
"x2": {"1", "2"},
"B.B1": {"b1", "b2"},
"B.B2": {"true"},
"B.B3": {"1.23"},
"c.B1": {"fb1", "fb2"},
"e.B1": {"fe1", "fe2"},
"c": {"100"},
"D": {"100", "200", "300"},
}
err := ReadFormData(values, &a)
assert.Nil(t, err)
assert.Equal(t, "abc", a.X1)
assert.Equal(t, "a1", a.A1)
assert.Equal(t, 0, a.X2)
assert.Equal(t, "b1", a.B.B1)
assert.True(t, a.B.B2)
assert.Equal(t, 1.23, a.B.B3)
assert.Equal(t, "fb1", a.B1)
assert.Equal(t, "fe1", a.E.B1)
assert.Equal(t, 0, a.c)
assert.Equal(t, []int{100, 200, 300}, a.D)
}
func TestDefaultDataReader(t *testing.T) {
tests := []struct {
tag string
header string
method, URL string
body string
}{
{"t1", "", "GET", "/test?A1=abc&A2=100", ""},
{"t2", "", "POST", "/test?A1=abc&A2=100", ""},
{"t3", "application/x-www-form-urlencoded", "POST", "/test", "A1=abc&A2=100"},
{"t4", "application/json", "POST", "/test", `{"A1":"abc","A2":100}`},
{"t5", "application/xml", "POST", "/test", `<data><A1>abc</A1><A2>100</A2></data>`},
}
expected := FA{
A1: "abc",
A2: 100,
}
for _, test := range tests {
var data FA
var ctx fasthttp.RequestCtx
ctx.Request.Header.SetMethod(test.method)
ctx.Request.SetRequestURI(test.URL)
ctx.Request.SetBodyString(test.body)
ctx.Request.Header.SetContentType(test.header)
c := NewContext(&ctx)
err := c.Read(&data)
assert.Nil(t, err, test.tag)
assert.Equal(t, expected, data, test.tag)
}
}
type TU struct {
UValue string
}
func (tu *TU) UnmarshalText(text []byte) error {
tu.UValue = "TU_" + string(text[:])
return nil
}
func TestTextUnmarshaler(t *testing.T) {
var a struct {
ATU TU `form:"atu"`
NTU string `form:"ntu"`
}
values := map[string][]string{
"atu": {"ORIGINAL"},
"ntu": {"ORIGINAL"},
}
err := ReadFormData(values, &a)
assert.Nil(t, err)
assert.Equal(t, "TU_ORIGINAL", a.ATU.UValue)
assert.Equal(t, "ORIGINAL", a.NTU)
}