github.com/xmidt-org/webpa-common@v1.11.9/xhttp/xhttptest/body.go (about)

     1  package xhttptest
     2  
     3  import "github.com/stretchr/testify/mock"
     4  
     5  // MockBody is a stretchr mock for a Request or a Response body, which is really just an io.ReadCloser.
     6  // This is mainly useful when testing error cases.  For testing with actual byte contents, it's generally more convenient
     7  // to use a *bytes.Buffer or other concrete container of bytes instead of mocking.
     8  type MockBody struct {
     9  	mock.Mock
    10  }
    11  
    12  // OnReadError sets an expectation for a call to Read, with any byte slice, that returns the given error (and 0 for bytes read).
    13  // If the given error is nil, wierd behavior can occur as the mocked Read will return (0, nil).
    14  func (mb *MockBody) OnReadError(err error) *mock.Call {
    15  	return mb.On("Read", mock.MatchedBy(func([]byte) bool { return true })).Return(0, err)
    16  }
    17  
    18  // OnCloseError sets an expectation for a call to Close that simply returns the given error.
    19  // The given error can be nil.
    20  func (mb *MockBody) OnCloseError(err error) *mock.Call {
    21  	return mb.On("Close").Return(err)
    22  }
    23  
    24  func (mb *MockBody) Read(p []byte) (int, error) {
    25  	arguments := mb.Called(p)
    26  	return arguments.Int(0), arguments.Error(1)
    27  }
    28  
    29  func (mb *MockBody) Close() error {
    30  	return mb.Called().Error(0)
    31  }