-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary_test.go
80 lines (69 loc) · 1.54 KB
/
library_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
package main // should be "package library", but gonew doesn't support it
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type httpClientMock struct {
mock.Mock
}
func (h *httpClientMock) Do(req *http.Request) (*http.Response, error) {
args := h.Called(req)
return args.Get(0).(*http.Response), args.Error(1)
}
type closingBuffer struct {
*bytes.Buffer
}
func (cb *closingBuffer) Close() error {
return nil
}
func TestSomething(t *testing.T) {
// record HTTP request
httpClient := new(httpClientMock)
httpClient.
On("Do", mock.MatchedBy(func(req *http.Request) bool {
return req.Method == http.MethodPost &&
req.URL.String() == "https://server.io/api" &&
req.Header.Get("User-Agent") == "library/1.0 (go1.16.5/darwin)" &&
req.Header.Get("Content-Type") == "application/json" &&
req.Header.Get("Accept") == "application/json" &&
string(mustRead(req.Body)) == `{"field":"req"}`
})).
Return(
&http.Response{
StatusCode: http.StatusOK,
Body: &closingBuffer{
bytes.NewBufferString(`{"field":"resp"}`),
},
},
nil,
)
client, err := NewMyStruct(
httpClient,
"library/1.0 (go1.16.5/darwin)",
"https://server.io/api",
)
assert.NoError(t, err)
resp, err := client.DoSomething(MyRequest{
Field: "req",
})
assert.NoError(t, err)
assert.Equal(
t,
&MyResponse{
Field: "resp",
},
resp,
)
}
func mustRead(r io.ReadCloser) []byte {
defer r.Close()
b, err := io.ReadAll(r)
if err != nil {
panic(err)
}
return b
}