Source file src/net/conn_test.go

     1  // Copyright 2012 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  // This file implements API tests across platforms and will never have a build
     6  // tag.
     7  
     8  //go:build !js
     9  
    10  package net
    11  
    12  import (
    13  	"testing"
    14  	"time"
    15  )
    16  
    17  // someTimeout is used just to test that net.Conn implementations
    18  // don't explode when their SetFooDeadline methods are called.
    19  // It isn't actually used for testing timeouts.
    20  const someTimeout = 1 * time.Hour
    21  
    22  func TestConnAndListener(t *testing.T) {
    23  	for i, network := range []string{"tcp", "unix", "unixpacket"} {
    24  		if !testableNetwork(network) {
    25  			t.Logf("skipping %s test", network)
    26  			continue
    27  		}
    28  
    29  		ls := newLocalServer(t, network)
    30  		defer ls.teardown()
    31  		ch := make(chan error, 1)
    32  		handler := func(ls *localServer, ln Listener) { ls.transponder(ln, ch) }
    33  		if err := ls.buildup(handler); err != nil {
    34  			t.Fatal(err)
    35  		}
    36  		if ls.Listener.Addr().Network() != network {
    37  			t.Fatalf("got %s; want %s", ls.Listener.Addr().Network(), network)
    38  		}
    39  
    40  		c, err := Dial(ls.Listener.Addr().Network(), ls.Listener.Addr().String())
    41  		if err != nil {
    42  			t.Fatal(err)
    43  		}
    44  		defer c.Close()
    45  		if c.LocalAddr().Network() != network || c.RemoteAddr().Network() != network {
    46  			t.Fatalf("got %s->%s; want %s->%s", c.LocalAddr().Network(), c.RemoteAddr().Network(), network, network)
    47  		}
    48  		c.SetDeadline(time.Now().Add(someTimeout))
    49  		c.SetReadDeadline(time.Now().Add(someTimeout))
    50  		c.SetWriteDeadline(time.Now().Add(someTimeout))
    51  
    52  		if _, err := c.Write([]byte("CONN AND LISTENER TEST")); err != nil {
    53  			t.Fatal(err)
    54  		}
    55  		rb := make([]byte, 128)
    56  		if _, err := c.Read(rb); err != nil {
    57  			t.Fatal(err)
    58  		}
    59  
    60  		for err := range ch {
    61  			t.Errorf("#%d: %v", i, err)
    62  		}
    63  	}
    64  }
    65  

View as plain text