|
1 | 1 | package collect |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
4 | 5 | "encoding/json" |
5 | 6 | "fmt" |
| 7 | + "io" |
6 | 8 | "net/http" |
7 | 9 | "net/http/httptest" |
8 | 10 | "strings" |
@@ -376,3 +378,64 @@ func Test_parseTimeout(t *testing.T) { |
376 | 378 | }) |
377 | 379 | } |
378 | 380 | } |
| 381 | + |
| 382 | +func Test_responseToOutput(t *testing.T) { |
| 383 | + tests := []struct { |
| 384 | + name string |
| 385 | + response *http.Response |
| 386 | + err error |
| 387 | + want []byte |
| 388 | + wantErr bool |
| 389 | + }{ |
| 390 | + { |
| 391 | + name: "valid JSON response", |
| 392 | + response: &http.Response{ |
| 393 | + Body: io.NopCloser(bytes.NewBufferString(`{"ok": false, "error": "invalid_auth"}`)), |
| 394 | + Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, |
| 395 | + StatusCode: http.StatusOK, |
| 396 | + }, |
| 397 | + err: nil, |
| 398 | + want: []byte(` |
| 399 | + { |
| 400 | + "response": |
| 401 | + { |
| 402 | + "status":200, |
| 403 | + "body":"{\"ok\": false, \"error\": \"invalid_auth\"}", |
| 404 | + "headers":{"Content-Type":"application/json; charset=utf-8"}, |
| 405 | + "raw_json":{"ok":false,"error":"invalid_auth"} |
| 406 | + } |
| 407 | + }`), |
| 408 | + wantErr: false, |
| 409 | + }, |
| 410 | + { |
| 411 | + name: "invalid JSON response", |
| 412 | + response: &http.Response{ |
| 413 | + Body: io.NopCloser(bytes.NewBufferString(`foobar`)), |
| 414 | + Header: http.Header{"Content-Type": []string{"text/html; charset=utf-8"}}, |
| 415 | + StatusCode: http.StatusOK, |
| 416 | + }, |
| 417 | + err: nil, |
| 418 | + want: []byte(` |
| 419 | + { |
| 420 | + "response": |
| 421 | + { |
| 422 | + "status":200, |
| 423 | + "body":"foobar", |
| 424 | + "headers":{"Content-Type":"text/html; charset=utf-8"} |
| 425 | + } |
| 426 | + }`), |
| 427 | + wantErr: false, |
| 428 | + }, |
| 429 | + } |
| 430 | + for _, tt := range tests { |
| 431 | + t.Run(tt.name, func(t *testing.T) { |
| 432 | + got, err := responseToOutput(tt.response, tt.err) |
| 433 | + if tt.wantErr { |
| 434 | + assert.Error(t, err) |
| 435 | + return |
| 436 | + } |
| 437 | + assert.NoError(t, err) |
| 438 | + assert.JSONEq(t, string(got), string(tt.want)) |
| 439 | + }) |
| 440 | + } |
| 441 | +} |
0 commit comments