8 "github.com/stretchr/testify/assert"
9 "github.com/stretchr/testify/require"
12 func createMConnection(conn net.Conn) *MConnection {
13 onReceive := func(chID byte, msgBytes []byte) {
15 onError := func(r interface{}) {
17 c := createMConnectionWithCallbacks(conn, onReceive, onError)
21 func createMConnectionWithCallbacks(conn net.Conn, onReceive func(chID byte, msgBytes []byte), onError func(r interface{})) *MConnection {
22 chDescs := []*ChannelDescriptor{&ChannelDescriptor{ID: 0x01, Priority: 1, SendQueueCapacity: 1}}
23 c := NewMConnectionWithConfig(conn, chDescs, onReceive, onError, DefaultMConnConfig())
27 func TestMConnectionSend(t *testing.T) {
28 assert, require := assert.New(t), require.New(t)
30 server, client := net.Pipe()
34 mconn := createMConnection(client)
35 _, err := mconn.Start()
40 assert.True(mconn.Send(0x01, msg))
41 // Note: subsequent Send/TrySend calls could pass because we are reading from
42 // the send queue in a separate goroutine.
43 server.Read(make([]byte, len(msg)))
44 assert.True(mconn.CanSend(0x01))
47 assert.True(mconn.TrySend(0x01, msg))
48 server.Read(make([]byte, len(msg)))
50 assert.False(mconn.CanSend(0x05), "CanSend should return false because channel is unknown")
51 assert.False(mconn.Send(0x05, "Absorbing Man"), "Send should return false because channel is unknown")
54 func TestMConnectionReceive(t *testing.T) {
55 assert, require := assert.New(t), require.New(t)
57 server, client := net.Pipe()
61 receivedCh := make(chan []byte)
62 errorsCh := make(chan interface{})
63 onReceive := func(chID byte, msgBytes []byte) {
64 receivedCh <- msgBytes
66 onError := func(r interface{}) {
69 mconn1 := createMConnectionWithCallbacks(client, onReceive, onError)
70 _, err := mconn1.Start()
74 mconn2 := createMConnection(server)
75 _, err = mconn2.Start()
80 assert.True(mconn2.Send(0x01, msg))
83 case receivedBytes := <-receivedCh:
84 assert.Equal([]byte(msg), receivedBytes[2:]) // first 3 bytes are internal
85 case err := <-errorsCh:
86 t.Fatalf("Expected %s, got %+v", msg, err)
87 case <-time.After(500 * time.Millisecond):
88 t.Fatalf("Did not receive %s message in 500ms", msg)
92 func TestMConnectionStopsAndReturnsError(t *testing.T) {
93 assert, require := assert.New(t), require.New(t)
95 server, client := net.Pipe()
99 receivedCh := make(chan []byte)
100 errorsCh := make(chan interface{})
101 onReceive := func(chID byte, msgBytes []byte) {
102 receivedCh <- msgBytes
104 onError := func(r interface{}) {
107 mconn := createMConnectionWithCallbacks(client, onReceive, onError)
108 _, err := mconn.Start()
115 case receivedBytes := <-receivedCh:
116 t.Fatalf("Expected error, got %v", receivedBytes)
117 case err := <-errorsCh:
119 assert.False(mconn.IsRunning())
120 case <-time.After(500 * time.Millisecond):
121 t.Fatal("Did not receive error in 500ms")