github.com/kafkaliu/etcd@v0.1.2-0.20131007164923-44c16dd30d69/transporter_test.go (about)

     1  /*
     2  Copyright 2013 CoreOS Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package main
    18  
    19  import (
    20  	"crypto/tls"
    21  	"fmt"
    22  	"io/ioutil"
    23  	"net/http"
    24  	"testing"
    25  	"time"
    26  )
    27  
    28  func TestTransporterTimeout(t *testing.T) {
    29  
    30  	http.HandleFunc("/timeout", func(w http.ResponseWriter, r *http.Request) {
    31  		fmt.Fprintf(w, "timeout")
    32  		w.(http.Flusher).Flush() // send headers and some body
    33  		time.Sleep(time.Second * 100)
    34  	})
    35  
    36  	go http.ListenAndServe(":8080", nil)
    37  
    38  	conf := tls.Config{}
    39  
    40  	ts := newTransporter("http", conf)
    41  
    42  	ts.Get("http://google.com")
    43  	_, _, err := ts.Get("http://google.com:9999")
    44  	if err == nil {
    45  		t.Fatal("timeout error")
    46  	}
    47  
    48  	res, req, err := ts.Get("http://localhost:8080/timeout")
    49  
    50  	if err != nil {
    51  		t.Fatal("should not timeout")
    52  	}
    53  
    54  	ts.CancelWhenTimeout(req)
    55  
    56  	body, err := ioutil.ReadAll(res.Body)
    57  	if err == nil {
    58  		fmt.Println(string(body))
    59  		t.Fatal("expected an error reading the body")
    60  	}
    61  
    62  	_, _, err = ts.Post("http://google.com:9999", nil)
    63  	if err == nil {
    64  		t.Fatal("timeout error")
    65  	}
    66  
    67  	_, _, err = ts.Get("http://www.google.com")
    68  	if err != nil {
    69  		t.Fatal("get error: ", err.Error())
    70  	}
    71  
    72  	_, _, err = ts.Post("http://www.google.com", nil)
    73  	if err != nil {
    74  		t.Fatal("post error")
    75  	}
    76  
    77  }