-
Notifications
You must be signed in to change notification settings - Fork 3
/
send_request_test.go
128 lines (115 loc) · 2.75 KB
/
send_request_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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package vertexai
import (
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type httpMock1 struct{}
func (hm *httpMock1) Do(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader("{\"success\": true}")),
}, nil
}
type httpMock2 struct{}
func (hm *httpMock2) Do(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 400,
Body: io.NopCloser(strings.NewReader("error calling http client")),
}, nil
}
type httpMock3 struct{}
func (hm *httpMock3) Do(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("error calling http client")
}
type httpMock4 struct{}
func (hm *httpMock4) Do(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader("{\"success\": \"true\"}")),
}, nil
}
type tokenMockSuccess struct{}
func (*tokenMockSuccess) getToken(string) (string, error) {
return "", nil
}
func Test_client_sendRequest(t *testing.T) {
httpReq, err := http.NewRequest("method", "url", nil)
if err != nil {
t.Errorf("failed to create http request: %v", err)
}
type respStruct struct {
Success bool `json:"success"`
}
tests := []struct {
name string
req *http.Request
want *respStruct
wantErr bool
mockHTTPClient httpClient
mockTokenizer tokenizer
}{
{
name: "success",
req: httpReq,
want: &respStruct{
Success: true,
},
wantErr: false,
mockHTTPClient: &httpMock1{},
mockTokenizer: &tokenMockSuccess{},
},
{
name: "error response from http client",
req: httpReq,
wantErr: true,
mockHTTPClient: &httpMock2{},
mockTokenizer: &tokenMockSuccess{},
},
{
name: "error in calling http client",
req: httpReq,
wantErr: true,
mockHTTPClient: &httpMock3{},
mockTokenizer: &tokenMockSuccess{},
},
{
name: "error decoding response",
req: httpReq,
want: &respStruct{
Success: false,
},
wantErr: true,
mockHTTPClient: &httpMock4{},
mockTokenizer: &tokenMockSuccess{},
},
{
name: "error get token",
req: httpReq,
want: nil,
wantErr: true,
mockTokenizer: &defaultTokenizer{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &client{
clientConfig: clientConfig{
authToken: "test_token",
},
httpClient: tt.mockHTTPClient,
tokenizer: tt.mockTokenizer,
}
got := &respStruct{}
if tt.want == nil {
got = nil
}
err := c.sendRequest(tt.req, got)
assert.Equal(t, tt.wantErr, err != nil)
assert.Equal(t, tt.want, got)
})
}
}