-
Notifications
You must be signed in to change notification settings - Fork 50
/
test_http_client.go
59 lines (47 loc) · 937 Bytes
/
test_http_client.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
package exec
import (
"fmt"
"net/http"
"time"
)
func NewTestHttpClient(timeout time.Duration, trips Trips) http.Client {
return http.Client{
Timeout: timeout,
Transport: NewTestRoundTripper(trips...),
}
}
type Trips []Trip
type Trip struct {
duration time.Duration
err error
}
func DoTrip(duration time.Duration, err error) Trip {
return Trip{
duration: duration,
err: err,
}
}
type TestRoundTripper struct {
trips []Trip
current int
}
func NewTestRoundTripper(trips ...Trip) *TestRoundTripper {
return &TestRoundTripper{
trips: trips,
current: 0,
}
}
func (t *TestRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
defer func() {
t.current++
}()
if t.current >= len(t.trips) {
return nil, fmt.Errorf("out of trips")
}
trip := t.trips[t.current]
time.Sleep(trip.duration)
if trip.err != nil {
return nil, trip.err
}
return &http.Response{}, nil
}