...

Source file src/net/conn_test.go

Documentation: net

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

View as plain text