Skip to content

Commit

Permalink
fix(gnodev): racy emitter test (#2022)
Browse files Browse the repository at this point in the history
  • Loading branch information
gfanton authored May 3, 2024
1 parent 6482c18 commit 56b5bc0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
13 changes: 12 additions & 1 deletion contribs/gnodev/pkg/emitter/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type Server struct {
logger *slog.Logger
upgrader websocket.Upgrader
clients map[*websocket.Conn]struct{}
muClients sync.Mutex
muClients sync.RWMutex
}

func NewServer(logger *slog.Logger) *Server {
Expand Down Expand Up @@ -85,3 +85,14 @@ func (s *Server) emit(evt events.Event) {
}
}
}

func (s *Server) conns() []*websocket.Conn {
s.muClients.RLock()
conns := make([]*websocket.Conn, 0, len(s.clients))
for conn := range s.clients {
conns = append(conns, conn)
}
s.muClients.RUnlock()

return conns
}
13 changes: 7 additions & 6 deletions contribs/gnodev/pkg/emitter/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/gnolang/gno/contribs/gnodev/pkg/events"
"github.com/gnolang/gno/tm2/pkg/log"
Expand All @@ -21,22 +22,22 @@ func TestServer_New(t *testing.T) {
}

func TestServer_ServeHTTP(t *testing.T) {
t.Parallel()

svr := NewServer(log.NewTestingLogger(t))

s := httptest.NewServer(http.HandlerFunc(svr.ServeHTTP))
defer s.Close()

u := "ws" + strings.TrimPrefix(s.URL, "http")
c, _, err := websocket.DefaultDialer.Dial(u, nil)
if err != nil {
t.Fatalf("client Dial failed: %v", err)
}
require.NoError(t, err, "client Dial failed")

defer c.Close()

assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.Len(c, svr.conns(), 1)
}, time.Second, time.Millisecond*100)

sendEvt := events.Custom("TEST")
assert.Len(t, svr.clients, 1)
svr.Emit(sendEvt) // simulate reload

var recvEvt eventJSON
Expand Down

0 comments on commit 56b5bc0

Please sign in to comment.