util/eventbus: add a LogAllEvents helper for testing (#17187)

When developing (and debugging) tests, it is useful to be able to see all the
traffic that transits the event bus during the execution of a test.

Updates #15160

Change-Id: I929aee62ccf13bdd4bd07d786924ce9a74acd17a
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
This commit is contained in:
M. J. Fromberger 2025-09-18 12:44:06 -07:00 committed by GitHub
parent 70dfdac609
commit 4f211ea5c5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 0 deletions

View File

@ -263,3 +263,25 @@ func EqualTo[T any](want T) func(T) error {
return nil
}
}
// LogAllEvents logs summaries of all the events routed via the specified bus
// during the execution of the test governed by t. This is intended to support
// development and debugging of tests.
func LogAllEvents(t testing.TB, bus *eventbus.Bus) {
dw := bus.Debugger().WatchBus()
done := make(chan struct{})
go func() {
defer close(done)
var i int
for {
select {
case <-dw.Done():
return
case re := <-dw.Events():
i++
t.Logf("[eventbus] #%[1]d: %[2]T | %+[2]v", i, re.Event)
}
}
}()
t.Cleanup(func() { dw.Close(); <-done })
}

View File

@ -4,6 +4,7 @@
package eventbustest_test
import (
"flag"
"fmt"
"strings"
"testing"
@ -13,6 +14,8 @@ import (
"tailscale.com/util/eventbus/eventbustest"
)
var doDebug = flag.Bool("debug", false, "Enable debug logging")
type EventFoo struct {
Value int
}
@ -109,7 +112,11 @@ func TestExpectFilter(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if *doDebug {
eventbustest.LogAllEvents(t, bus)
}
tw := eventbustest.NewWatcher(t, bus)
// TODO(cmol): When synctest is out of experimental, use that instead:
// https://go.dev/blog/synctest
tw.TimeOut = 10 * time.Millisecond