util/eventbus: add an EqualTo helper for testing (#17178)

For a common case of events being simple struct types with some exported
fields, add a helper to check (reflectively) for equal values using cmp.Diff so
that a failed comparison gives a useful diff in the test output.

More complex uses will still want to provide their own comparisons; this
(intentionally) does not export diff options or other hooks from the cmp
package.

Updates #15160

Change-Id: I86bee1771cad7debd9e3491aa6713afe6fd577a6
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
This commit is contained in:
M. J. Fromberger
2025-09-17 08:39:29 -07:00
committed by GitHub
parent 8a4b1eb6a3
commit 6992f958fc
2 changed files with 40 additions and 9 deletions
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"tailscale.com/util/eventbus"
)
@@ -249,3 +250,16 @@ func Inject[T any](inj *Injector, event T) {
}
pub.(*eventbus.Publisher[T]).Publish(event)
}
// EqualTo returns an event-matching function for use with [Expect] and
// [ExpectExactly] that matches on an event of the given type that is equal to
// want by comparison with [cmp.Diff]. The expectation fails with an error
// message including the diff, if present.
func EqualTo[T any](want T) func(T) error {
return func(got T) error {
if diff := cmp.Diff(got, want); diff != "" {
return fmt.Errorf("wrong result (-got, +want):\n%s", diff)
}
return nil
}
}