2020-02-19 16:48:38 -07:00
|
|
|
// Copyright 2020 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package jsonrpc2
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestIdleTimeout(t *testing.T) {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-04-07 13:58:08 -06:00
|
|
|
ln, err := net.Listen("tcp", "localhost:0")
|
2020-02-19 16:48:38 -07:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
defer ln.Close()
|
|
|
|
|
|
|
|
connect := func() net.Conn {
|
|
|
|
conn, err := net.DialTimeout("tcp", ln.Addr().String(), 5*time.Second)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return conn
|
|
|
|
}
|
|
|
|
|
2020-03-30 15:09:42 -06:00
|
|
|
server := HandlerServer(MethodNotFound)
|
2020-02-19 16:48:38 -07:00
|
|
|
// connTimer := &fakeTimer{c: make(chan time.Time, 1)}
|
|
|
|
var (
|
|
|
|
runErr error
|
|
|
|
wg sync.WaitGroup
|
|
|
|
)
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
runErr = Serve(ctx, ln, server, 100*time.Millisecond)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Exercise some connection/disconnection patterns, and then assert that when
|
|
|
|
// our timer fires, the server exits.
|
|
|
|
conn1 := connect()
|
|
|
|
conn2 := connect()
|
|
|
|
conn1.Close()
|
|
|
|
conn2.Close()
|
|
|
|
conn3 := connect()
|
|
|
|
conn3.Close()
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
if runErr != ErrIdleTimeout {
|
|
|
|
t.Errorf("run() returned error %v, want %v", runErr, ErrIdleTimeout)
|
|
|
|
}
|
|
|
|
}
|