Skip to content

Commit

Permalink
Merge pull request #6 from bozd4g/bug/context-canceling-problem
Browse files Browse the repository at this point in the history
Update unmarshal and tests
  • Loading branch information
bozd4g authored Dec 5, 2022
2 parents a82330e + 1ee8790 commit 0f3708b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 41 deletions.
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

0 comments on commit 0f3708b

Please sign in to comment.