transporter_test.go 1.1 KB

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