Skip to content

Instantly share code, notes, and snippets.

@crhntr
Last active August 13, 2019 04:38
Show Gist options
  • Save crhntr/97f76b776d074dfa8bdc8ba4d3a4b265 to your computer and use it in GitHub Desktop.
Save crhntr/97f76b776d074dfa8bdc8ba4d3a4b265 to your computer and use it in GitHub Desktop.
Some helpers for mocking requests
package foo_test
import (
"bytes"
"io"
"io/ioutil"
"net/http"
)
type RoundTriper struct {
CallCount int
Recieves struct {
Req *http.Request
}
Returns struct {
Res *http.Response
Err error
}
}
func (mock *RoundTriper) RoundTrip(req *http.Request) (*http.Response, error) {
mock.CallCount++
mock.Recieves.Req = req
return mock.Returns.Res, mock.Returns.Err
}
type ReadCloser struct {
RC io.ReadCloser
ReadCall struct {
Returns struct {
Err error
}
}
CloseCall struct {
Count int
Returns struct {
Err error
}
}
}
func NewReadCloser(buf string) *ReadCloser {
return &ReadCloser{
RC: ioutil.NopCloser(bytes.NewBufferString(buf)),
}
}
func (mock *ReadCloser) Read(buf []byte) (int, error) {
if mock.ReadCall.Returns.Err != nil {
return 0, mock.ReadCall.Returns.Err
}
if mock.RC == nil {
mock.RC = ioutil.NopCloser(bytes.NewBufferString(""))
}
return mock.RC.Read(buf)
}
func (mock *ReadCloser) Close() error {
mock.CloseCall.Count++
if mock.CloseCall.Returns.Err != nil {
return mock.CloseCall.Returns.Err
}
if mock.RC == nil {
mock.RC = ioutil.NopCloser(bytes.NewBufferString(""))
}
return mock.RC.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment