conntest_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build go1.8
  5. package nettest
  6. import (
  7. "net"
  8. "os"
  9. "runtime"
  10. "testing"
  11. )
  12. func TestTestConn(t *testing.T) {
  13. tests := []struct{ name, network string }{
  14. {"TCP", "tcp"},
  15. {"UnixPipe", "unix"},
  16. {"UnixPacketPipe", "unixpacket"},
  17. }
  18. for _, tt := range tests {
  19. t.Run(tt.name, func(t *testing.T) {
  20. if !TestableNetwork(tt.network) {
  21. t.Skipf("%s not supported on %s/%s", tt.network, runtime.GOOS, runtime.GOARCH)
  22. }
  23. mp := func() (c1, c2 net.Conn, stop func(), err error) {
  24. ln, err := NewLocalListener(tt.network)
  25. if err != nil {
  26. return nil, nil, nil, err
  27. }
  28. // Start a connection between two endpoints.
  29. var err1, err2 error
  30. done := make(chan bool)
  31. go func() {
  32. c2, err2 = ln.Accept()
  33. close(done)
  34. }()
  35. c1, err1 = net.Dial(ln.Addr().Network(), ln.Addr().String())
  36. <-done
  37. stop = func() {
  38. if err1 == nil {
  39. c1.Close()
  40. }
  41. if err2 == nil {
  42. c2.Close()
  43. }
  44. ln.Close()
  45. switch tt.network {
  46. case "unix", "unixpacket":
  47. os.Remove(ln.Addr().String())
  48. }
  49. }
  50. switch {
  51. case err1 != nil:
  52. stop()
  53. return nil, nil, nil, err1
  54. case err2 != nil:
  55. stop()
  56. return nil, nil, nil, err2
  57. default:
  58. return c1, c2, stop, nil
  59. }
  60. }
  61. TestConn(t, mp)
  62. })
  63. }
  64. }