Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ioutil.ReadAll error testing. #75

Open
ghost opened this issue Sep 18, 2020 · 2 comments
Open

ioutil.ReadAll error testing. #75

ghost opened this issue Sep 18, 2020 · 2 comments

Comments

@ghost
Copy link

ghost commented Sep 18, 2020

I am trying to test the following line of code:

func ook() error {
        […]
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return errors.Wrap(err, "cannot read body, trying again")
	}

This is my test:


func (errReader) Read(p []byte) (int, error) {
	return 1, errors.New("Computer says NON!")
}

// Wait for vault to unseal: body error.
func TestWaitForVaultToUnsealBodyError(t *testing.T) {
	defer gock.Off() // Flush pending mocks after test execution

	gock.New(URL).
		Get("v1/seal-status").
		Reply(200).
		Body(errReader{})

        ook()
}

I removed the URL and other extra stuff, the code is a little (but not much) more complex than that. However, the ioutil.ReadAll refuses to spew an error. What am I doing wrong?

@rafael-piovesan-hash
Copy link

rafael-piovesan-hash commented Oct 17, 2021

I've managed to test this using something as follows:

serverAPI := httptest.NewServer(
	http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                // says the response is longer than what we're actually returning
		w.Header().Add("Content-Length", "50")
                // return less bytes, wich will result in an "unexpected EOF" from ioutil.ReadAll()
		_, _ = w.Write([]byte("a"))
	}),
)
defer serverAPI.Close()

@ibrt
Copy link

ibrt commented Apr 10, 2022

Same issue here. The problem is that this library immediately consumes that response buffer and will have the mock RoundTripper return (nil, error) instead of (*http.Response, nil) (with the reader as *http.Response.Body).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants