From 98e69ab0cc66a36786cb321ac2709c77042a8373 Mon Sep 17 00:00:00 2001 From: gaowenju Date: Thu, 10 Aug 2023 17:08:53 +0800 Subject: [PATCH] test: add ut --- pkg/protocol/http1/ext/common.go | 8 ++++++++ pkg/protocol/http1/ext/common_test.go | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/pkg/protocol/http1/ext/common.go b/pkg/protocol/http1/ext/common.go index 19f82e3d4..2f2280ab9 100644 --- a/pkg/protocol/http1/ext/common.go +++ b/pkg/protocol/http1/ext/common.go @@ -51,6 +51,7 @@ import ( "github.com/cloudwego/hertz/internal/bytesconv" "github.com/cloudwego/hertz/internal/bytestr" errs "github.com/cloudwego/hertz/pkg/common/errors" + "github.com/cloudwego/hertz/pkg/common/hlog" "github.com/cloudwego/hertz/pkg/common/utils" "github.com/cloudwego/hertz/pkg/network" "github.com/cloudwego/hertz/pkg/protocol" @@ -117,9 +118,16 @@ func WriteBodyChunked(w network.Writer, r io.Reader) error { if err == nil { panic("BUG: io.Reader returned 0, nil") } + + if !errors.Is(err, io.EOF) { + hlog.SystemLogger().Warnf("writing chunked response body encountered an error from the reader, "+ + "this may cause the short of the content in response body, error: %s", err.Error()) + } + if err = WriteChunk(w, buf[:0], true); err != nil { break } + err = nil break } diff --git a/pkg/protocol/http1/ext/common_test.go b/pkg/protocol/http1/ext/common_test.go index 78a9fede0..16c168c8b 100644 --- a/pkg/protocol/http1/ext/common_test.go +++ b/pkg/protocol/http1/ext/common_test.go @@ -19,6 +19,7 @@ package ext import ( "bytes" "errors" + "github.com/cloudwego/hertz/pkg/common/hlog" "io" "strings" "testing" @@ -123,6 +124,9 @@ func TestReadRawHeaders(t *testing.T) { } func TestBodyChunked(t *testing.T) { + var log bytes.Buffer + hlog.SetOutput(&log) + body := "foobar baz aaa bbb ccc" chunk := "16\r\nfoobar baz aaa bbb ccc\r\n0\r\n" b := bytes.NewBufferString(body) @@ -137,6 +141,22 @@ func TestBodyChunked(t *testing.T) { rb, err := ReadBody(zr, -1, 0, nil) assert.Nil(t, err) assert.DeepEqual(t, body, string(rb)) + + assert.DeepEqual(t, 0, log.Len()) +} + +func TestBrokenBodyChunked(t *testing.T) { + brokenReader := mock.NewBrokenConn("") + var log bytes.Buffer + hlog.SetOutput(&log) + + var w bytes.Buffer + zw := netpoll.NewWriter(&w) + err := WriteBodyChunked(zw, brokenReader) + assert.Nil(t, err) + + assert.DeepEqual(t, []byte("0\r\n"), w.Bytes()) + assert.True(t, bytes.Contains(log.Bytes(), []byte("writing chunked response body encountered an error from the reader"))) } func TestBodyFixedSize(t *testing.T) {