croc/src/tcp/tcp_test.go

72 lines
1.7 KiB
Go
Raw Normal View History

2019-04-27 18:20:03 +02:00
package tcp
import (
2019-11-18 22:25:51 +01:00
"bytes"
2020-05-06 19:18:39 +02:00
"fmt"
2019-04-27 18:20:03 +02:00
"testing"
"time"
2020-05-06 19:18:39 +02:00
log "github.com/schollz/logger"
2019-04-27 18:20:03 +02:00
"github.com/stretchr/testify/assert"
)
2020-05-06 19:18:39 +02:00
func BenchmarkConnection(b *testing.B) {
log.SetLevel("trace")
go Run("debug", "8283", "pass123", "8284")
time.Sleep(100 * time.Millisecond)
b.ResetTimer()
for i := 0; i < b.N; i++ {
c, _, _, _ := ConnectToTCPServer("localhost:8283", "pass123", fmt.Sprintf("testroom%d", i), 1*time.Minute)
c.Close()
}
}
2019-04-27 18:20:03 +02:00
func TestTCP(t *testing.T) {
2020-05-06 19:18:39 +02:00
log.SetLevel("error")
2019-09-08 15:12:16 +02:00
timeToRoomDeletion = 100 * time.Millisecond
2019-11-18 20:13:36 +01:00
go Run("debug", "8281", "pass123", "8282")
2020-10-22 19:09:04 +02:00
time.Sleep(100 * time.Millisecond)
err := PingServer("localhost:8281")
assert.Nil(t, err)
err = PingServer("localhost:8333")
assert.NotNil(t, err)
2019-04-27 18:20:03 +02:00
time.Sleep(100 * time.Millisecond)
2019-11-18 20:13:36 +01:00
c1, banner, _, err := ConnectToTCPServer("localhost:8281", "pass123", "testRoom", 1*time.Minute)
2019-09-07 19:06:41 +02:00
assert.Equal(t, banner, "8282")
2019-04-27 18:20:03 +02:00
assert.Nil(t, err)
2019-11-18 20:13:36 +01:00
c2, _, _, err := ConnectToTCPServer("localhost:8281", "pass123", "testRoom")
2019-04-27 18:20:03 +02:00
assert.Nil(t, err)
2019-11-18 20:13:36 +01:00
_, _, _, err = ConnectToTCPServer("localhost:8281", "pass123", "testRoom")
2019-04-27 18:20:03 +02:00
assert.NotNil(t, err)
2019-11-18 20:13:36 +01:00
_, _, _, err = ConnectToTCPServer("localhost:8281", "pass123", "testRoom", 1*time.Nanosecond)
2019-09-08 15:12:16 +02:00
assert.NotNil(t, err)
2019-04-27 18:20:03 +02:00
// try sending data
assert.Nil(t, c1.Send([]byte("hello, c2")))
2019-11-18 22:25:51 +01:00
var data []byte
for {
data, err = c2.Receive()
if bytes.Equal(data, []byte{1}) {
continue
}
2019-11-18 22:27:22 +01:00
break
2019-11-18 22:25:51 +01:00
}
2019-04-27 18:20:03 +02:00
assert.Nil(t, err)
assert.Equal(t, []byte("hello, c2"), data)
assert.Nil(t, c2.Send([]byte("hello, c1")))
2019-11-18 22:25:51 +01:00
for {
data, err = c1.Receive()
if bytes.Equal(data, []byte{1}) {
continue
}
2019-11-18 22:27:22 +01:00
break
2019-11-18 22:25:51 +01:00
}
2019-04-27 18:20:03 +02:00
assert.Nil(t, err)
assert.Equal(t, []byte("hello, c1"), data)
c1.Close()
2019-04-30 19:14:21 +02:00
time.Sleep(300 * time.Millisecond)
2019-04-27 18:20:03 +02:00
}