github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/event_emitter_test.go (about) 1 // Copyright 2023 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package utils 16 17 import ( 18 "sort" 19 "testing" 20 21 "github.com/stretchr/testify/require" 22 ) 23 24 func TestEventEmitter(t *testing.T) { 25 t.Run("emitter", func(t *testing.T) { 26 emitter := NewDefaultEventEmitter[string, int]() 27 ao0 := emitter.Observe("a") 28 ao1 := emitter.Observe("a") 29 bo := emitter.Observe("b") 30 31 emitter.Emit("a", 1) 32 emitter.Emit("b", 2) 33 require.Equal(t, 1, <-ao0.Events()) 34 require.Equal(t, 1, <-ao1.Events()) 35 require.Equal(t, 2, <-bo.Events()) 36 37 ao1.Stop() 38 emitter.Emit("a", 3) 39 require.Equal(t, 3, <-ao0.Events()) 40 select { 41 case <-ao1.Events(): 42 require.Fail(t, "expected no event from stopped observer") 43 default: 44 } 45 46 ao0.Stop() 47 48 keys := emitter.ObservedKeys() 49 sort.Strings(keys) 50 require.Equal(t, []string{"b"}, keys) 51 }) 52 53 t.Run("observer", func(t *testing.T) { 54 var closeCalled bool 55 o, emit := NewEventObserver[int](func() { closeCalled = true }) 56 57 emit(1) 58 require.Equal(t, 1, <-o.Events()) 59 60 o.Stop() 61 require.True(t, closeCalled) 62 }) 63 }