2014-09-02 17:05:22 -04:00
|
|
|
package rpc
|
|
|
|
|
|
|
|
import (
|
2018-12-14 16:59:26 -05:00
|
|
|
"fmt"
|
2014-09-02 17:05:22 -04:00
|
|
|
"net"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/hashicorp/yamux"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestMuxBroker(t *testing.T) {
|
|
|
|
c, s := testYamux(t)
|
|
|
|
defer c.Close()
|
|
|
|
defer s.Close()
|
|
|
|
|
|
|
|
bc := newMuxBroker(c)
|
|
|
|
bs := newMuxBroker(s)
|
|
|
|
go bc.Run()
|
|
|
|
go bs.Run()
|
|
|
|
|
2018-12-14 16:53:39 -05:00
|
|
|
errChan := make(chan error, 1)
|
2014-09-02 17:05:22 -04:00
|
|
|
go func() {
|
2018-12-17 04:58:32 -05:00
|
|
|
defer close(errChan)
|
2014-09-02 17:05:22 -04:00
|
|
|
c, err := bc.Dial(5)
|
|
|
|
if err != nil {
|
2018-12-14 16:59:26 -05:00
|
|
|
errChan <- fmt.Errorf("err dialing: %s", err.Error())
|
2018-12-14 16:53:39 -05:00
|
|
|
return
|
2014-09-02 17:05:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := c.Write([]byte{42}); err != nil {
|
2018-12-14 16:59:26 -05:00
|
|
|
errChan <- fmt.Errorf("err writing: %s", err.Error())
|
2014-09-02 17:05:22 -04:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
client, err := bs.Accept(5)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var data [1]byte
|
|
|
|
if _, err := client.Read(data[:]); err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if data[0] != 42 {
|
|
|
|
t.Fatalf("bad: %d", data[0])
|
|
|
|
}
|
2018-12-14 16:53:39 -05:00
|
|
|
|
|
|
|
for {
|
|
|
|
err, open := <-errChan
|
|
|
|
if !open {
|
|
|
|
if err != nil {
|
2018-12-14 16:59:26 -05:00
|
|
|
t.Fatalf(err.Error())
|
2018-12-14 16:53:39 -05:00
|
|
|
}
|
2018-12-14 16:59:26 -05:00
|
|
|
break
|
2018-12-14 16:53:39 -05:00
|
|
|
}
|
|
|
|
}
|
2014-09-02 17:05:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func testYamux(t *testing.T) (client *yamux.Session, server *yamux.Session) {
|
|
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Server side
|
|
|
|
doneCh := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
defer close(doneCh)
|
|
|
|
conn, err := l.Accept()
|
|
|
|
l.Close()
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
server, err = yamux.Server(conn, nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Client side
|
|
|
|
conn, err := net.Dial("tcp", l.Addr().String())
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
client, err = yamux.Client(conn, nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("err: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for the server
|
|
|
|
<-doneCh
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|