github.com/Andyfoo/golang/x/net@v0.0.0-20190901054642-57c1bf301704/nettest/conntest_test.go (about)

     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  
     5  // +build go1.8
     6  
     7  package nettest
     8  
     9  import (
    10  	"net"
    11  	"os"
    12  	"runtime"
    13  	"testing"
    14  )
    15  
    16  func TestTestConn(t *testing.T) {
    17  	tests := []struct{ name, network string }{
    18  		{"TCP", "tcp"},
    19  		{"UnixPipe", "unix"},
    20  		{"UnixPacketPipe", "unixpacket"},
    21  	}
    22  
    23  	for _, tt := range tests {
    24  		t.Run(tt.name, func(t *testing.T) {
    25  			if !TestableNetwork(tt.network) {
    26  				t.Skipf("%s not supported on %s/%s", tt.network, runtime.GOOS, runtime.GOARCH)
    27  			}
    28  
    29  			mp := func() (c1, c2 net.Conn, stop func(), err error) {
    30  				ln, err := NewLocalListener(tt.network)
    31  				if err != nil {
    32  					return nil, nil, nil, err
    33  				}
    34  
    35  				// Start a connection between two endpoints.
    36  				var err1, err2 error
    37  				done := make(chan bool)
    38  				go func() {
    39  					c2, err2 = ln.Accept()
    40  					close(done)
    41  				}()
    42  				c1, err1 = net.Dial(ln.Addr().Network(), ln.Addr().String())
    43  				<-done
    44  
    45  				stop = func() {
    46  					if err1 == nil {
    47  						c1.Close()
    48  					}
    49  					if err2 == nil {
    50  						c2.Close()
    51  					}
    52  					ln.Close()
    53  					switch tt.network {
    54  					case "unix", "unixpacket":
    55  						os.Remove(ln.Addr().String())
    56  					}
    57  				}
    58  
    59  				switch {
    60  				case err1 != nil:
    61  					stop()
    62  					return nil, nil, nil, err1
    63  				case err2 != nil:
    64  					stop()
    65  					return nil, nil, nil, err2
    66  				default:
    67  					return c1, c2, stop, nil
    68  				}
    69  			}
    70  
    71  			TestConn(t, mp)
    72  		})
    73  	}
    74  }