-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient_test.go
334 lines (278 loc) · 10.4 KB
/
client_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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package megaport
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/suite"
)
var (
ctx = context.TODO()
)
// ClientTestSuite tests the Megaport SDK Client.
type ClientTestSuite struct {
suite.Suite
client *Client
server *httptest.Server
mux *http.ServeMux
}
func TestClientTestSuite(t *testing.T) {
t.Parallel()
suite.Run(t, new(ClientTestSuite))
}
func (suite *ClientTestSuite) SetupTest() {
suite.mux = http.NewServeMux()
suite.server = httptest.NewServer(suite.mux)
suite.client = NewClient(nil, nil)
url, _ := url.Parse(suite.server.URL)
suite.client.BaseURL = url
}
func (suite *ClientTestSuite) TearDownTest() {
suite.server.Close()
}
// testURLParseError tests if the error is a URL parse error.
func (suite *ClientTestSuite) testURLParseError(err error) {
if err == nil {
suite.FailNow("Expected error to be returned")
}
if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
suite.FailNowf("Expected URL parse error, got %+v", err.Error())
}
}
// testClientDefaultBaseURL tests if the client's default base URL is set to the defaultBaseURL.
func (suite *ClientTestSuite) testClientDefaultBaseURL(c *Client) {
if c.BaseURL == nil || c.BaseURL.String() != string(defaultBaseURL) {
suite.FailNowf("NewClient BaseURL = %v, expected %v", c.BaseURL.String(), defaultBaseURL)
}
}
// testClientDefaultUserAgent tests if the client's default user agent is set to the userAgent.
func (suite *ClientTestSuite) testClientDefaultUserAgent(c *Client) {
if c.UserAgent != userAgent {
suite.FailNowf("NewClient UserAgent = %v, expected %v", c.UserAgent, userAgent)
}
}
// testClientDefaults tests if the client's default base URL and user agent are set to the defaultBaseURL and userAgent.
func (suite *ClientTestSuite) testClientDefaults(c *Client) {
suite.testClientDefaultBaseURL(c)
suite.testClientDefaultUserAgent(c)
}
// TestNewClient tests if the NewClient function returns a client with the default base URL and user agent.
func (suite *ClientTestSuite) TestNewClient() {
c := NewClient(nil, nil)
suite.testClientDefaults(c)
}
// TestNew tests if the New function returns a client with the default base URL and user agent.
func (suite *ClientTestSuite) TestNew() {
c, err := New(nil)
if err != nil {
suite.FailNowf("New(): %v", err.Error())
}
suite.testClientDefaults(c)
}
// TestNewRequest_get tests if the NewRequest function returns a GET request with the default base URL and user agent.
func (suite *ClientTestSuite) TestNewRequest_get() {
c := NewClient(nil, nil)
inURL, outURL := "/foo", string(defaultBaseURL)+"foo"
req, _ := c.NewRequest(ctx, http.MethodGet, inURL, nil)
// test relative URL was expanded
if req.URL.String() != outURL {
suite.FailNowf("NewRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL)
}
// test the content-type header is not set
if contentType := req.Header.Get("Content-Type"); contentType != "" {
suite.FailNowf("NewRequest() Content-Type = %v, expected empty string", contentType)
}
// test default user-agent is attached to the request
userAgent := req.Header.Get("User-Agent")
if c.UserAgent != userAgent {
suite.FailNowf("NewRequest() User-Agent = %v, expected %v", userAgent, c.UserAgent)
}
}
// TestNewRequest_badURL tests if the NewRequest function returns a URL parse error.
func (suite *ClientTestSuite) TestNewRequest_badURL() {
c := NewClient(nil, nil)
_, err := c.NewRequest(ctx, http.MethodGet, ":", nil)
suite.testURLParseError(err)
}
// TestNewRequest_withCustomUserAgent tests if the NewRequest function returns a request with a custom user agent.
func (suite *ClientTestSuite) TestNewRequest_withCustomUserAgent() {
ua := "testing/0.0.1"
c, err := New(nil, WithUserAgent(ua))
if err != nil {
suite.FailNowf("New() unexpected error: %v", err.Error())
}
req, _ := c.NewRequest(ctx, http.MethodGet, "/foo", nil)
expected := fmt.Sprintf("%s %s", ua, userAgent)
if got := req.Header.Get("User-Agent"); got != expected {
suite.FailNowf("New() UserAgent = %s; expected %s", got, expected)
}
}
// TestNewRequest_withResponseLogging tests if the NewRequest function returns a request with response logging.
func (suite *ClientTestSuite) TestNewRequest_withResponseLogging() {
// for debugging - capture logs
logCapture := &bytes.Buffer{}
levelFilterHandler := NewLevelFilterHandler(slog.LevelDebug, slog.NewJSONHandler(io.Writer(logCapture), nil))
c, err := New(nil, WithLogResponseBody(), WithLogHandler(levelFilterHandler))
if err != nil {
suite.FailNowf("unexpected error", "New() unexpected error: %v", err.Error())
}
suite.client = c
url, _ := url.Parse(suite.server.URL)
suite.client.BaseURL = url
suite.mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
if m := http.MethodGet; m != r.Method {
suite.FailNowf("Incorrect request method", "Request method = %v, expected %v", r.Method, m)
}
fmt.Fprint(w, `{"A":"a"}`)
})
req, _ := suite.client.NewRequest(ctx, http.MethodGet, "/a", nil)
_, err = suite.client.Do(ctx, req, nil)
if err != nil {
suite.FailNowf("Unexpected error: Do()", "Unexpected error: Do(): %v", err.Error())
}
// Check the log output for the expected base64 encoded response body
expectedBase64 := "eyJBIjoiYSJ9" // base64 encoded {"A":"a"}
logOutput := logCapture.String()
if !strings.Contains(logOutput, expectedBase64) {
suite.FailNowf("Log output does not contain expected base64", "Log output: %s", logOutput)
}
}
// TestNewRequest_withCustomHeaders tests if the NewRequest function returns a request with custom headers.
func (suite *ClientTestSuite) TestNewRequest_withCustomHeaders() {
expectedIdentity := "identity"
expectedCustom := "x_test_header"
c, err := New(nil, WithCustomHeaders(map[string]string{
"Accept-Encoding": expectedIdentity,
"X-Test-Header": expectedCustom,
}))
if err != nil {
suite.FailNowf("New() unexpected error: %v", err.Error())
}
req, _ := c.NewRequest(ctx, http.MethodGet, "/foo", nil)
if got := req.Header.Get("Accept-Encoding"); got != expectedIdentity {
suite.FailNowf("New() Custom Accept Encoding Header = %s; expected %s", got, expectedIdentity)
}
if got := req.Header.Get("X-Test-Header"); got != expectedCustom {
suite.FailNowf("New() Custom Accept Encoding Header = %s; expected %s", got, expectedCustom)
}
}
// TestDo_get tests if the Do function returns a GET request with the default base URL and user agent.
func (suite *ClientTestSuite) TestDo() {
type foo struct {
A string
}
suite.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if m := http.MethodGet; m != r.Method {
suite.FailNowf("Request method = %v, expected %v", r.Method, m)
}
fmt.Fprint(w, `{"A":"a"}`)
})
req, _ := suite.client.NewRequest(ctx, http.MethodGet, "/", nil)
body := new(foo)
_, err := suite.client.Do(context.Background(), req, body)
if err != nil {
suite.FailNowf("", "Do(): %v", err.Error())
}
expected := &foo{"a"}
if !reflect.DeepEqual(body, expected) {
suite.FailNowf("", "Response body = %v, expected %v", *body, expected)
}
}
// TestDo_httpError tests if the Do function returns an HTTP 400 error.
func (suite *ClientTestSuite) TestDo_httpError() {
suite.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Bad Request", 400)
})
req, _ := suite.client.NewRequest(ctx, http.MethodGet, "/", nil)
_, err := suite.client.Do(context.Background(), req, nil)
if err == nil {
suite.FailNow("Expected HTTP 400 error.")
}
}
// TestErrorResponse_Error tests if the ErrorResponse function returns a non-empty error message.
func (suite *ClientTestSuite) TestErrorResponse_Error() {
res := &http.Response{Request: &http.Request{}}
err := ErrorResponse{Message: "m", Response: res}
if err.Error() == "" {
suite.FailNow("Expected non-empty ErrorResponse.Error()")
}
}
// TestDo_completion_callback tests if the Do function calls the completion callback.
func (suite *ClientTestSuite) TestDo_completion_callback() {
type foo struct {
A string
}
suite.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if m := http.MethodGet; m != r.Method {
suite.FailNowf("", "Request method = %v, expected %v", r.Method, m)
}
fmt.Fprint(w, `{"A":"a"}`)
})
req, _ := suite.client.NewRequest(ctx, http.MethodGet, "/", nil)
body := new(foo)
var completedReq *http.Request
var completedResp string
suite.client.SetOnRequestCompleted(func(req *http.Request, resp *http.Response) {
completedReq = req
b, err := httputil.DumpResponse(resp, true)
if err != nil {
suite.FailNowf("Failed to dump response", "Failed to dump response: %s", err)
}
completedResp = string(b)
})
_, err := suite.client.Do(context.Background(), req, body)
if err != nil {
suite.FailNowf("", "Do(): %v", err)
}
if !reflect.DeepEqual(req, completedReq) {
suite.FailNowf("", "Completed request = %v, expected %v", completedReq, req)
}
expected := `{"A":"a"}`
if !strings.Contains(completedResp, expected) {
suite.FailNowf("", "expected response to contain %v, Response = %v", expected, completedResp)
}
}
// TestCustomUserAgent tests if the New function returns a client with a custom user agent.
func (suite *ClientTestSuite) TestCustomUserAgent() {
ua := "testing/0.0.1"
c, err := New(nil, WithUserAgent(ua))
if err != nil {
suite.FailNowf("", "New() unexpected error: %v", err)
}
expected := fmt.Sprintf("%s %s", ua, userAgent)
if got := c.UserAgent; got != expected {
suite.FailNowf("", "New() UserAgent = %s; expected %s", got, expected)
}
}
// TestCustomBaseURL tests if the New function returns a client with a custom base URL.
func (suite *ClientTestSuite) TestCustomBaseURL() {
baseURL := "http://localhost/foo"
c, err := New(nil, WithBaseURL(baseURL))
if err != nil {
suite.FailNowf("", "New() unexpected error: %v", err)
}
expected := baseURL
if got := c.BaseURL.String(); got != expected {
suite.FailNowf("", "New() BaseURL = %s; expected %s", got, expected)
}
}
// TestCustomBaseURL_badURL tests if the New function returns a URL parse error.
func (suite *ClientTestSuite) TestCustomBaseURL_badURL() {
baseURL := ":"
_, err := New(nil, WithBaseURL(baseURL))
suite.testURLParseError(err)
}
// testMethod tests if the request method is the expected method.
func (suite *ClientTestSuite) testMethod(r *http.Request, expected string) {
if expected != r.Method {
suite.FailNowf("Request method = %v, expected %v", r.Method, expected)
}
}