-
Notifications
You must be signed in to change notification settings - Fork 10
/
doubles.go
61 lines (52 loc) · 1.6 KB
/
doubles.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
package httpspec
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/adamluzsi/testcase"
)
type RoundTripperFunc func(r *http.Request) (*http.Response, error)
func (fn RoundTripperFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return fn(request)
}
func LetRoundTripperDouble(s *testcase.Spec) testcase.Var[*RoundTripperDouble] {
return testcase.Let(s, func(t *testcase.T) *RoundTripperDouble {
return &RoundTripperDouble{}
})
}
type RoundTripperDouble struct {
// RoundTripperFunc is an optional argument in case you want to stub the response
RoundTripperFunc RoundTripperFunc
// ReceivedRequests hold all the received http request.
ReceivedRequests []*http.Request
}
func (d *RoundTripperDouble) RoundTrip(r *http.Request) (*http.Response, error) {
d.ReceivedRequests = append(d.ReceivedRequests, r.Clone(r.Context()))
if d.RoundTripperFunc != nil {
return d.RoundTripperFunc(r)
}
const code = http.StatusOK
return &http.Response{
Status: http.StatusText(code),
StatusCode: code,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: http.Header{},
Body: io.NopCloser(bytes.NewReader([]byte{})),
ContentLength: 0,
TransferEncoding: nil,
Close: false,
Uncompressed: false,
Trailer: nil,
Request: r,
TLS: nil,
}, nil
}
func (d *RoundTripperDouble) LastReceivedRequest(tb testing.TB) *http.Request {
if len(d.ReceivedRequests) == 0 {
tb.Fatalf("%T did not received any *http.Request", *d)
}
return d.ReceivedRequests[len(d.ReceivedRequests)-1]
}