...
Run Format

Source file src/net/http/transfer_test.go

Documentation: net/http

     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  
     5  package http
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"io"
    11  	"io/ioutil"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  func TestBodyReadBadTrailer(t *testing.T) {
    17  	b := &body{
    18  		src: strings.NewReader("foobar"),
    19  		hdr: true, // force reading the trailer
    20  		r:   bufio.NewReader(strings.NewReader("")),
    21  	}
    22  	buf := make([]byte, 7)
    23  	n, err := b.Read(buf[:3])
    24  	got := string(buf[:n])
    25  	if got != "foo" || err != nil {
    26  		t.Fatalf(`first Read = %d (%q), %v; want 3 ("foo")`, n, got, err)
    27  	}
    28  
    29  	n, err = b.Read(buf[:])
    30  	got = string(buf[:n])
    31  	if got != "bar" || err != nil {
    32  		t.Fatalf(`second Read = %d (%q), %v; want 3 ("bar")`, n, got, err)
    33  	}
    34  
    35  	n, err = b.Read(buf[:])
    36  	got = string(buf[:n])
    37  	if err == nil {
    38  		t.Errorf("final Read was successful (%q), expected error from trailer read", got)
    39  	}
    40  }
    41  
    42  func TestFinalChunkedBodyReadEOF(t *testing.T) {
    43  	res, err := ReadResponse(bufio.NewReader(strings.NewReader(
    44  		"HTTP/1.1 200 OK\r\n"+
    45  			"Transfer-Encoding: chunked\r\n"+
    46  			"\r\n"+
    47  			"0a\r\n"+
    48  			"Body here\n\r\n"+
    49  			"09\r\n"+
    50  			"continued\r\n"+
    51  			"0\r\n"+
    52  			"\r\n")), nil)
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	want := "Body here\ncontinued"
    57  	buf := make([]byte, len(want))
    58  	n, err := res.Body.Read(buf)
    59  	if n != len(want) || err != io.EOF {
    60  		t.Logf("body = %#v", res.Body)
    61  		t.Errorf("Read = %v, %v; want %d, EOF", n, err, len(want))
    62  	}
    63  	if string(buf) != want {
    64  		t.Errorf("buf = %q; want %q", buf, want)
    65  	}
    66  }
    67  
    68  func TestDetectInMemoryReaders(t *testing.T) {
    69  	pr, _ := io.Pipe()
    70  	tests := []struct {
    71  		r    io.Reader
    72  		want bool
    73  	}{
    74  		{pr, false},
    75  
    76  		{bytes.NewReader(nil), true},
    77  		{bytes.NewBuffer(nil), true},
    78  		{strings.NewReader(""), true},
    79  
    80  		{ioutil.NopCloser(pr), false},
    81  
    82  		{ioutil.NopCloser(bytes.NewReader(nil)), true},
    83  		{ioutil.NopCloser(bytes.NewBuffer(nil)), true},
    84  		{ioutil.NopCloser(strings.NewReader("")), true},
    85  	}
    86  	for i, tt := range tests {
    87  		got := isKnownInMemoryReader(tt.r)
    88  		if got != tt.want {
    89  			t.Errorf("%d: got = %v; want %v", i, got, tt.want)
    90  		}
    91  	}
    92  }
    93  

View as plain text