-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequests_test.go
86 lines (72 loc) · 2.11 KB
/
requests_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
package intake
import (
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func TestContextHelpers(t *testing.T) {
t.Run("Test context with struct", func(t *testing.T) {
type fake struct {
UserName string
Address string
}
testEp := fmt.Sprintf("/%s", RandStringRunes(20))
var app = NewDefault()
testHandler := func(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
var f fake
FromContext(r, "key", &f)
RespondJSON(w, r, http.StatusOK, f)
}
app.AddEndpoint(http.MethodGet, testEp, testHandler, wrap("key", fake{
UserName: "tom",
Address: "addr",
}))
r := httptest.NewRequest(http.MethodGet, testEp, nil)
w := httptest.NewRecorder()
app.Router.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Code)
resp, _ := ioutil.ReadAll(w.Body)
assert.JSONEq(t, `{"Address":"addr", "UserName":"tom"}`, string(resp))
})
t.Run("Test context with string", func(t *testing.T) {
testEp := fmt.Sprintf("/%s", RandStringRunes(20))
var app = NewDefault()
testHandler := func(w http.ResponseWriter, r *http.Request, param httprouter.Params) {
var s string
FromContext(r, "key", &s)
Respond(w, r, http.StatusOK, []byte(s))
}
app.AddEndpoint(http.MethodGet, testEp, testHandler, wrap("key", "hello"))
r := httptest.NewRequest(http.MethodGet, testEp, nil)
w := httptest.NewRecorder()
app.Router.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Code)
resp, _ := ioutil.ReadAll(w.Body)
assert.Equal(t, "hello", string(resp))
})
}
func wrap(key string, val interface{}) func(next Handler) Handler {
return func(next Handler) Handler {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
AddToContext(r, key, val)
next(w, r, params)
}
}
}