github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/eventbus/event_bus_test.go (about) 1 /* 2 * Copyright (C) 2019 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package eventbus 19 20 import ( 21 "sync" 22 "sync/atomic" 23 "testing" 24 "time" 25 26 "github.com/stretchr/testify/assert" 27 ) 28 29 func Test_simplifiedEventBus_Publish_InvokesSubscribers(t *testing.T) { 30 eventBus := New() 31 var received string 32 eventBus.Subscribe("test topic", func(data string) { 33 received = data 34 }) 35 36 eventBus.Publish("test topic", "test data") 37 38 assert.Equal(t, "test data", received) 39 } 40 41 type handler struct { 42 val int 43 } 44 45 func (h *handler) Handle(_ string) { 46 h.val++ 47 } 48 49 func TestUnsubscribeMethod(t *testing.T) { 50 bus := New() 51 h := &handler{val: 0} 52 h2 := &handler{val: 5} 53 54 bus.SubscribeWithUID("topic", "1", h.Handle) 55 bus.SubscribeWithUID("topic", "2", h2.Handle) 56 57 bus.Publish("topic", "1") 58 59 err := bus.UnsubscribeWithUID("topic", "1", h.Handle) 60 assert.NoError(t, err) 61 62 bus.Publish("topic", "2") 63 64 err = bus.UnsubscribeWithUID("topic", "2", h2.Handle) 65 assert.NoError(t, err) 66 67 err = bus.UnsubscribeWithUID("topic", "1", h.Handle) 68 assert.Error(t, err) 69 70 bus.Publish("topic", "3") 71 72 assert.Equal(t, 1, h.val) 73 assert.Equal(t, 7, h2.val) 74 } 75 76 func Test_simplifiedEventBus_Publish_DataRace(t *testing.T) { 77 eventBus := New() 78 79 fn := func(data string) {} 80 81 active := new(atomic.Bool) 82 active.Store(true) 83 84 var wg sync.WaitGroup 85 wg.Add(2) 86 87 go func() { 88 defer wg.Done() 89 90 for i := 0; i < 100; i++ { 91 eventBus.SubscribeWithUID("topic", "1", fn) 92 eventBus.Publish("topic", "test data") 93 time.Sleep(time.Millisecond) 94 } 95 active.Store(false) 96 }() 97 go func() { 98 defer wg.Done() 99 for active.Load() == true { 100 eventBus.UnsubscribeWithUID("topic", "1", fn) 101 time.Sleep(time.Millisecond) 102 } 103 }() 104 wg.Wait() 105 }