-
Notifications
You must be signed in to change notification settings - Fork 627
/
Copy pathlogger_internal_test.go
488 lines (395 loc) · 11.6 KB
/
logger_internal_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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Licensed to Elasticsearch B.V. under one or more agreements.
// Elasticsearch B.V. licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
// +build !integration
package estransport
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"sync"
"testing"
"time"
)
var (
_ = fmt.Print
_ = os.Stdout
)
func TestTransportLogger(t *testing.T) {
newRoundTripper := func() http.RoundTripper {
return &mockTransp{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
Status: "200 OK",
StatusCode: 200,
ContentLength: 13,
Header: http.Header(map[string][]string{"Content-Type": {"application/json"}}),
Body: ioutil.NopCloser(strings.NewReader(`{"foo":"bar"}`)),
}, nil
},
}
}
t.Run("Defaults", func(t *testing.T) {
var wg sync.WaitGroup
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
// Logger: ioutil.Discard,
})
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req, _ := http.NewRequest("GET", "/abc", nil)
_, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
}()
}
wg.Wait()
})
t.Run("Nil", func(t *testing.T) {
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: nil,
})
req, _ := http.NewRequest("GET", "/abc", nil)
_, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
})
t.Run("No HTTP response", func(t *testing.T) {
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: &mockTransp{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, errors.New("Mock error")
},
},
Logger: &TextLogger{Output: ioutil.Discard},
})
req, _ := http.NewRequest("GET", "/abc", nil)
res, err := tp.Perform(req)
if err == nil {
t.Errorf("Expected error: %v", err)
}
if res != nil {
t.Errorf("Expected nil response, got: %v", err)
}
})
t.Run("Keep response body", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &TextLogger{Output: &dst, EnableRequestBody: true, EnableResponseBody: true},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
res, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Error reading response body: %s", err)
}
if len(dst.String()) < 1 {
t.Errorf("Log is empty: %#v", dst.String())
}
if len(body) < 1 {
t.Fatalf("Body is empty: %#v", body)
}
})
t.Run("Text with body", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &TextLogger{Output: &dst, EnableRequestBody: true, EnableResponseBody: true},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
res, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
_, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Error reading response body: %s", err)
}
output := dst.String()
output = strings.TrimSuffix(output, "\n")
// fmt.Println(output)
lines := strings.Split(output, "\n")
if len(lines) != 3 {
t.Fatalf("Expected 3 lines, got %d", len(lines))
}
if !strings.Contains(lines[0], "GET http://foo/abc?q=a,b") {
t.Errorf("Unexpected output: %s", lines[0])
}
if lines[1] != `> {"query":"42"}` {
t.Errorf("Unexpected output: %s", lines[1])
}
if lines[2] != `< {"foo":"bar"}` {
t.Errorf("Unexpected output: %s", lines[1])
}
})
t.Run("Color with body", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &ColorLogger{Output: &dst, EnableRequestBody: true, EnableResponseBody: true},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
res, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
_, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Error reading response body: %s", err)
}
var output string
stripANSI := regexp.MustCompile("(?sm)\x1b\\[.+?m([^\x1b]+?)|\x1b\\[0m")
for _, v := range strings.Split(dst.String(), "\n") {
if v != "" {
output += stripANSI.ReplaceAllString(v, "$1")
if !strings.HasSuffix(output, "\n") {
output += "\n"
}
}
}
output = strings.TrimSuffix(output, "\n")
// fmt.Println(output)
lines := strings.Split(output, "\n")
if len(lines) != 4 {
t.Fatalf("Expected 4 lines, got %d", len(lines))
}
if !strings.Contains(lines[0], "GET http://foo/abc?q=a,b") {
t.Errorf("Unexpected output: %s", lines[0])
}
if !strings.Contains(lines[1], `» {"query":"42"}`) {
t.Errorf("Unexpected output: %s", lines[1])
}
if !strings.Contains(lines[2], `« {"foo":"bar"}`) {
t.Errorf("Unexpected output: %s", lines[2])
}
})
t.Run("Curl", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &CurlLogger{Output: &dst, EnableRequestBody: true, EnableResponseBody: true},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
res, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
_, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Error reading response body: %s", err)
}
output := dst.String()
output = strings.TrimSuffix(output, "\n")
// fmt.Println(output)
lines := strings.Split(output, "\n")
if len(lines) != 9 {
t.Fatalf("Expected 9 lines, got %d", len(lines))
}
if !strings.Contains(lines[0], "curl -X GET 'http://localhost:9200/abc?pretty&q=a%2Cb'") {
t.Errorf("Unexpected output: %s", lines[0])
}
})
t.Run("JSON", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &JSONLogger{Output: &dst},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
_, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
output := dst.String()
output = strings.TrimSuffix(output, "\n")
// fmt.Println(output)
lines := strings.Split(output, "\n")
if len(lines) != 1 {
t.Fatalf("Expected 1 line, got %d", len(lines))
}
var j map[string]interface{}
if err := json.Unmarshal([]byte(output), &j); err != nil {
t.Errorf("Error decoding JSON: %s", err)
}
domain := j["url"].(map[string]interface{})["domain"]
if domain != "foo" {
t.Errorf("Unexpected JSON output: %s", domain)
}
})
t.Run("JSON with request body", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &JSONLogger{Output: &dst, EnableRequestBody: true},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
res, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
_, err = ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("Error reading response body: %s", err)
}
output := dst.String()
output = strings.TrimSuffix(output, "\n")
// fmt.Println(output)
lines := strings.Split(output, "\n")
if len(lines) != 1 {
t.Fatalf("Expected 1 line, got %d", len(lines))
}
var j map[string]interface{}
if err := json.Unmarshal([]byte(output), &j); err != nil {
t.Errorf("Error decoding JSON: %s", err)
}
body := j["http"].(map[string]interface{})["request"].(map[string]interface{})["body"].(string)
if !strings.Contains(body, "query") {
t.Errorf("Unexpected JSON output: %s", body)
}
})
t.Run("Custom", func(t *testing.T) {
var dst strings.Builder
tp, _ := New(Config{
URLs: []*url.URL{{Scheme: "http", Host: "foo"}},
Transport: newRoundTripper(),
Logger: &CustomLogger{Output: &dst},
})
req, _ := http.NewRequest("GET", "/abc?q=a,b", nil)
req.Body = ioutil.NopCloser(strings.NewReader(`{"query":"42"}`))
_, err := tp.Perform(req)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
if !strings.HasPrefix(dst.String(), "GET http://foo/abc?q=a,b") {
t.Errorf("Unexpected output: %s", dst.String())
}
})
t.Run("Duplicate body", func(t *testing.T) {
input := ResponseBody{content: strings.NewReader("FOOBAR")}
b1, b2, err := duplicateBody(&input)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
if !input.closed {
t.Errorf("Expected input to be closed: %#v", input)
}
read, _ := ioutil.ReadAll(&input)
if len(read) > 0 {
t.Errorf("Expected input to be drained: %#v", input.content)
}
b1r, _ := ioutil.ReadAll(b1)
b2r, _ := ioutil.ReadAll(b2)
if len(b1r) != 6 || len(b2r) != 6 {
t.Errorf(
"Unexpected duplicate content, b1=%q (%db), b2=%q (%db)",
string(b1r), len(b1r), string(b2r), len(b2r),
)
}
})
t.Run("Duplicate body with error", func(t *testing.T) {
input := ResponseBody{content: &ErrorReader{r: strings.NewReader("FOOBAR")}}
b1, b2, err := duplicateBody(&input)
if err == nil {
t.Errorf("Expected error, got: %v", err)
}
if err.Error() != "MOCK ERROR" {
t.Errorf("Unexpected error value, expected [ERROR MOCK], got [%s]", err.Error())
}
read, _ := ioutil.ReadAll(&input)
if string(read) != "BAR" {
t.Errorf("Unexpected undrained part: %q", read)
}
b2r, _ := ioutil.ReadAll(b2)
if string(b2r) != "FOO" {
t.Errorf("Unexpected value, b2=%q", string(b2r))
}
b1c, err := ioutil.ReadAll(b1)
if string(b1c) != "FOO" {
t.Errorf("Unexpected value, b1=%q", string(b1c))
}
if err == nil {
t.Errorf("Expected error when reading b1, got: %v", err)
}
if err.Error() != "MOCK ERROR" {
t.Errorf("Unexpected error value, expected [ERROR MOCK], got [%s]", err.Error())
}
})
}
func TestDebuggingLogger(t *testing.T) {
logger := &debuggingLogger{Output: ioutil.Discard}
t.Run("Log", func(t *testing.T) {
if err := logger.Log("Foo"); err != nil {
t.Errorf("Unexpected error: %s", err)
}
})
t.Run("Logf", func(t *testing.T) {
if err := logger.Logf("Foo %d", 1); err != nil {
t.Errorf("Unexpected error: %s", err)
}
})
}
type CustomLogger struct {
Output io.Writer
}
func (l *CustomLogger) LogRoundTrip(
req *http.Request,
res *http.Response,
err error,
start time.Time,
dur time.Duration,
) error {
fmt.Fprintln(l.Output, req.Method, req.URL, "->", res.Status)
return nil
}
func (l *CustomLogger) RequestBodyEnabled() bool { return false }
func (l *CustomLogger) ResponseBodyEnabled() bool { return false }
type ResponseBody struct {
content io.Reader
closed bool
}
func (r *ResponseBody) Read(p []byte) (int, error) {
return r.content.Read(p)
}
func (r *ResponseBody) Close() error {
r.closed = true
return nil
}
type ErrorReader struct {
r io.Reader
}
func (r *ErrorReader) Read(p []byte) (int, error) {
lr := io.LimitReader(r.r, 3)
c, _ := lr.Read(p)
return c, errors.New("MOCK ERROR")
}