|
| 1 | +package nuts |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/stretchr/testify/require" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +func Test_ParseResponse(t *testing.T) { |
| 13 | + fn := func(response *http.Response) (*string, error) { |
| 14 | + data, _ := io.ReadAll(response.Body) |
| 15 | + result := string(data) |
| 16 | + return &result, nil |
| 17 | + } |
| 18 | + okResponse := func() *http.Response { |
| 19 | + return &http.Response{ |
| 20 | + StatusCode: 200, |
| 21 | + Status: "200 OK", |
| 22 | + Body: io.NopCloser(strings.NewReader("http-test-response")), |
| 23 | + Request: httptest.NewRequest(http.MethodGet, "http://example.com", nil), |
| 24 | + } |
| 25 | + } |
| 26 | + nokResponse := func() *http.Response { |
| 27 | + return &http.Response{ |
| 28 | + StatusCode: 404, |
| 29 | + Status: "404 Not Found", |
| 30 | + Body: io.NopCloser(strings.NewReader("http-test-response")), |
| 31 | + Request: httptest.NewRequest(http.MethodGet, "http://example.com", nil), |
| 32 | + } |
| 33 | + } |
| 34 | + t.Run("error", func(t *testing.T) { |
| 35 | + _, err := ParseResponse(io.EOF, okResponse(), fn) |
| 36 | + require.EqualError(t, err, "http request failed: EOF") |
| 37 | + }) |
| 38 | + t.Run("parse error", func(t *testing.T) { |
| 39 | + _, err := ParseResponse(nil, okResponse(), func(response *http.Response) (*string, error) { |
| 40 | + return nil, io.EOF |
| 41 | + }) |
| 42 | + require.EqualError(t, err, "failed to parse response: EOF") |
| 43 | + }) |
| 44 | + t.Run("ok", func(t *testing.T) { |
| 45 | + result, err := ParseResponse(nil, okResponse(), fn) |
| 46 | + require.NoError(t, err) |
| 47 | + require.Equal(t, "http-test-response", *result) |
| 48 | + }) |
| 49 | + t.Run("non-ok status", func(t *testing.T) { |
| 50 | + _, err := ParseResponse(nil, nokResponse(), fn) |
| 51 | + require.EqualError(t, err, "non-OK status code (status=404 Not Found, url=http://example.com)\nResponse data:\n----------------\nhttp-test-response\n----------------") |
| 52 | + }) |
| 53 | +} |
0 commit comments