Fixed a race condition in dial_test related to hub closing in-test

This commit is contained in:
bwilliams committed 2026-10-15 17:57:26 +01:00
1 parent a279405cae
commit 2490519c2b
1 file changed
+23 -17
+23 -17
View File
@@ -161,32 +161,38 @@ func TestDialOrigin(t *testing.T) {
// With --listen, pushed messages are printed until the server closes the // With --listen, pushed messages are printed until the server closes the
// connection. // connection.
func TestDialListen(t *testing.T) { func TestDialListen(t *testing.T) {
cmdtest.Setup(t, "")
hub, url := wsServer(t) hub, url := wsServer(t)
out := &syncBuffer{}
done := make(chan error, 1)
go func() { go func() {
// Wait for the client to connect and get its pong. done <- dial(context.Background(), nil, out, dialSettings{
deadline := time.Now().Add(2 * time.Second) url: url,
for hub.Count() == 0 && time.Now().Before(deadline) { messages: []string{ping},
time.Sleep(5 * time.Millisecond) listen: true,
} timeout: time.Second,
time.Sleep(50 * time.Millisecond) })
}()
// Push only once the client has its pong, and shut down only once it has
// the push: Shutdown closes clients without waiting for their queues.
waitFor(t, out, `< {"type":"pong","id":"1"`)
hub.Push("event", map[string]any{"n": 1}) hub.Push("event", map[string]any{"n": 1})
waitFor(t, out, `< {"type":"event","payload":{"n":1}}`)
ctx, cancel := context.WithTimeout(context.Background(), time.Second) ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel() defer cancel()
hub.Shutdown(ctx) hub.Shutdown(ctx)
}()
out := cmdtest.MustRun( select {
t, newRoot, "ws", "dial", "--url", url, "--message", ping, "--listen", case err := <-done:
) if err != nil {
cmdtest.Contains( t.Fatalf("dial = %v; want nil when the server closes", err)
t, }
out, case <-time.After(time.Second):
`< {"type":"event","payload":{"n":1}}`, t.Fatal("dial did not return when the server closed")
"closed by the server (1001)", }
) waitFor(t, out, "closed by the server (1001)")
} }
// syncBuffer is a bytes.Buffer safe to write from one goroutine while // syncBuffer is a bytes.Buffer safe to write from one goroutine while