timeout_dialer_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. done := make(chan struct{})
  40. go func() {
  41. _, err = conn.Write(data)
  42. done <- struct{}{}
  43. }()
  44. select {
  45. case <-done:
  46. // It waits 1s more to avoid delay in low-end system.
  47. case <-time.After(d.wtimeoutd*10 + time.Second):
  48. t.Fatal("wait timeout")
  49. }
  50. if operr, ok := err.(*net.OpError); !ok || operr.Op != "write" || !operr.Timeout() {
  51. t.Errorf("err = %v, want write i/o timeout error", err)
  52. }
  53. conn, err = d.Dial("tcp", ln.Addr().String())
  54. if err != nil {
  55. t.Fatalf("unexpected dial error: %v", err)
  56. }
  57. defer conn.Close()
  58. buf := make([]byte, 10)
  59. go func() {
  60. _, err = conn.Read(buf)
  61. done <- struct{}{}
  62. }()
  63. select {
  64. case <-done:
  65. case <-time.After(d.rdtimeoutd * 10):
  66. t.Fatal("wait timeout")
  67. }
  68. if operr, ok := err.(*net.OpError); !ok || operr.Op != "read" || !operr.Timeout() {
  69. t.Errorf("err = %v, want write i/o timeout error", err)
  70. }
  71. stop <- struct{}{}
  72. }
  73. type testBlockingServer struct {
  74. ln net.Listener
  75. n int
  76. stop chan struct{}
  77. }
  78. func (ts *testBlockingServer) Start(t *testing.T) {
  79. for i := 0; i < ts.n; i++ {
  80. conn, err := ts.ln.Accept()
  81. if err != nil {
  82. t.Fatal(err)
  83. }
  84. defer conn.Close()
  85. }
  86. <-ts.stop
  87. }