1 // Copyright 2015 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.
17 "golang.org/x/net/context"
21 requestDuration = 100 * time.Millisecond
25 func okHandler(w http.ResponseWriter, r *http.Request) {
26 time.Sleep(requestDuration)
27 io.WriteString(w, requestBody)
30 func TestNoTimeout(t *testing.T) {
31 ts := httptest.NewServer(http.HandlerFunc(okHandler))
34 ctx := context.Background()
35 res, err := Get(ctx, nil, ts.URL)
39 defer res.Body.Close()
40 slurp, err := ioutil.ReadAll(res.Body)
44 if string(slurp) != requestBody {
45 t.Errorf("body = %q; want %q", slurp, requestBody)
49 func TestCancelBeforeHeaders(t *testing.T) {
50 ctx, cancel := context.WithCancel(context.Background())
52 blockServer := make(chan struct{})
53 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
56 io.WriteString(w, requestBody)
59 defer close(blockServer)
61 res, err := Get(ctx, nil, ts.URL)
64 t.Fatal("Get returned unexpected nil error")
66 if err != context.Canceled {
67 t.Errorf("err = %v; want %v", err, context.Canceled)
71 func TestCancelAfterHangingRequest(t *testing.T) {
72 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
73 w.WriteHeader(http.StatusOK)
74 w.(http.Flusher).Flush()
75 <-w.(http.CloseNotifier).CloseNotify()
79 ctx, cancel := context.WithCancel(context.Background())
80 resp, err := Get(ctx, nil, ts.URL)
82 t.Fatalf("unexpected error in Get: %v", err)
85 // Cancel befer reading the body.
86 // Reading Request.Body should fail, since the request was
87 // canceled before anything was written.
90 done := make(chan struct{})
93 b, err := ioutil.ReadAll(resp.Body)
94 if len(b) != 0 || err == nil {
95 t.Errorf(`Read got (%q, %v); want ("", error)`, b, err)
101 case <-time.After(1 * time.Second):
102 t.Errorf("Test timed out")