Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package gohttpclient

import (
"encoding/json"
"io/ioutil"
"net/http"
)

Expand All @@ -18,13 +17,7 @@ func (r *Response) Body() []byte {
}

func (r *Response) Unmarshal(v any) error {
defer r.res.Body.Close()
body, err := ioutil.ReadAll(r.res.Body)
if err != nil {
return err
}

return json.Unmarshal(body, &v)
return json.Unmarshal(r.body, &v)
}

func (r *Response) Status() int {
Expand Down
38 changes: 5 additions & 33 deletions response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,13 @@ package gohttpclient
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"testing"

"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
)

type mockReadCloser struct {
mock.Mock
}

func (m *mockReadCloser) Read(p []byte) (n int, err error) {
args := m.Called(p)
return args.Int(0), args.Error(1)
}

func (m *mockReadCloser) Close() error {
args := m.Called()
return args.Error(0)
}

type TestResponseSuite struct {
suite.Suite
ctx context.Context
Expand Down Expand Up @@ -56,13 +40,10 @@ func (s *TestResponseSuite) Test_Body_ShouldRunSuccesfully() {
func (s *TestResponseSuite) Test_Unmarshal_ShouldRunSuccesfully() {
// Arrange
body := []byte(`{"name":"test"}`)
res := &http.Response{}

// Act
resp := Response{
res: &http.Response{
Body: ioutil.NopCloser(bytes.NewBuffer(body)),
},
}
resp := Response{res, body}

// Assert
var response map[string]interface{}
Expand All @@ -73,14 +54,8 @@ func (s *TestResponseSuite) Test_Unmarshal_ShouldRunSuccesfully() {

func (s *TestResponseSuite) Test_Unmarshal_WhenBodyIsWrong_ShouldReturnError() {
// Arrange
mockReadCloser := mockReadCloser{}
mockReadCloser.On("Read", mock.AnythingOfType("[]uint8")).Return(0, fmt.Errorf("error reading"))
mockReadCloser.On("Close").Return(fmt.Errorf("error closing"))

resp := Response{
res: &http.Response{
Body: &mockReadCloser,
},
body: nil,
}

// Act
Expand All @@ -94,13 +69,10 @@ func (s *TestResponseSuite) Test_Unmarshal_WhenBodyIsWrong_ShouldReturnError() {
func (s *TestResponseSuite) Test_Unmarshal_WhenUnMarshalReturnsError_ShouldReturnError() {
// Arrange
body := []byte(`{"name":"test"`)
res := &http.Response{}

// Act
resp := Response{
res: &http.Response{
Body: ioutil.NopCloser(bytes.NewBuffer(body)),
},
}
resp := Response{res, body}

// Assert
var response map[string]interface{}
Expand Down