timeout_dialer_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2015 CoreOS, Inc.
  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. "net"
  17. "testing"
  18. "time"
  19. )
  20. func TestReadWriteTimeoutDialer(t *testing.T) {
  21. stop := make(chan struct{})
  22. ln, err := net.Listen("tcp", "127.0.0.1:0")
  23. if err != nil {
  24. t.Fatalf("unexpected listen error: %v", err)
  25. }
  26. ts := testBlockingServer{ln, 2, stop}
  27. go ts.Start(t)
  28. d := rwTimeoutDialer{
  29. wtimeoutd: 10 * time.Millisecond,
  30. rdtimeoutd: 10 * time.Millisecond,
  31. }
  32. conn, err := d.Dial("tcp", ln.Addr().String())
  33. if err != nil {
  34. t.Fatalf("unexpected dial error: %v", err)
  35. }
  36. defer conn.Close()
  37. // fill the socket buffer
  38. data := make([]byte, 5*1024*1024)
  39. timer := time.AfterFunc(d.wtimeoutd*5, func() {
  40. t.Fatal("wait timeout")
  41. })
  42. defer timer.Stop()
  43. _, err = conn.Write(data)
  44. if operr, ok := err.(*net.OpError); !ok || operr.Op != "write" || !operr.Timeout() {
  45. t.Errorf("err = %v, want write i/o timeout error", err)
  46. }
  47. timer.Reset(d.rdtimeoutd * 5)
  48. conn, err = d.Dial("tcp", ln.Addr().String())
  49. if err != nil {
  50. t.Fatalf("unexpected dial error: %v", err)
  51. }
  52. defer conn.Close()
  53. buf := make([]byte, 10)
  54. _, err = conn.Read(buf)
  55. if operr, ok := err.(*net.OpError); !ok || operr.Op != "read" || !operr.Timeout() {
  56. t.Errorf("err = %v, want write i/o timeout error", err)
  57. }
  58. stop <- struct{}{}
  59. }
  60. type testBlockingServer struct {
  61. ln net.Listener
  62. n int
  63. stop chan struct{}
  64. }
  65. func (ts *testBlockingServer) Start(t *testing.T) {
  66. for i := 0; i < ts.n; i++ {
  67. conn, err := ts.ln.Accept()
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. defer conn.Close()
  72. }
  73. <-ts.stop
  74. }