-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_test.go
83 lines (72 loc) · 2.31 KB
/
parse_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
package chirp
import (
"bytes"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/go-chi/chi"
"github.com/satori/go.uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParse(t *testing.T) {
router := chi.NewRouter()
router.Put("/user/{id}/name", func(w http.ResponseWriter, r *http.Request) {
var data struct {
ID uuid.UUID `path:"id"`
Name string `json:"name"`
Part string `query:"part"`
Priority uint8 `json:"priority"`
Null string `json:"-"`
Hero string
}
require.NoError(t, Parse(r, &data))
assert.EqualValues(t, uuid.FromStringOrNil("6b245e15-5c88-438b-a170-d8f97460083a"), data.ID)
assert.Equal(t, "John", data.Name)
assert.Equal(t, "last", data.Part)
assert.Empty(t, "", data.Null)
assert.Equal(t, "Joker", data.Hero)
assert.EqualValues(t, 5, data.Priority)
})
t.Run("json", func(t *testing.T) {
body := bytes.NewBufferString(`{"name": "John", "priority": 5, "Hero": "Joker"}`)
req := httptest.NewRequest(http.MethodPut, "/user/6b245e15-5c88-438b-a170-d8f97460083a/name?part=last", body)
res := httptest.NewRecorder()
router.ServeHTTP(res, req)
})
t.Run("form", func(t *testing.T) {
form := &url.Values{}
form.Add("name", "John")
form.Add("priority", "5")
form.Add("Hero", "Joker")
body := bytes.NewBufferString(form.Encode())
req := httptest.NewRequest(http.MethodPut, "/user/6b245e15-5c88-438b-a170-d8f97460083a/name?part=last", body)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res := httptest.NewRecorder()
router.ServeHTTP(res, req)
})
}
func BenchmarkParse(b *testing.B) {
router := chi.NewRouter()
type Data struct {
ID uuid.UUID `path:"id"`
Name string `json:"name"`
Part string `query:"part"`
Priority uint8 `json:"priority"`
Null string `json:"-"`
Hero string
}
router.Put("/user/{id}/name", func(w http.ResponseWriter, r *http.Request) {
data := Data{}
Parse(r, &data)
_ = data
})
body := bytes.NewBufferString(`{"name": "John", "priority": 5, "Hero": "Joker"}`)
req := httptest.NewRequest(http.MethodPut, "/user/6b245e15-5c88-438b-a170-d8f97460083a/name?part=last", body)
b.StartTimer()
for i := 0; i < b.N; i++ {
res := httptest.NewRecorder()
router.ServeHTTP(res, req)
}
}