gomu/hook/hook_test.go

58 lines
909 B
Go
Raw Normal View History

2021-02-19 10:25:34 +08:00
package hook
import (
"testing"
"github.com/stretchr/testify/assert"
)
2021-02-19 12:08:08 +08:00
func TestAddHook(t *testing.T) {
2021-03-04 12:33:09 +08:00
2021-02-19 12:08:08 +08:00
h := NewEventHook()
h.AddHook("a", nil)
h.AddHook("a", nil)
h.AddHook("a", nil)
h.AddHook("a", nil)
assert.Equal(t, 1, len(h.events), "should only contain 1 event")
hooks := h.events["a"]
assert.Equal(t, 4, len(hooks), "should contain 4 hooks")
h.AddHook("b", nil)
h.AddHook("c", nil)
assert.Equal(t, 3, len(h.events), "should contain 3 events")
}
func TestRunHooks(t *testing.T) {
2021-02-19 10:25:34 +08:00
h := NewEventHook()
2021-02-19 22:22:36 +08:00
x := 0
2021-02-19 10:25:34 +08:00
2021-03-04 12:33:09 +08:00
for i := 0; i < 100; i++ {
2021-02-19 22:22:36 +08:00
h.AddHook("sample", func() {
x++
})
}
2021-02-19 10:25:34 +08:00
2021-02-19 22:22:36 +08:00
h.AddHook("noop", func() {
x++
2021-02-19 10:25:34 +08:00
})
2021-02-19 12:08:08 +08:00
h.AddHook("noop", func() {
2021-02-19 22:22:36 +08:00
x++
2021-02-19 12:08:08 +08:00
})
2021-02-19 22:22:36 +08:00
assert.Equal(t, x, 0, "should not execute any hook")
2021-02-19 10:25:34 +08:00
h.RunHooks("x")
2021-02-19 22:22:36 +08:00
assert.Equal(t, x, 0, "should not execute any hook")
2021-02-19 10:25:34 +08:00
h.RunHooks("sample")
2021-02-19 22:22:36 +08:00
assert.Equal(t, x, 100, "should only execute event 'sample'")
2021-02-19 10:25:34 +08:00
}