How to Simulate Response Body Read Errors with httptest?
Oct 27, 2024 am 01:05 AMSimulating Errors on Response Body Read with httptest
When testing HTTP clients with httptest, there may be a need to simulate errors during response body read.
Consider the following wrapper function that consumes response bodies:
<code class="go">package req func GetContent(url string) ([]byte, error) { response, err := httpClient.Get(url) // some header validation goes here body, err := ioutil.ReadAll(response.Body) defer response.Body.Close() if err != nil { errStr := fmt.Sprintf("Unable to read from body %s", err) return nil, errors.New(errStr) } return body, nil }</code>
To test this function, a fake server can be set up using httptest:
<code class="go">package req_test import ( "net/http" "net/http/httptest" "testing" ) func Test_GetContent_RequestBodyReadError(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } ts := httptest.NewServer(http.HandlerFunc(handler)) defer ts.Close() _, err := GetContent(ts.URL) if err != nil { t.Log("Body read failed as expected.") } else { t.Fatalf("Method did not fail as expected") } }</code>
To force a read error, it's vital to understand the behavior of Response.Body from the documentation:
// Body represents the response body. // // ... // If the network connection fails or the server terminates the response, Body.Read calls return an error.
Therefore, a simple way to simulate an error is to create an invalid HTTP response from the test handler. For instance, lying about the content length can cause an unexpected EOF error on the client side.
An example of such a handler:
<code class="go">handler := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", "1") }</code>
The above is the detailed content of How to Simulate Response Body Read Errors with httptest?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language pack import: What is the difference between underscore and without underscore?

How to implement short-term information transfer between pages in the Beego framework?

How do I write mock objects and stubs for testing in Go?

How to convert MySQL query result List into a custom structure slice in Go language?

How can I define custom type constraints for generics in Go?

How can I use tracing tools to understand the execution flow of my Go applications?

How to write files in Go language conveniently?
