ctxhttp_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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.
  4. package ctxhttp
  5. import (
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/httptest"
  9. "testing"
  10. "time"
  11. "golang.org/x/net/context"
  12. )
  13. const (
  14. requestDuration = 100 * time.Millisecond
  15. requestBody = "ok"
  16. )
  17. func TestNoTimeout(t *testing.T) {
  18. ctx := context.Background()
  19. resp, err := doRequest(ctx)
  20. if resp == nil || err != nil {
  21. t.Fatalf("error received from client: %v %v", err, resp)
  22. }
  23. }
  24. func TestCancel(t *testing.T) {
  25. ctx, cancel := context.WithCancel(context.Background())
  26. go func() {
  27. time.Sleep(requestDuration / 2)
  28. cancel()
  29. }()
  30. resp, err := doRequest(ctx)
  31. if resp != nil || err == nil {
  32. t.Fatalf("expected error, didn't get one. resp: %v", resp)
  33. }
  34. if err != ctx.Err() {
  35. t.Fatalf("expected error from context but got: %v", err)
  36. }
  37. }
  38. func TestCancelAfterRequest(t *testing.T) {
  39. ctx, cancel := context.WithCancel(context.Background())
  40. resp, err := doRequest(ctx)
  41. // Cancel before reading the body.
  42. // Request.Body should still be readable after the context is canceled.
  43. cancel()
  44. b, err := ioutil.ReadAll(resp.Body)
  45. if err != nil || string(b) != requestBody {
  46. t.Fatalf("could not read body: %q %v", b, err)
  47. }
  48. }
  49. func doRequest(ctx context.Context) (*http.Response, error) {
  50. var okHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  51. time.Sleep(requestDuration)
  52. w.Write([]byte(requestBody))
  53. })
  54. serv := httptest.NewServer(okHandler)
  55. defer serv.Close()
  56. return Get(ctx, nil, serv.URL)
  57. }