-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinspector_test.go
104 lines (76 loc) · 1.95 KB
/
inspector_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 requester
import (
"bytes"
"fmt"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io/ioutil"
"net/http"
"strings"
"testing"
)
func TestInspector(t *testing.T) {
var dumpedReqBody []byte
var doer DoerFunc = func(req *http.Request) (*http.Response, error) {
dumpedReqBody, _ = ioutil.ReadAll(req.Body)
resp := &http.Response{
StatusCode: 201,
Body: ioutil.NopCloser(strings.NewReader("pong")),
}
return resp, nil
}
i := Inspector{}
resp, body, err := Receive(&i, doer, Body("ping"))
require.NoError(t, err)
assert.Equal(t, 201, resp.StatusCode)
assert.Equal(t, "pong", string(body))
require.NotNil(t, i.Request)
assert.Equal(t, "ping", i.RequestBody.String())
assert.Equal(t, "ping", string(dumpedReqBody))
require.NotNil(t, i.Response)
assert.Equal(t, 201, i.Response.StatusCode)
assert.Equal(t, "pong", i.ResponseBody.String())
}
func TestInspector_Clear(t *testing.T) {
i := Inspector{
Request: &http.Request{},
Response: &http.Response{},
RequestBody: bytes.NewBuffer(nil),
ResponseBody: bytes.NewBuffer(nil),
}
i.Clear()
assert.Nil(t, i.Request)
assert.Nil(t, i.Response)
assert.Nil(t, i.RequestBody)
assert.Nil(t, i.ResponseBody)
assert.NotPanics(t, func() {
(*Inspector)(nil).Clear()
})
}
func TestInspect(t *testing.T) {
r := MustNew()
i := Inspect(r)
r.Receive(MockDoer(201))
assert.NotNil(t, i.Request)
assert.Equal(t, 201, i.Response.StatusCode)
}
// Inspect returns an Inspector, which captures the traffic to and from a Requester. It's
// a tool for writing tests.
func ExampleInspect() {
r := MustNew(
MockDoer(201, Body("pong")),
Header(HeaderAccept, MediaTypeTextPlain),
Body("ping"),
)
i := Inspect(r)
r.Receive(nil)
fmt.Println(i.Request.Header.Get(HeaderAccept))
fmt.Println(i.RequestBody.String())
fmt.Println(i.Response.StatusCode)
fmt.Println(i.ResponseBody.String())
// Output:
// text/plain
// ping
// 201
// pong
}