event_dispatcher_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package raft
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. // Ensure that we can listen and dispatch events.
  7. func TestDispatchEvent(t *testing.T) {
  8. var count int
  9. dispatcher := newEventDispatcher(nil)
  10. dispatcher.AddEventListener("foo", func(e Event) {
  11. count += 1
  12. })
  13. dispatcher.AddEventListener("foo", func(e Event) {
  14. count += 10
  15. })
  16. dispatcher.AddEventListener("bar", func(e Event) {
  17. count += 100
  18. })
  19. dispatcher.DispatchEvent(&event{typ: "foo", value: nil, prevValue: nil})
  20. assert.Equal(t, 11, count)
  21. }
  22. // Ensure that we can add and remove a listener.
  23. func TestRemoveEventListener(t *testing.T) {
  24. var count int
  25. f0 := func(e Event) {
  26. count += 1
  27. }
  28. f1 := func(e Event) {
  29. count += 10
  30. }
  31. dispatcher := newEventDispatcher(nil)
  32. dispatcher.AddEventListener("foo", f0)
  33. dispatcher.AddEventListener("foo", f1)
  34. dispatcher.DispatchEvent(&event{typ: "foo"})
  35. dispatcher.RemoveEventListener("foo", f0)
  36. dispatcher.DispatchEvent(&event{typ: "foo"})
  37. assert.Equal(t, 21, count)
  38. }
  39. // Ensure that event is properly passed to listener.
  40. func TestEventListener(t *testing.T) {
  41. dispatcher := newEventDispatcher("X")
  42. dispatcher.AddEventListener("foo", func(e Event) {
  43. assert.Equal(t, "foo", e.Type())
  44. assert.Equal(t, "X", e.Source())
  45. assert.Equal(t, 10, e.Value())
  46. assert.Equal(t, 20, e.PrevValue())
  47. })
  48. dispatcher.DispatchEvent(&event{typ: "foo", value: 10, prevValue: 20})
  49. }
  50. // Benchmark the performance of event dispatch.
  51. func BenchmarkEventDispatch(b *testing.B) {
  52. dispatcher := newEventDispatcher(nil)
  53. dispatcher.AddEventListener("xxx", func(e Event) {})
  54. for i := 0; i < b.N; i++ {
  55. dispatcher.DispatchEvent(&event{typ: "foo", value: 10, prevValue: 20})
  56. }
  57. }