Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix tests: Update handlers and use httptest.Server instead #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 26 additions & 24 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package msgkit

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"sync/atomic"
Expand All @@ -13,45 +13,49 @@ import (
)

func TestHandler(t *testing.T) {
const addr = "localhost:17892"
const connsN = 10 // number of concurrent sockets
const msgsN = 1000 // number of messages per socket

s := NewServer(nil)

// create handlers
s.Handle("h0", func(so *Socket, msg *Message) { so.Send("h0", msg.Data) })
s.Handle("h1", func(so *Socket, msg *Message) { so.Send("h1", msg.Data) })
s.Handle("h2", func(so *Socket, msg *Message) { so.Send("h2", msg.Data) })
s.Handle("h0", func(so *Socket, msg *Message) (err error) {
so.Send("h0", msg.Data)
return
})
s.Handle("h1", func(so *Socket, msg *Message) (err error) {
so.Send("h1", msg.Data)
return
})
s.Handle("h2", func(so *Socket, msg *Message) (err error) {
so.Send("h2", msg.Data)
return
})

// count the number of opens
var opened int32
s.Handle("connected", func(_ *Socket, _ *Message) { atomic.AddInt32(&opened, 1) })
s.Handle("connected", func(_ *Socket, _ *Message) (err error) {
atomic.AddInt32(&opened, 1)
return
})

// count/wait on all closes
var cwg sync.WaitGroup
cwg.Add(connsN)
s.Handle("disconnected", func(_ *Socket, _ *Message) { cwg.Done() })
s.Handle("disconnected", func(_ *Socket, _ *Message) (err error) {
cwg.Done()
return
})

srv := &http.Server{Addr: addr}
http.Handle("/ws", s)
ts := httptest.NewServer(s)
defer ts.Close()

var swg sync.WaitGroup
swg.Add(1)
go func() {
defer swg.Done()
if err := srv.ListenAndServe(); err != nil {
if err.Error() != "http: Server closed" {
panic(err)
}
}
}()
var wg sync.WaitGroup
wg.Add(connsN)
for i := 0; i < connsN; i++ {
go func(i int) {
defer wg.Done()
u := url.URL{Scheme: "ws", Host: addr, Path: "/ws"}
u := url.URL{Scheme: "ws", Host: ts.Listener.Addr().String(), Path: "/ws"}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
panic(err)
Expand Down Expand Up @@ -80,12 +84,10 @@ func TestHandler(t *testing.T) {
}
}(i)
}

wg.Wait()
if err := srv.Shutdown(nil); err != nil {
t.Fatal(err)
}
swg.Wait()
cwg.Wait()

if opened != connsN {
t.Fatalf("expected '%v', got '%v'", connsN, opened)
}
Expand Down