首頁  >  文章  >  後端開發  >  如何使用 httptest 模擬回應正文讀取錯誤?

如何使用 httptest 模擬回應正文讀取錯誤?

Patricia Arquette
Patricia Arquette原創
2024-10-27 01:05:30405瀏覽

How to Simulate Response Body Read Errors with httptest?

使用httptest 模擬回應正文讀取時的錯誤

使用httptest 測試HTTP 用戶端時,可能需要在回應正文中模擬錯誤閱讀。

考慮以下消耗回應主體的包裝函數:

<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>

要測試此函數,可以使用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>

要強制讀取錯誤,從文件中了解Response.Body 的行為至關重要:

// Body represents the response body.
//
// ...
// If the network connection fails or the server terminates the response, Body.Read calls return an error.

因此,模擬錯誤的簡單方法是從測試處理程序建立無效的HTTP 回應。例如,謊報內容長度可能會導致客戶端出現意外的 EOF 錯誤。

此類處理程序的範例:

<code class="go">handler := func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Length", "1")
}</code>

以上是如何使用 httptest 模擬回應正文讀取錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn