doue2666 2019-03-10 18:34
浏览 13

有没有办法清除响应编写器中的数据?

I am writing test for an elasticsearch middleware, where I am using a function to build test servers in which I pass a slice of configuration structs for each tests and in a handler function they are iterated upon and the expected response is written to the response writer. This is my function.

func newMockClient(url string) (*elasticsearch, error) {
    client, err := elastic.NewSimpleClient(elastic.SetURL(url))
    if err != nil {
        return nil, fmt.Errorf("error while initializing elastic client: %v", err)
    }
    es := &elasticsearch{
        url:    url,
        client: client,
    }
    return es, nil
}

type ServerSetup struct {
    Method, Path, Body, Response string
    HTTPStatus                   int
}

func buildTestServer(t *testing.T, setups []*ServerSetup) *httptest.Server {
    handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        requestBytes, _ := ioutil.ReadAll(r.Body)
        requestBody := string(requestBytes)

        matched := false
        for _, setup := range setups {
            if r.Method == setup.Method && r.URL.EscapedPath() == setup.Path {
                matched = true
                if setup.HTTPStatus == 0 {
                    w.WriteHeader(http.StatusOK)
                } else {
                    w.WriteHeader(setup.HTTPStatus)
                }
                _, err := w.Write([]byte(setup.Response))
                if err != nil {
                    t.Fatalf("Unable to write test server response: %v", err)
                }
            }
        }

        if !matched {
            t.Fatalf("No requests matched setup. Got method %s, Path %s, body %s", r.Method, r.URL.EscapedPath(), requestBody)
        }
    })

    return httptest.NewServer(handlerFunc)
}

It is copied from github.com/github/vulcanizer. When I run a single test using this, it works fine. For e.g. this test

func TestCreateIndex(t *testing.T) {
    setup := &ServerSetup{
        Method:   "PUT",
        Path:     "/test",
        Response: `{"acknowledged": true, "shards_acknowledged": true, "index": "test"}`,
    }

    ts := buildTestServer(t, []*ServerSetup{setup})

    es, _ := newMockClient(ts.URL)

    err := es.createIndex(context.Background(), "test", nil)
    if err != nil {
        t.Fatalf("Index creation failed with error: %v
", err)
    }

}

But when I try to check different behaviours in a single test like this one I get an error http: multiple response.WriteHeader calls

func TestDeleteIndex(t *testing.T) {
    setup := &ServerSetup{
        Method:   "DELETE",
        Path:     "/test",
        Response: `{"acknowledged": true}`,
    }

    errSetup := &ServerSetup{
        Method:   "DELETE",
        Path:     "/test",
        Response: `{"acknowledged": false}`,
    }

    ctx := context.Background()

    ts := buildTestServer(t, []*ServerSetup{setup, errSetup})
    defer ts.Close()

    es, _ := newMockClient(ts.URL)

    err := es.deleteIndex(ctx, "test")
    if err != nil {
        t.Fatalf("Index creation failed with error: %v
", err)
    }

    err = es.deleteIndex(ctx, "test")
    if err == nil {
        t.Fatal("Expected error but not found")
    }
}

I am guessing that it is because of the fact that when I run deleteIndex for the second time it pings the server again but the response writer has already been written to so it can't write anything else to it.

Is there anyway I can have a check at the beginning of my handler func like

handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if w != nil{
        // clear data in response writer
    }

// .........



}
  • 写回答

2条回答 默认 最新

  • duankuang7928 2019-03-10 19:01
    关注

    I don't think what you are doing is the correct way to test your functionality. You need to separate your test to test-cases for checking different behaviours like that:

    func Test_DeleteIndex(t *testing.T) {
        t.Run("Should be ok with correct setup", func(t *testing.T) {
            setup := &ServerSetup{
                Method:   "DELETE",
                Path:     "/test",
                Response: `{"acknowledged": true}`,
            }
            ctx := context.Background()
            ts := buildTestServer(t, []*ServerSetup{setup})
            defer ts.Close()
            es, _ := newMockClient(ts.URL)
            err := es.deleteIndex(ctx, "test")
            require.NoError(t, err)
        })
    
        t.Run("Shouldn't be ok with wrong setup", func(t *testing.T) {
            setup := &ServerSetup{
                Method:   "DELETE",
                Path:     "/test",
                Response: `{"acknowledged": false}`,
            }
            ctx := context.Background()
            ts := buildTestServer(t, []*ServerSetup{setup})
            defer ts.Close()
            es, _ := newMockClient(ts.URL)
            err := es.deleteIndex(ctx, "test")
            require.Error(t, err)
        })
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线