blob: 48cd540b9f75ae034319ecae6969baff8af98ce9 [file] [log] [blame]
Brad Fitzpatrick56bcef02012-11-13 22:38:25 -08001// Copyright 2012 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
5package http
6
7import (
8 "bufio"
Brad Fitzpatrickff29be12014-01-29 13:44:21 +01009 "io"
Brad Fitzpatrick56bcef02012-11-13 22:38:25 -080010 "strings"
11 "testing"
12)
13
14func TestBodyReadBadTrailer(t *testing.T) {
15 b := &body{
Brad Fitzpatrickaffab3f2014-01-07 10:40:56 -080016 src: strings.NewReader("foobar"),
17 hdr: true, // force reading the trailer
18 r: bufio.NewReader(strings.NewReader("")),
Brad Fitzpatrick56bcef02012-11-13 22:38:25 -080019 }
20 buf := make([]byte, 7)
21 n, err := b.Read(buf[:3])
22 got := string(buf[:n])
23 if got != "foo" || err != nil {
Robin Eklind4f250132012-11-16 17:24:43 -080024 t.Fatalf(`first Read = %d (%q), %v; want 3 ("foo")`, n, got, err)
Brad Fitzpatrick56bcef02012-11-13 22:38:25 -080025 }
26
27 n, err = b.Read(buf[:])
28 got = string(buf[:n])
29 if got != "bar" || err != nil {
Robin Eklind4f250132012-11-16 17:24:43 -080030 t.Fatalf(`second Read = %d (%q), %v; want 3 ("bar")`, n, got, err)
Brad Fitzpatrick56bcef02012-11-13 22:38:25 -080031 }
32
33 n, err = b.Read(buf[:])
34 got = string(buf[:n])
35 if err == nil {
36 t.Errorf("final Read was successful (%q), expected error from trailer read", got)
37 }
38}
Brad Fitzpatrickff29be12014-01-29 13:44:21 +010039
40func TestFinalChunkedBodyReadEOF(t *testing.T) {
41 res, err := ReadResponse(bufio.NewReader(strings.NewReader(
42 "HTTP/1.1 200 OK\r\n"+
43 "Transfer-Encoding: chunked\r\n"+
44 "\r\n"+
45 "0a\r\n"+
46 "Body here\n\r\n"+
47 "09\r\n"+
48 "continued\r\n"+
49 "0\r\n"+
50 "\r\n")), nil)
51 if err != nil {
52 t.Fatal(err)
53 }
54 want := "Body here\ncontinued"
55 buf := make([]byte, len(want))
56 n, err := res.Body.Read(buf)
57 if n != len(want) || err != io.EOF {
58 t.Logf("body = %#v", res.Body)
59 t.Errorf("Read = %v, %v; want %d, EOF", n, err, len(want))
60 }
61 if string(buf) != want {
62 t.Errorf("buf = %q; want %q", buf, want)
63 }
64}