forked from fulldump/apitest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapitest.go
85 lines (69 loc) · 1.47 KB
/
apitest.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
package apitest
import (
"crypto/tls"
"net/http/httptest"
"net/http"
)
type Apitest struct {
Handler http.Handler // handler to test
Server *httptest.Server // testing server
Base string // Base uri to make requests
client *http.Client // Default Http Client to use in requests
clients chan *http.Client // http clients
}
// Deprecated: Please, use NewWithHandler instead
func New(h http.Handler) *Apitest {
return NewWithPool(h, 2)
}
func NewWithBase(base string) *Apitest {
return &Apitest{
client: http.DefaultClient,
Base: base,
}
}
func NewWithHandler(h http.Handler) *Apitest {
return NewWithPool(h, 2)
}
func NewWithPool(h http.Handler, n int) *Apitest {
s := httptest.NewServer(h)
a := &Apitest{
Base: s.URL,
Handler: h,
Server: s,
clients: make(chan *http.Client, n),
client: http.DefaultClient,
}
for i := 0; i < cap(a.clients); i++ {
a.clients <- &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
DisableKeepAlives: false,
},
}
}
return a
}
func (a *Apitest) WithHttpClient(client *http.Client) *Apitest {
a.client = client
if a.clients != nil {
for i := 0; i < cap(a.clients); i++ {
a.clients <- client
}
}
return a
}
func (a *Apitest) Destroy() {
if nil != a.Server {
a.Server.Close()
a.Server = nil
}
}
func (a *Apitest) Request(method, path string) *Request {
return NewRequest(
method,
a.Base+path,
a,
)
}