github.com/qorio/etcd@v0.1.2-0.20131003183127-5cc585af9618/transporter_test.go (about)

     1  package main
     2  
     3  import (
     4  	"crypto/tls"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"testing"
     9  	"time"
    10  )
    11  
    12  func TestTransporterTimeout(t *testing.T) {
    13  
    14  	http.HandleFunc("/timeout", func(w http.ResponseWriter, r *http.Request) {
    15  		fmt.Fprintf(w, "timeout")
    16  		w.(http.Flusher).Flush() // send headers and some body
    17  		time.Sleep(time.Second * 100)
    18  	})
    19  
    20  	go http.ListenAndServe(":8080", nil)
    21  
    22  	conf := tls.Config{}
    23  
    24  	ts := newTransporter("http", conf)
    25  
    26  	ts.Get("http://google.com")
    27  	_, _, err := ts.Get("http://google.com:9999")
    28  	if err == nil {
    29  		t.Fatal("timeout error")
    30  	}
    31  
    32  	res, req, err := ts.Get("http://localhost:8080/timeout")
    33  
    34  	if err != nil {
    35  		t.Fatal("should not timeout")
    36  	}
    37  
    38  	ts.CancelWhenTimeout(req)
    39  
    40  	body, err := ioutil.ReadAll(res.Body)
    41  	if err == nil {
    42  		fmt.Println(string(body))
    43  		t.Fatal("expected an error reading the body")
    44  	}
    45  
    46  	_, _, err = ts.Post("http://google.com:9999", nil)
    47  	if err == nil {
    48  		t.Fatal("timeout error")
    49  	}
    50  
    51  	_, _, err = ts.Get("http://www.google.com")
    52  	if err != nil {
    53  		t.Fatal("get error: ", err.Error())
    54  	}
    55  
    56  	_, _, err = ts.Post("http://www.google.com", nil)
    57  	if err != nil {
    58  		t.Fatal("post error")
    59  	}
    60  
    61  }