golang-lib/websocket/server_test.go

77 lines
1.2 KiB
Go
Raw Normal View History

2017-10-27 19:40:42 +02:00
package websocket
import (
"net/http"
"net/http/httptest"
2018-08-23 21:02:51 +02:00
"sync"
2017-10-27 19:40:42 +02:00
"testing"
2018-04-26 21:24:42 +02:00
"github.com/google/uuid"
2017-10-27 19:40:42 +02:00
"github.com/stretchr/testify/assert"
)
func TestServer(t *testing.T) {
assert := assert.New(t)
srv := NewServer(nil, NewSessionManager())
assert.NotNil(srv)
req, _ := http.NewRequest("GET", "url", nil)
w := httptest.NewRecorder()
srv.Handler(w, req)
out := make(chan *Message)
c := &Client{
out: out,
server: srv,
}
srv.AddClient(nil)
go srv.AddClient(c)
msg := <-out
assert.Equal(SessionMessageInit, msg.Subject)
srv.DelClient(nil)
srv.DelClient(c)
}
2018-04-26 21:24:42 +02:00
func TestServerSendAll(t *testing.T) {
assert := assert.New(t)
srv := NewServer(nil, nil)
assert.NotNil(srv)
2018-08-23 21:02:51 +02:00
out1 := make(chan *Message, 2)
2018-04-26 21:24:42 +02:00
c1 := &Client{
id: uuid.New(),
out: out1,
server: srv,
}
2018-08-23 21:02:51 +02:00
out2 := make(chan *Message, 2)
2018-04-26 21:24:42 +02:00
c2 := &Client{
id: uuid.New(),
out: out2,
server: srv,
}
srv.AddClient(c1)
srv.AddClient(c2)
2018-08-23 21:02:51 +02:00
wg := sync.WaitGroup{}
2018-04-26 21:24:42 +02:00
2018-08-23 21:02:51 +02:00
client := func(out chan *Message) {
msg := <-out
2018-04-26 21:24:42 +02:00
assert.Equal("hi", msg.Subject)
2018-08-23 21:02:51 +02:00
wg.Done()
}
wg.Add(2)
go client(out1)
go client(out2)
2018-04-26 21:24:42 +02:00
srv.SendAll(&Message{
Subject: "hi",
})
2018-08-23 21:02:51 +02:00
wg.Wait()
2018-04-26 21:24:42 +02:00
srv.DelClient(c2)
srv.DelClient(c1)
}