bus_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package bus
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "testing"
  7. )
  8. type testQuery struct {
  9. ID int64
  10. Resp string
  11. }
  12. func TestDispatchCtxCanUseNormalHandlers(t *testing.T) {
  13. bus := New()
  14. handlerWithCtxCallCount := 0
  15. handlerCallCount := 0
  16. handlerWithCtx := func(ctx context.Context, query *testQuery) error {
  17. handlerWithCtxCallCount++
  18. return nil
  19. }
  20. handler := func(query *testQuery) error {
  21. handlerCallCount++
  22. return nil
  23. }
  24. err := bus.DispatchCtx(context.Background(), &testQuery{})
  25. if err != ErrHandlerNotFound {
  26. t.Errorf("expected bus to return HandlerNotFound is no handler is registered")
  27. }
  28. bus.AddHandler(handler)
  29. t.Run("when a normal handler is registered", func(t *testing.T) {
  30. bus.Dispatch(&testQuery{})
  31. if handlerCallCount != 1 {
  32. t.Errorf("Expected normal handler to be called 1 time. was called %d", handlerCallCount)
  33. }
  34. t.Run("when a ctx handler is registered", func(t *testing.T) {
  35. bus.AddHandlerCtx(handlerWithCtx)
  36. bus.Dispatch(&testQuery{})
  37. if handlerWithCtxCallCount != 1 {
  38. t.Errorf("Expected ctx handler to be called 1 time. was called %d", handlerWithCtxCallCount)
  39. }
  40. })
  41. })
  42. }
  43. func TestQueryHandlerReturnsError(t *testing.T) {
  44. bus := New()
  45. bus.AddHandler(func(query *testQuery) error {
  46. return errors.New("handler error")
  47. })
  48. err := bus.Dispatch(&testQuery{})
  49. if err == nil {
  50. t.Fatal("Send query failed")
  51. } else {
  52. t.Log("Handler error received ok " + err.Error())
  53. }
  54. }
  55. func TestQueryHandlerReturn(t *testing.T) {
  56. bus := New()
  57. bus.AddHandler(func(q *testQuery) error {
  58. q.Resp = "hello from handler"
  59. return nil
  60. })
  61. query := &testQuery{}
  62. err := bus.Dispatch(query)
  63. if err != nil {
  64. t.Fatal("Send query failed " + err.Error())
  65. } else if query.Resp != "hello from handler" {
  66. t.Fatal("Failed to get response from handler")
  67. }
  68. }
  69. func TestEventListeners(t *testing.T) {
  70. bus := New()
  71. count := 0
  72. bus.AddEventListener(func(query *testQuery) error {
  73. count++
  74. return nil
  75. })
  76. bus.AddEventListener(func(query *testQuery) error {
  77. count += 10
  78. return nil
  79. })
  80. err := bus.Publish(&testQuery{})
  81. if err != nil {
  82. t.Fatal("Publish event failed " + err.Error())
  83. } else if count != 11 {
  84. t.Fatal(fmt.Sprintf("Publish event failed, listeners called: %v, expected: %v", count, 11))
  85. }
  86. }