| 119 | } |
| 120 | |
| 121 | func TestDoContextCancellation(t *testing.T) { |
| 122 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 123 | _, _ = w.Write([]byte("partial")) |
| 124 | if f, ok := w.(http.Flusher); ok { |
| 125 | f.Flush() |
| 126 | } |
| 127 | |
| 128 | <-r.Context().Done() |
| 129 | })) |
| 130 | |
| 131 | defer ts.Close() |
| 132 | |
| 133 | client, err := NewClient(Config{ |
| 134 | Address: ts.URL, |
| 135 | }) |
| 136 | if err != nil { |
| 137 | t.Fatalf("failed to create client: %v", err) |
| 138 | } |
| 139 | |
| 140 | req, err := http.NewRequest(http.MethodGet, ts.URL, nil) |
| 141 | if err != nil { |
| 142 | t.Fatalf("failed to create request: %v", err) |
| 143 | } |
| 144 | |
| 145 | ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) |
| 146 | defer cancel() |
| 147 | |
| 148 | start := time.Now() |
| 149 | resp, body, err := client.Do(ctx, req) |
| 150 | elapsed := time.Since(start) |
| 151 | |
| 152 | if !errors.Is(err, context.DeadlineExceeded) { |
| 153 | t.Errorf("expected error %v, got: %v", context.DeadlineExceeded, err) |
| 154 | } |
| 155 | if body != nil { |
| 156 | t.Errorf("expected no body due to cancellation, got: %q", string(body)) |
| 157 | } |
| 158 | if elapsed > 200*time.Millisecond { |
| 159 | t.Errorf("Do did not return promptly on cancellation: took %v", elapsed) |
| 160 | } |
| 161 | |
| 162 | if resp != nil && resp.Body != nil { |
| 163 | resp.Body.Close() |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // Serve any http request with a response of N KB of spaces. |
| 168 | type serveSpaces struct { |