>  기사  >  백엔드 개발  >  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으로 문의하세요.