events/bus_test.go

106 lines
2.1 KiB
Go
Raw Normal View History

2020-08-22 22:15:12 +00:00
package events
import (
"context"
2024-03-09 22:33:36 +00:00
"errors"
"fmt"
2020-08-22 22:15:12 +00:00
"testing"
2024-03-09 22:33:36 +00:00
"github.com/stretchr/testify/assert"
2020-08-22 22:15:12 +00:00
)
func TestNew_Lifecycle(t *testing.T) {
receives := make([][]int, 0)
d := New()
d.On("event", func(x int, y int) { receives = append(receives, []int{1, x, y}) })
d.On("event", func(x int) { receives = append(receives, []int{2, x}) })
d.On("event", func(x int, y string, z string) { receives = append(receives, []int{3, x, len(y)}) })
d.Fire("event", 123, 123)
d.Fire("event", 234, 234)
d.Fire("event", "string", "value")
2024-03-09 22:33:36 +00:00
assert.Equal(t, [][]int{
2020-08-22 22:15:12 +00:00
{1, 123, 123},
{2, 123},
{3, 123, 0},
{1, 234, 234},
{2, 234},
{3, 234, 0},
{1, 0, 0},
{2, 0},
{3, 0, 5},
}, receives)
}
func TestFire(t *testing.T) {
t.Run("should preserve context.Context", func(t *testing.T) {
var wasFired bool
d := New()
d.On("event", func(ctx context.Context) {
assert.NotNil(t, ctx)
wasFired = true
})
d.Fire("event", context.Background())
assert.True(t, wasFired)
})
}
2024-03-09 22:33:36 +00:00
func TestTryFire(t *testing.T) {
errVal := errors.New("bang")
tests := []struct {
errsRet [3]error
wantErr bool
}{
{
errsRet: [3]error{nil, nil, nil},
wantErr: false,
},
{
errsRet: [3]error{errVal, nil, nil},
wantErr: true,
},
{
errsRet: [3]error{nil, errVal, nil},
wantErr: true,
},
{
errsRet: [3]error{nil, nil, errVal},
wantErr: true,
},
{
errsRet: [3]error{errVal, nil, errVal},
wantErr: true,
},
2020-08-22 22:15:12 +00:00
}
2024-03-09 22:33:36 +00:00
for i, tt := range tests {
t.Run(fmt.Sprint(i), func(t *testing.T) {
d := New()
var handlersFired [4]bool
d.On("event", func() error { handlersFired[0] = true; return tt.errsRet[0] })
d.On("event", func(x int) error { handlersFired[1] = true; return tt.errsRet[1] })
d.On("event", func(x int, y string) error { handlersFired[2] = true; return tt.errsRet[2] })
d.On("event", func(x string, y string) { handlersFired[3] = true })
err := d.TryFire("event")
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, [4]bool{true, true, true, true}, handlersFired)
})
}
}