1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-06 10:20:44 -05:00
v2fly/transport/internet/kcp/connection_test.go

74 lines
1.9 KiB
Go
Raw Normal View History

2016-07-12 07:27:12 -04:00
package kcp_test
import (
2016-07-12 11:11:36 -04:00
"crypto/rand"
"io"
"net"
2016-07-12 07:27:12 -04:00
"testing"
"time"
2016-07-12 11:11:36 -04:00
v2net "github.com/v2ray/v2ray-core/common/net"
2016-07-12 07:27:12 -04:00
"github.com/v2ray/v2ray-core/testing/assert"
. "github.com/v2ray/v2ray-core/transport/internet/kcp"
)
2016-07-12 11:11:36 -04:00
type NoOpWriteCloser struct{}
func (this *NoOpWriteCloser) Write(b []byte) (int, error) {
return len(b), nil
}
func (this *NoOpWriteCloser) Close() error {
return nil
}
2016-07-12 07:27:12 -04:00
func TestConnectionReadTimeout(t *testing.T) {
assert := assert.On(t)
2016-07-12 11:11:36 -04:00
conn := NewConnection(1, &NoOpWriteCloser{}, nil, nil, NewSimpleAuthenticator())
2016-07-12 07:27:12 -04:00
conn.SetReadDeadline(time.Now().Add(time.Second))
b := make([]byte, 1024)
nBytes, err := conn.Read(b)
assert.Int(nBytes).Equals(0)
assert.Error(err).IsNotNil()
}
2016-07-12 11:11:36 -04:00
func TestConnectionReadWrite(t *testing.T) {
assert := assert.On(t)
upReader, upWriter := io.Pipe()
downReader, downWriter := io.Pipe()
connClient := NewConnection(1, upWriter, &net.UDPAddr{IP: v2net.LocalHostIP.IP(), Port: 1}, &net.UDPAddr{IP: v2net.LocalHostIP.IP(), Port: 2}, NewSimpleAuthenticator())
go connClient.FetchInputFrom(downReader)
connServer := NewConnection(1, downWriter, &net.UDPAddr{IP: v2net.LocalHostIP.IP(), Port: 2}, &net.UDPAddr{IP: v2net.LocalHostIP.IP(), Port: 1}, NewSimpleAuthenticator())
go connServer.FetchInputFrom(upReader)
totalWritten := 1024 * 1024
clientSend := make([]byte, totalWritten)
rand.Read(clientSend)
2016-07-14 15:31:04 -04:00
go func() {
nBytes, err := connClient.Write(clientSend)
assert.Int(nBytes).Equals(totalWritten)
assert.Error(err).IsNil()
}()
2016-07-12 11:11:36 -04:00
serverReceived := make([]byte, totalWritten)
totalRead := 0
for totalRead < totalWritten {
2016-07-14 15:31:04 -04:00
nBytes, err := connServer.Read(serverReceived[totalRead:])
2016-07-12 11:11:36 -04:00
assert.Error(err).IsNil()
totalRead += nBytes
}
assert.Bytes(serverReceived).Equals(clientSend)
2016-07-14 15:31:04 -04:00
connClient.Close()
connServer.Close()
for connClient.State() != StateTerminated || connServer.State() != StateTerminated {
time.Sleep(time.Second)
}
2016-07-12 11:11:36 -04:00
}