How to Simulate Response Body Read Errors with httptest?

Patricia Arquette
Release: 2024-10-27 01:05:30
Original
413 people have browsed it

How to Simulate Response Body Read Errors with httptest?

Simulating 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>
Copy after login

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>
Copy after login

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.
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!