github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/net/http/httputil/chunked_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This code is a duplicate of ../chunked_test.go with these edits: 6 // s/newChunked/NewChunked/g 7 // s/package http/package httputil/ 8 // Please make any changes in both files. 9 10 package httputil 11 12 import ( 13 "bytes" 14 "fmt" 15 "io" 16 "io/ioutil" 17 "runtime" 18 "testing" 19 ) 20 21 func TestChunk(t *testing.T) { 22 var b bytes.Buffer 23 24 w := NewChunkedWriter(&b) 25 const chunk1 = "hello, " 26 const chunk2 = "world! 0123456789abcdef" 27 w.Write([]byte(chunk1)) 28 w.Write([]byte(chunk2)) 29 w.Close() 30 31 if g, e := b.String(), "7\r\nhello, \r\n17\r\nworld! 0123456789abcdef\r\n0\r\n"; g != e { 32 t.Fatalf("chunk writer wrote %q; want %q", g, e) 33 } 34 35 r := NewChunkedReader(&b) 36 data, err := ioutil.ReadAll(r) 37 if err != nil { 38 t.Logf(`data: "%s"`, data) 39 t.Fatalf("ReadAll from reader: %v", err) 40 } 41 if g, e := string(data), chunk1+chunk2; g != e { 42 t.Errorf("chunk reader read %q; want %q", g, e) 43 } 44 } 45 46 func TestChunkReaderAllocs(t *testing.T) { 47 // temporarily set GOMAXPROCS to 1 as we are testing memory allocations 48 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) 49 var buf bytes.Buffer 50 w := NewChunkedWriter(&buf) 51 a, b, c := []byte("aaaaaa"), []byte("bbbbbbbbbbbb"), []byte("cccccccccccccccccccccccc") 52 w.Write(a) 53 w.Write(b) 54 w.Write(c) 55 w.Close() 56 57 r := NewChunkedReader(&buf) 58 readBuf := make([]byte, len(a)+len(b)+len(c)+1) 59 60 var ms runtime.MemStats 61 runtime.ReadMemStats(&ms) 62 m0 := ms.Mallocs 63 64 n, err := io.ReadFull(r, readBuf) 65 66 runtime.ReadMemStats(&ms) 67 mallocs := ms.Mallocs - m0 68 if mallocs > 1 { 69 t.Errorf("%d mallocs; want <= 1", mallocs) 70 } 71 72 if n != len(readBuf)-1 { 73 t.Errorf("read %d bytes; want %d", n, len(readBuf)-1) 74 } 75 if err != io.ErrUnexpectedEOF { 76 t.Errorf("read error = %v; want ErrUnexpectedEOF", err) 77 } 78 } 79 80 func TestParseHexUint(t *testing.T) { 81 for i := uint64(0); i <= 1234; i++ { 82 line := []byte(fmt.Sprintf("%x", i)) 83 got, err := parseHexUint(line) 84 if err != nil { 85 t.Fatalf("on %d: %v", i, err) 86 } 87 if got != i { 88 t.Errorf("for input %q = %d; want %d", line, got, i) 89 } 90 } 91 _, err := parseHexUint([]byte("bogus")) 92 if err == nil { 93 t.Error("expected error on bogus input") 94 } 95 }