ホームページ  >  記事  >  バックエンド開発  >  httptest でレスポンスボディ読み取りエラーをシミュレートするには?

httptest でレスポンスボディ読み取りエラーをシミュレートするには?

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-27 01:05:30405ブラウズ

How to Simulate Response Body Read Errors with httptest?

httptest で読み取られた応答本文のエラーをシミュレートする

httptest で HTTP クライアントをテストする場合、応答本文中にエラーをシミュレートする必要がある場合があります。 read.

レスポンスボディを消費する次のラッパー関数を考えてみましょう:

<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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。