|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | +) |
| 9 | + |
| 10 | +func readString(t *testing.T, rc io.ReadCloser) string { |
| 11 | + t.Helper() |
| 12 | + defer func(rc io.ReadCloser) { |
| 13 | + err := rc.Close() |
| 14 | + assert.NoError(t, err) |
| 15 | + }(rc) |
| 16 | + b, err := io.ReadAll(rc) |
| 17 | + assert.NoError(t, err) |
| 18 | + return string(b) |
| 19 | +} |
| 20 | + |
| 21 | +func TestFindBackendError_NoKeys(t *testing.T) { |
| 22 | + resp, ok := FindBackendError(map[string]interface{}{ |
| 23 | + "product": map[string]interface{}{"id": 1}, |
| 24 | + }) |
| 25 | + |
| 26 | + assert.False(t, ok) |
| 27 | + assert.Nil(t, resp) |
| 28 | +} |
| 29 | + |
| 30 | +func TestFindBackendError_PicksFirstSortedKey(t *testing.T) { |
| 31 | + body := map[string]interface{}{ |
| 32 | + "error_2": map[string]interface{}{ |
| 33 | + "http_status_code": 502, |
| 34 | + "http_body": `{"message":"second"}`, |
| 35 | + "http_body_encoding": "application/json", |
| 36 | + }, |
| 37 | + "error_1": map[string]interface{}{ |
| 38 | + "http_status_code": 500, |
| 39 | + "http_body": `{"message":"first"}`, |
| 40 | + "http_body_encoding": "application/json; charset=utf-8", |
| 41 | + }, |
| 42 | + "product": map[string]interface{}{"id": 1}, |
| 43 | + } |
| 44 | + |
| 45 | + resp, ok := FindBackendError(body) |
| 46 | + assert.True(t, ok) |
| 47 | + assert.NotNil(t, resp) |
| 48 | + |
| 49 | + assert.Equal(t, 500, resp.StatusCode) |
| 50 | + assert.Equal(t, "application/json; charset=utf-8", resp.Header.Get("Content-Type")) |
| 51 | + |
| 52 | + gotBody := readString(t, resp.Body) |
| 53 | + assert.Equal(t, `{"message":"first"}`, gotBody) |
| 54 | + assert.Equal(t, int64(len(gotBody)), resp.ContentLength) |
| 55 | +} |
| 56 | + |
| 57 | +func TestFindBackendError_InvalidShape_ReturnsFalse(t *testing.T) { |
| 58 | + body := map[string]interface{}{ |
| 59 | + "error_1": "not an object", |
| 60 | + } |
| 61 | + |
| 62 | + resp, ok := FindBackendError(body) |
| 63 | + assert.False(t, ok) |
| 64 | + assert.Nil(t, resp) |
| 65 | +} |
| 66 | + |
| 67 | +func TestFindBackendErrorMissingEncoding(t *testing.T) { |
| 68 | + body := map[string]interface{}{ |
| 69 | + "error_1": map[string]interface{}{ |
| 70 | + "http_status_code": 503, |
| 71 | + "http_body": "service unavailable", |
| 72 | + }, |
| 73 | + } |
| 74 | + |
| 75 | + resp, ok := FindBackendError(body) |
| 76 | + assert.True(t, ok) |
| 77 | + assert.NotNil(t, resp) |
| 78 | + assert.Equal(t, 503, resp.StatusCode) |
| 79 | + assert.Equal(t, "text/plain", resp.Header.Get("Content-Type")) |
| 80 | + |
| 81 | + got := readString(t, resp.Body) |
| 82 | + assert.Equal(t, `service unavailable`, got) |
| 83 | +} |
0 commit comments