-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers_test.go
104 lines (92 loc) · 2.24 KB
/
helpers_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
package nvelope_test
import (
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
"github.com/muir/nape"
"github.com/muir/nvelope"
"github.com/gorilla/mux"
)
// nolint:deadcode,unused
func setupTestService(path string, f interface{}) func(string, ...mod) {
return captureOutputFunc(func(i ...interface{}) {
fmt.Println(i...)
}, path, f)
}
func captureOutput(path string, f interface{}) func(string, ...mod) string {
var o string
do := captureOutputFunc(func(i ...interface{}) {
o += fmt.Sprint(i...)
}, path, f)
return func(url string, mods ...mod) string {
o = ""
do(url, mods...)
return o
}
}
type mod func(*http.Request, *http.Client, *httptest.Server)
func body(s string) mod {
return func(r *http.Request, cl *http.Client, ts *httptest.Server) {
r.Body = io.NopCloser(strings.NewReader(s))
}
}
func cookie(k, v string) mod {
return func(r *http.Request, cl *http.Client, ts *httptest.Server) {
cl.Jar.SetCookies(r.URL, []*http.Cookie{
{Name: k, Value: v},
})
}
}
func header(k, v string) mod {
return func(r *http.Request, cl *http.Client, ts *httptest.Server) {
r.Header[k] = append(r.Header[k], v)
}
}
func captureOutputFunc(out func(...interface{}), path string, f interface{}) func(string, ...mod) {
router := mux.NewRouter()
service := nape.RegisterServiceWithMux("example", router)
service.RegisterEndpoint(path,
// order matters and this is a correct order
nvelope.NoLogger,
nvelope.InjectWriter,
nvelope.EncodeJSON,
nvelope.CatchPanic,
nvelope.Nil204,
nvelope.ReadBody,
nape.DecodeJSON,
f,
).Methods("POST")
ts := httptest.NewServer(router)
return func(url string, mods ...mod) {
client := ts.Client()
var err error
client.Jar, err = cookiejar.New(&cookiejar.Options{})
if err != nil {
panic("jar")
}
// nolint:noctx
req, err := http.NewRequest("POST", ts.URL+url, io.NopCloser(strings.NewReader("")))
if err != nil {
panic("request")
}
for _, m := range mods {
m(req, client, ts)
}
// nolint:noctx
res, err := client.Do(req)
if err != nil {
out("response error:", err)
return
}
b, err := io.ReadAll(res.Body)
if err != nil {
out("read error:", err)
return
}
res.Body.Close()
out(res.StatusCode, "->"+string(b))
}
}