Handle arithmetic on eliminated address indices [PR116413]
[official-gcc.git] / libgo / go / net / http / transfer_test.go
blobf0c28b26299a8dd9b43358214be991fc4d7bd1cd
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.
5 package http
7 import (
8 "bufio"
9 "bytes"
10 "crypto/rand"
11 "fmt"
12 "io"
13 "os"
14 "reflect"
15 "strings"
16 "testing"
19 func TestBodyReadBadTrailer(t *testing.T) {
20 b := &body{
21 src: strings.NewReader("foobar"),
22 hdr: true, // force reading the trailer
23 r: bufio.NewReader(strings.NewReader("")),
25 buf := make([]byte, 7)
26 n, err := b.Read(buf[:3])
27 got := string(buf[:n])
28 if got != "foo" || err != nil {
29 t.Fatalf(`first Read = %d (%q), %v; want 3 ("foo")`, n, got, err)
32 n, err = b.Read(buf[:])
33 got = string(buf[:n])
34 if got != "bar" || err != nil {
35 t.Fatalf(`second Read = %d (%q), %v; want 3 ("bar")`, n, got, err)
38 n, err = b.Read(buf[:])
39 got = string(buf[:n])
40 if err == nil {
41 t.Errorf("final Read was successful (%q), expected error from trailer read", got)
45 func TestFinalChunkedBodyReadEOF(t *testing.T) {
46 res, err := ReadResponse(bufio.NewReader(strings.NewReader(
47 "HTTP/1.1 200 OK\r\n"+
48 "Transfer-Encoding: chunked\r\n"+
49 "\r\n"+
50 "0a\r\n"+
51 "Body here\n\r\n"+
52 "09\r\n"+
53 "continued\r\n"+
54 "0\r\n"+
55 "\r\n")), nil)
56 if err != nil {
57 t.Fatal(err)
59 want := "Body here\ncontinued"
60 buf := make([]byte, len(want))
61 n, err := res.Body.Read(buf)
62 if n != len(want) || err != io.EOF {
63 t.Logf("body = %#v", res.Body)
64 t.Errorf("Read = %v, %v; want %d, EOF", n, err, len(want))
66 if string(buf) != want {
67 t.Errorf("buf = %q; want %q", buf, want)
71 func TestDetectInMemoryReaders(t *testing.T) {
72 pr, _ := io.Pipe()
73 tests := []struct {
74 r io.Reader
75 want bool
77 {pr, false},
79 {bytes.NewReader(nil), true},
80 {bytes.NewBuffer(nil), true},
81 {strings.NewReader(""), true},
83 {io.NopCloser(pr), false},
85 {io.NopCloser(bytes.NewReader(nil)), true},
86 {io.NopCloser(bytes.NewBuffer(nil)), true},
87 {io.NopCloser(strings.NewReader("")), true},
89 for i, tt := range tests {
90 got := isKnownInMemoryReader(tt.r)
91 if got != tt.want {
92 t.Errorf("%d: got = %v; want %v", i, got, tt.want)
97 type mockTransferWriter struct {
98 CalledReader io.Reader
99 WriteCalled bool
102 var _ io.ReaderFrom = (*mockTransferWriter)(nil)
104 func (w *mockTransferWriter) ReadFrom(r io.Reader) (int64, error) {
105 w.CalledReader = r
106 return io.Copy(io.Discard, r)
109 func (w *mockTransferWriter) Write(p []byte) (int, error) {
110 w.WriteCalled = true
111 return io.Discard.Write(p)
114 func TestTransferWriterWriteBodyReaderTypes(t *testing.T) {
115 fileType := reflect.TypeOf(&os.File{})
116 bufferType := reflect.TypeOf(&bytes.Buffer{})
118 nBytes := int64(1 << 10)
119 newFileFunc := func() (r io.Reader, done func(), err error) {
120 f, err := os.CreateTemp("", "net-http-newfilefunc")
121 if err != nil {
122 return nil, nil, err
125 // Write some bytes to the file to enable reading.
126 if _, err := io.CopyN(f, rand.Reader, nBytes); err != nil {
127 return nil, nil, fmt.Errorf("failed to write data to file: %v", err)
129 if _, err := f.Seek(0, 0); err != nil {
130 return nil, nil, fmt.Errorf("failed to seek to front: %v", err)
133 done = func() {
134 f.Close()
135 os.Remove(f.Name())
138 return f, done, nil
141 newBufferFunc := func() (io.Reader, func(), error) {
142 return bytes.NewBuffer(make([]byte, nBytes)), func() {}, nil
145 cases := []struct {
146 name string
147 bodyFunc func() (io.Reader, func(), error)
148 method string
149 contentLength int64
150 transferEncoding []string
151 limitedReader bool
152 expectedReader reflect.Type
153 expectedWrite bool
156 name: "file, non-chunked, size set",
157 bodyFunc: newFileFunc,
158 method: "PUT",
159 contentLength: nBytes,
160 limitedReader: true,
161 expectedReader: fileType,
164 name: "file, non-chunked, size set, nopCloser wrapped",
165 method: "PUT",
166 bodyFunc: func() (io.Reader, func(), error) {
167 r, cleanup, err := newFileFunc()
168 return io.NopCloser(r), cleanup, err
170 contentLength: nBytes,
171 limitedReader: true,
172 expectedReader: fileType,
175 name: "file, non-chunked, negative size",
176 method: "PUT",
177 bodyFunc: newFileFunc,
178 contentLength: -1,
179 expectedReader: fileType,
182 name: "file, non-chunked, CONNECT, negative size",
183 method: "CONNECT",
184 bodyFunc: newFileFunc,
185 contentLength: -1,
186 expectedReader: fileType,
189 name: "file, chunked",
190 method: "PUT",
191 bodyFunc: newFileFunc,
192 transferEncoding: []string{"chunked"},
193 expectedWrite: true,
196 name: "buffer, non-chunked, size set",
197 bodyFunc: newBufferFunc,
198 method: "PUT",
199 contentLength: nBytes,
200 limitedReader: true,
201 expectedReader: bufferType,
204 name: "buffer, non-chunked, size set, nopCloser wrapped",
205 method: "PUT",
206 bodyFunc: func() (io.Reader, func(), error) {
207 r, cleanup, err := newBufferFunc()
208 return io.NopCloser(r), cleanup, err
210 contentLength: nBytes,
211 limitedReader: true,
212 expectedReader: bufferType,
215 name: "buffer, non-chunked, negative size",
216 method: "PUT",
217 bodyFunc: newBufferFunc,
218 contentLength: -1,
219 expectedWrite: true,
222 name: "buffer, non-chunked, CONNECT, negative size",
223 method: "CONNECT",
224 bodyFunc: newBufferFunc,
225 contentLength: -1,
226 expectedWrite: true,
229 name: "buffer, chunked",
230 method: "PUT",
231 bodyFunc: newBufferFunc,
232 transferEncoding: []string{"chunked"},
233 expectedWrite: true,
237 for _, tc := range cases {
238 t.Run(tc.name, func(t *testing.T) {
239 body, cleanup, err := tc.bodyFunc()
240 if err != nil {
241 t.Fatal(err)
243 defer cleanup()
245 mw := &mockTransferWriter{}
246 tw := &transferWriter{
247 Body: body,
248 ContentLength: tc.contentLength,
249 TransferEncoding: tc.transferEncoding,
252 if err := tw.writeBody(mw); err != nil {
253 t.Fatal(err)
256 if tc.expectedReader != nil {
257 if mw.CalledReader == nil {
258 t.Fatal("did not call ReadFrom")
261 var actualReader reflect.Type
262 lr, ok := mw.CalledReader.(*io.LimitedReader)
263 if ok && tc.limitedReader {
264 actualReader = reflect.TypeOf(lr.R)
265 } else {
266 actualReader = reflect.TypeOf(mw.CalledReader)
269 if tc.expectedReader != actualReader {
270 t.Fatalf("got reader %T want %T", actualReader, tc.expectedReader)
274 if tc.expectedWrite && !mw.WriteCalled {
275 t.Fatal("did not invoke Write")
281 func TestParseTransferEncoding(t *testing.T) {
282 tests := []struct {
283 hdr Header
284 wantErr error
287 hdr: Header{"Transfer-Encoding": {"fugazi"}},
288 wantErr: &unsupportedTEError{`unsupported transfer encoding: "fugazi"`},
291 hdr: Header{"Transfer-Encoding": {"chunked, chunked", "identity", "chunked"}},
292 wantErr: &unsupportedTEError{`too many transfer encodings: ["chunked, chunked" "identity" "chunked"]`},
295 hdr: Header{"Transfer-Encoding": {""}},
296 wantErr: &unsupportedTEError{`unsupported transfer encoding: ""`},
299 hdr: Header{"Transfer-Encoding": {"chunked, identity"}},
300 wantErr: &unsupportedTEError{`unsupported transfer encoding: "chunked, identity"`},
303 hdr: Header{"Transfer-Encoding": {"chunked", "identity"}},
304 wantErr: &unsupportedTEError{`too many transfer encodings: ["chunked" "identity"]`},
307 hdr: Header{"Transfer-Encoding": {"\x0bchunked"}},
308 wantErr: &unsupportedTEError{`unsupported transfer encoding: "\vchunked"`},
311 hdr: Header{"Transfer-Encoding": {"chunked"}},
312 wantErr: nil,
316 for i, tt := range tests {
317 tr := &transferReader{
318 Header: tt.hdr,
319 ProtoMajor: 1,
320 ProtoMinor: 1,
322 gotErr := tr.parseTransferEncoding()
323 if !reflect.DeepEqual(gotErr, tt.wantErr) {
324 t.Errorf("%d.\ngot error:\n%v\nwant error:\n%v\n\n", i, gotErr, tt.wantErr)
329 // issue 39017 - disallow Content-Length values such as "+3"
330 func TestParseContentLength(t *testing.T) {
331 tests := []struct {
332 cl string
333 wantErr error
336 cl: "3",
337 wantErr: nil,
340 cl: "+3",
341 wantErr: badStringError("bad Content-Length", "+3"),
344 cl: "-3",
345 wantErr: badStringError("bad Content-Length", "-3"),
348 // max int64, for safe conversion before returning
349 cl: "9223372036854775807",
350 wantErr: nil,
353 cl: "9223372036854775808",
354 wantErr: badStringError("bad Content-Length", "9223372036854775808"),
358 for _, tt := range tests {
359 if _, gotErr := parseContentLength(tt.cl); !reflect.DeepEqual(gotErr, tt.wantErr) {
360 t.Errorf("%q:\n\tgot=%v\n\twant=%v", tt.cl, gotErr, tt.wantErr)