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)
2017-10-27 19:40:42 +02:00
msg := <-out
assert.Equal(SessionMessageInit, msg.Subject)
srv.delClient(nil)
srv.delClient(c)
2017-10-27 19:40:42 +02:00
}
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-04-26 21:24:42 +02:00
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)
2018-04-26 21:24:42 +02:00
}