go.etcd.io/etcd@v3.3.27+incompatible/pkg/transport/timeout_transport_test.go (about) 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 15 package transport 16 17 import ( 18 "bytes" 19 "io/ioutil" 20 "net/http" 21 "net/http/httptest" 22 "testing" 23 "time" 24 ) 25 26 // TestNewTimeoutTransport tests that NewTimeoutTransport returns a transport 27 // that can dial out timeout connections. 28 func TestNewTimeoutTransport(t *testing.T) { 29 tr, err := NewTimeoutTransport(TLSInfo{}, time.Hour, time.Hour, time.Hour) 30 if err != nil { 31 t.Fatalf("unexpected NewTimeoutTransport error: %v", err) 32 } 33 34 remoteAddr := func(w http.ResponseWriter, r *http.Request) { 35 w.Write([]byte(r.RemoteAddr)) 36 } 37 srv := httptest.NewServer(http.HandlerFunc(remoteAddr)) 38 39 defer srv.Close() 40 conn, err := tr.Dial("tcp", srv.Listener.Addr().String()) 41 if err != nil { 42 t.Fatalf("unexpected dial error: %v", err) 43 } 44 defer conn.Close() 45 46 tconn, ok := conn.(*timeoutConn) 47 if !ok { 48 t.Fatalf("failed to dial out *timeoutConn") 49 } 50 if tconn.rdtimeoutd != time.Hour { 51 t.Errorf("read timeout = %s, want %s", tconn.rdtimeoutd, time.Hour) 52 } 53 if tconn.wtimeoutd != time.Hour { 54 t.Errorf("write timeout = %s, want %s", tconn.wtimeoutd, time.Hour) 55 } 56 57 // ensure not reuse timeout connection 58 req, err := http.NewRequest("GET", srv.URL, nil) 59 if err != nil { 60 t.Fatalf("unexpected err %v", err) 61 } 62 resp, err := tr.RoundTrip(req) 63 if err != nil { 64 t.Fatalf("unexpected err %v", err) 65 } 66 addr0, err := ioutil.ReadAll(resp.Body) 67 resp.Body.Close() 68 if err != nil { 69 t.Fatalf("unexpected err %v", err) 70 } 71 72 resp, err = tr.RoundTrip(req) 73 if err != nil { 74 t.Fatalf("unexpected err %v", err) 75 } 76 addr1, err := ioutil.ReadAll(resp.Body) 77 resp.Body.Close() 78 if err != nil { 79 t.Fatalf("unexpected err %v", err) 80 } 81 82 if bytes.Equal(addr0, addr1) { 83 t.Errorf("addr0 = %s addr1= %s, want not equal", string(addr0), string(addr1)) 84 } 85 }