github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/eventbus/bus_test.go (about) 1 package eventbus 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/mit-dci/lit/logging" 8 ) 9 10 func TestBusSimple(t *testing.T) { 11 bus := NewEventBus() 12 m := "Hello, World!" 13 x := "" 14 15 // Register the handler. 16 bus.RegisterHandler("foo", func(e Event) EventHandleResult { 17 println("normal event handler invoked") 18 e2 := e.(FooEvent) 19 x = e2.msg 20 return EHANDLE_OK 21 }) 22 if bus.CountHandlers("foo") != 1 { 23 t.Fail() 24 } 25 26 // Publish an event to the handler. 27 bus.Publish(FooEvent{ 28 msg: m, 29 async: false, 30 }) 31 if x != m { 32 t.Fail() 33 } 34 } 35 36 func TestBusAsync(t *testing.T) { 37 38 bus := NewEventBus() 39 c := make(chan uint8, 2) 40 41 // Register the handler. 42 bus.RegisterHandler("foo", func(e Event) EventHandleResult { 43 println("async event handler invoked") 44 c <- 42 45 return EHANDLE_OK 46 }) 47 48 // Escape if we don't work out. 49 go (func() { 50 time.Sleep(1000 * time.Millisecond) 51 t.FailNow() 52 })() 53 54 // Publish an event to the handler. 55 bus.Publish(FooEvent{ 56 msg: "asdf", 57 async: true, 58 }) 59 60 r := <-c 61 logging.Infof("got result: %d\n", r) 62 63 } 64 65 func TestBusNoHandlers(t *testing.T) { 66 67 bus := NewEventBus() 68 69 bus.Publish(FooEvent{ 70 msg: "lol", 71 async: false, 72 }) 73 74 println("event fired with no handlers ok") 75 76 return 77 78 } 79 80 type FooEvent struct { 81 msg string 82 async bool 83 } 84 85 func (FooEvent) Name() string { 86 return "foo" 87 } 88 89 func (e FooEvent) Flags() uint8 { 90 if e.async { 91 return EFLAG_ASYNC 92 } else { 93 return EFLAG_NORMAL 94 } 95 }