github.com/cloudwego/hertz@v0.9.3/pkg/protocol/http1/resp/writer_test.go (about) 1 /* 2 * Copyright 2023 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package resp 18 19 import ( 20 "strings" 21 "testing" 22 23 "github.com/cloudwego/hertz/internal/bytestr" 24 "github.com/cloudwego/hertz/pkg/common/test/assert" 25 "github.com/cloudwego/hertz/pkg/common/test/mock" 26 "github.com/cloudwego/hertz/pkg/protocol" 27 ) 28 29 func TestNewChunkedBodyWriter(t *testing.T) { 30 response := protocol.AcquireResponse() 31 mockConn := mock.NewConn("") 32 w := NewChunkedBodyWriter(response, mockConn) 33 w.Write([]byte("hello")) 34 w.Flush() 35 out, _ := mockConn.WriterRecorder().ReadBinary(mockConn.WriterRecorder().WroteLen()) 36 assert.True(t, strings.Contains(string(out), "Transfer-Encoding: chunked")) 37 assert.True(t, strings.Contains(string(out), "5"+string(bytestr.StrCRLF)+"hello")) 38 assert.False(t, strings.Contains(string(out), "0"+string(bytestr.StrCRLF)+string(bytestr.StrCRLF))) 39 } 40 41 func TestNewChunkedBodyWriter1(t *testing.T) { 42 response := protocol.AcquireResponse() 43 mockConn := mock.NewConn("") 44 w := NewChunkedBodyWriter(response, mockConn) 45 w.Write([]byte("hello")) 46 w.Flush() 47 w.Finalize() 48 w.Flush() 49 out, _ := mockConn.WriterRecorder().ReadBinary(mockConn.WriterRecorder().WroteLen()) 50 assert.True(t, strings.Contains(string(out), "Transfer-Encoding: chunked")) 51 assert.True(t, strings.Contains(string(out), "5"+string(bytestr.StrCRLF)+"hello")) 52 assert.True(t, strings.Contains(string(out), "0"+string(bytestr.StrCRLF)+string(bytestr.StrCRLF))) 53 } 54 55 func TestNewChunkedBodyWriterNoData(t *testing.T) { 56 response := protocol.AcquireResponse() 57 response.Header.Set("Foo", "Bar") 58 mockConn := mock.NewConn("") 59 w := NewChunkedBodyWriter(response, mockConn) 60 w.Finalize() 61 w.Flush() 62 out, _ := mockConn.WriterRecorder().ReadBinary(mockConn.WriterRecorder().WroteLen()) 63 assert.True(t, strings.Contains(string(out), "Transfer-Encoding: chunked")) 64 assert.True(t, strings.Contains(string(out), "Foo: Bar")) 65 assert.True(t, strings.Contains(string(out), "0"+string(bytestr.StrCRLF)+string(bytestr.StrCRLF))) 66 }