-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtest_utils.go
100 lines (86 loc) · 2.15 KB
/
test_utils.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
package ucon
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
// BubbleTestOption is an option for setting a mock request.
type BubbleTestOption struct {
Method string
URL string
ContentType string
Body io.Reader
MiddlewareContext Context
}
// MakeMiddlewareTestBed returns a Bubble and ServeMux for handling the request made from the option.
func MakeMiddlewareTestBed(t *testing.T, middleware MiddlewareFunc, handler interface{}, opts *BubbleTestOption) (*Bubble, *ServeMux) {
if opts == nil {
opts = &BubbleTestOption{
Method: "GET",
URL: "/api/tmp",
}
}
if opts.MiddlewareContext == nil {
opts.MiddlewareContext = background
}
mux := NewServeMux()
mux.Middleware(middleware)
r, err := http.NewRequest(opts.Method, opts.URL, opts.Body)
if err != nil {
t.Fatal(err)
}
if opts.Body != nil {
if opts.ContentType != "" {
r.Header.Add("Content-Type", opts.ContentType)
} else {
r.Header.Add("Content-Type", "application/json")
}
}
w := httptest.NewRecorder()
u, err := url.Parse(opts.URL)
if err != nil {
t.Fatal(err)
}
rd := &RouteDefinition{
Method: opts.Method,
PathTemplate: ParsePathTemplate(u.Path),
HandlerContainer: &handlerContainerImpl{
handler: handler,
Context: opts.MiddlewareContext,
},
}
b, err := mux.newBubble(context.Background(), w, r, rd)
if err != nil {
t.Fatal(err)
}
return b, mux
}
// MakeHandlerTestBed returns a response by the request made from arguments.
// To test some handlers, those must be registered by Handle or HandleFunc before calling this.
func MakeHandlerTestBed(t *testing.T, method string, path string, body io.Reader) *http.Response {
ts := httptest.NewServer(DefaultMux)
defer ts.Close()
reqURL, err := url.Parse(ts.URL)
if err != nil {
t.Fatal(err)
}
reqURL, err = reqURL.Parse(path)
if err != nil {
t.Fatal(err)
}
req, err := http.NewRequest(method, reqURL.String(), body)
if err != nil {
t.Fatal(err)
}
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}