1// 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"
9	"io"
10	"strings"
11	"testing"
12)
13
14func TestBodyReadBadTrailer(t *testing.T) {
15	b := &body{
16		src: strings.NewReader("foobar"),
17		hdr: true, // force reading the trailer
18		r:   bufio.NewReader(strings.NewReader("")),
19	}
20	buf := make([]byte, 7)
21	n, err := b.Read(buf[:3])
22	got := string(buf[:n])
23	if got != "foo" || err != nil {
24		t.Fatalf(`first Read = %d (%q), %v; want 3 ("foo")`, n, got, err)
25	}
26
27	n, err = b.Read(buf[:])
28	got = string(buf[:n])
29	if got != "bar" || err != nil {
30		t.Fatalf(`second Read = %d (%q), %v; want 3 ("bar")`, n, got, err)
31	}
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}
39
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}
65