github.com/whoyao/protocol@v0.0.0-20230519045905-2d8ace718ca5/utils/event_emitter_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"sort"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  func TestEventEmitter(t *testing.T) {
    11  	t.Run("emitter", func(t *testing.T) {
    12  		emitter := NewDefaultEventEmitter[string, int]()
    13  		ao0 := emitter.Observe("a")
    14  		ao1 := emitter.Observe("a")
    15  		bo := emitter.Observe("b")
    16  
    17  		emitter.Emit("a", 1)
    18  		emitter.Emit("b", 2)
    19  		require.Equal(t, 1, <-ao0.Events())
    20  		require.Equal(t, 1, <-ao1.Events())
    21  		require.Equal(t, 2, <-bo.Events())
    22  
    23  		ao1.Stop()
    24  		emitter.Emit("a", 3)
    25  		require.Equal(t, 3, <-ao0.Events())
    26  		select {
    27  		case <-ao1.Events():
    28  			require.Fail(t, "expected no event from stopped observer")
    29  		default:
    30  		}
    31  
    32  		keys := emitter.ObservedKeys()
    33  		sort.Strings(keys)
    34  		require.Equal(t, []string{"a", "b"}, keys)
    35  	})
    36  
    37  	t.Run("observer", func(t *testing.T) {
    38  		var closeCalled bool
    39  		o, emit := NewEventObserver[int](func() { closeCalled = true })
    40  
    41  		emit(1)
    42  		require.Equal(t, 1, <-o.Events())
    43  
    44  		o.Stop()
    45  		require.True(t, closeCalled)
    46  	})
    47  }