timeout_transport_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package transport
  15. import (
  16. "bytes"
  17. "io/ioutil"
  18. "net/http"
  19. "net/http/httptest"
  20. "testing"
  21. "time"
  22. )
  23. // TestNewTimeoutTransport tests that NewTimeoutTransport returns a transport
  24. // that can dial out timeout connections.
  25. func TestNewTimeoutTransport(t *testing.T) {
  26. tr, err := NewTimeoutTransport(TLSInfo{}, time.Hour, time.Hour, time.Hour)
  27. if err != nil {
  28. t.Fatalf("unexpected NewTimeoutTransport error: %v", err)
  29. }
  30. remoteAddr := func(w http.ResponseWriter, r *http.Request) {
  31. w.Write([]byte(r.RemoteAddr))
  32. }
  33. srv := httptest.NewServer(http.HandlerFunc(remoteAddr))
  34. defer srv.Close()
  35. conn, err := tr.Dial("tcp", srv.Listener.Addr().String())
  36. if err != nil {
  37. t.Fatalf("unexpected dial error: %v", err)
  38. }
  39. defer conn.Close()
  40. tconn, ok := conn.(*timeoutConn)
  41. if !ok {
  42. t.Fatalf("failed to dial out *timeoutConn")
  43. }
  44. if tconn.rdtimeoutd != time.Hour {
  45. t.Errorf("read timeout = %s, want %s", tconn.rdtimeoutd, time.Hour)
  46. }
  47. if tconn.wtimeoutd != time.Hour {
  48. t.Errorf("write timeout = %s, want %s", tconn.wtimeoutd, time.Hour)
  49. }
  50. // ensure not reuse timeout connection
  51. req, err := http.NewRequest("GET", srv.URL, nil)
  52. if err != nil {
  53. t.Fatalf("unexpected err %v", err)
  54. }
  55. resp, err := tr.RoundTrip(req)
  56. if err != nil {
  57. t.Fatalf("unexpected err %v", err)
  58. }
  59. addr0, err := ioutil.ReadAll(resp.Body)
  60. resp.Body.Close()
  61. if err != nil {
  62. t.Fatalf("unexpected err %v", err)
  63. }
  64. resp, err = tr.RoundTrip(req)
  65. if err != nil {
  66. t.Fatalf("unexpected err %v", err)
  67. }
  68. addr1, err := ioutil.ReadAll(resp.Body)
  69. resp.Body.Close()
  70. if err != nil {
  71. t.Fatalf("unexpected err %v", err)
  72. }
  73. if bytes.Equal(addr0, addr1) {
  74. t.Errorf("addr0 = %s addr1= %s, want not equal", string(addr0), string(addr1))
  75. }
  76. }