From 56b5bc0cc5c7400ed3700f9e469a422f2b849f61 Mon Sep 17 00:00:00 2001 From: Guilhem Fanton <8671905+gfanton@users.noreply.github.com> Date: Fri, 3 May 2024 09:44:16 +0200 Subject: [PATCH] fix(gnodev): racy emitter test (#2022) --- contribs/gnodev/pkg/emitter/server.go | 13 ++++++++++++- contribs/gnodev/pkg/emitter/server_test.go | 13 +++++++------ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/contribs/gnodev/pkg/emitter/server.go b/contribs/gnodev/pkg/emitter/server.go index 68faf27122b..e6052890095 100644 --- a/contribs/gnodev/pkg/emitter/server.go +++ b/contribs/gnodev/pkg/emitter/server.go @@ -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 { @@ -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 +} diff --git a/contribs/gnodev/pkg/emitter/server_test.go b/contribs/gnodev/pkg/emitter/server_test.go index 6e1ba71b097..4725378dbda 100644 --- a/contribs/gnodev/pkg/emitter/server_test.go +++ b/contribs/gnodev/pkg/emitter/server_test.go @@ -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" @@ -21,8 +22,6 @@ 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)) @@ -30,13 +29,15 @@ func TestServer_ServeHTTP(t *testing.T) { 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