timeout_dailer_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package transport
  14. import (
  15. "net"
  16. "testing"
  17. "time"
  18. )
  19. func TestReadWriteTimeoutDialer(t *testing.T) {
  20. stop := make(chan struct{})
  21. ln, err := net.Listen("tcp", "127.0.0.1:0")
  22. if err != nil {
  23. t.Fatalf("unexpected listen error: %v", err)
  24. }
  25. ts := testBlockingServer{ln, 2, stop}
  26. go ts.Start(t)
  27. d := rwTimeoutDialer{
  28. wtimeoutd: 10 * time.Millisecond,
  29. rdtimeoutd: 10 * time.Millisecond,
  30. }
  31. conn, err := d.Dial("tcp", ln.Addr().String())
  32. if err != nil {
  33. t.Fatalf("unexpected dial error: %v", err)
  34. }
  35. defer conn.Close()
  36. // fill the socket buffer
  37. data := make([]byte, 1024*1024)
  38. timer := time.AfterFunc(d.wtimeoutd*5, func() {
  39. t.Fatal("wait timeout")
  40. })
  41. defer timer.Stop()
  42. _, err = conn.Write(data)
  43. if operr, ok := err.(*net.OpError); !ok || operr.Op != "write" || !operr.Timeout() {
  44. t.Errorf("err = %v, want write i/o timeout error", err)
  45. }
  46. timer.Reset(d.rdtimeoutd * 5)
  47. conn, err = d.Dial("tcp", ln.Addr().String())
  48. if err != nil {
  49. t.Fatalf("unexpected dial error: %v", err)
  50. }
  51. defer conn.Close()
  52. buf := make([]byte, 10)
  53. _, err = conn.Read(buf)
  54. if operr, ok := err.(*net.OpError); !ok || operr.Op != "read" || !operr.Timeout() {
  55. t.Errorf("err = %v, want write i/o timeout error", err)
  56. }
  57. stop <- struct{}{}
  58. }
  59. type testBlockingServer struct {
  60. ln net.Listener
  61. n int
  62. stop chan struct{}
  63. }
  64. func (ts *testBlockingServer) Start(t *testing.T) {
  65. for i := 0; i < ts.n; i++ {
  66. conn, err := ts.ln.Accept()
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. defer conn.Close()
  71. }
  72. <-ts.stop
  73. }