golang.org/x/tools@v0.21.0/internal/jsonrpc2/serve_test.go (about)

     1  // Copyright 2020 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  package jsonrpc2
     6  
     7  import (
     8  	"context"
     9  	"net"
    10  	"sync"
    11  	"testing"
    12  	"time"
    13  
    14  	"golang.org/x/tools/internal/stack/stacktest"
    15  	"golang.org/x/tools/internal/testenv"
    16  )
    17  
    18  func TestIdleTimeout(t *testing.T) {
    19  	testenv.NeedsLocalhostNet(t)
    20  
    21  	stacktest.NoLeak(t)
    22  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    23  	defer cancel()
    24  
    25  	ln, err := net.Listen("tcp", "localhost:0")
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  	defer ln.Close()
    30  
    31  	connect := func() net.Conn {
    32  		conn, err := net.DialTimeout("tcp", ln.Addr().String(), 5*time.Second)
    33  		if err != nil {
    34  			panic(err)
    35  		}
    36  		return conn
    37  	}
    38  
    39  	server := HandlerServer(MethodNotFound)
    40  	// connTimer := &fakeTimer{c: make(chan time.Time, 1)}
    41  	var (
    42  		runErr error
    43  		wg     sync.WaitGroup
    44  	)
    45  	wg.Add(1)
    46  	go func() {
    47  		defer wg.Done()
    48  		runErr = Serve(ctx, ln, server, 100*time.Millisecond)
    49  	}()
    50  
    51  	// Exercise some connection/disconnection patterns, and then assert that when
    52  	// our timer fires, the server exits.
    53  	conn1 := connect()
    54  	conn2 := connect()
    55  	conn1.Close()
    56  	conn2.Close()
    57  	conn3 := connect()
    58  	conn3.Close()
    59  
    60  	wg.Wait()
    61  
    62  	if runErr != ErrIdleTimeout {
    63  		t.Errorf("run() returned error %v, want %v", runErr, ErrIdleTimeout)
    64  	}
    65  }