github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/eventstream/eventstream_test.go (about) 1 package eventstream_test 2 3 import ( 4 "testing" 5 6 "github.com/asynkron/protoactor-go/eventstream" 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestEventStream_Subscribe(t *testing.T) { 11 es := &eventstream.EventStream{} 12 s := es.Subscribe(func(interface{}) {}) 13 assert.NotNil(t, s) 14 assert.Equal(t, es.Length(), int32(1)) 15 } 16 17 func TestEventStream_Unsubscribe(t *testing.T) { 18 es := &eventstream.EventStream{} 19 var c1, c2 int 20 21 s1 := es.Subscribe(func(interface{}) { c1++ }) 22 s2 := es.Subscribe(func(interface{}) { c2++ }) 23 assert.Equal(t, es.Length(), int32(2)) 24 25 es.Unsubscribe(s2) 26 assert.Equal(t, es.Length(), int32(1)) 27 28 es.Publish(1) 29 assert.Equal(t, 1, c1) 30 31 es.Unsubscribe(s1) 32 assert.Equal(t, es.Length(), int32(0)) 33 34 es.Publish(1) 35 assert.Equal(t, 1, c1) 36 assert.Equal(t, 0, c2) 37 } 38 39 func TestEventStream_Publish(t *testing.T) { 40 es := &eventstream.EventStream{} 41 42 var v int 43 es.Subscribe(func(m interface{}) { v = m.(int) }) 44 45 es.Publish(1) 46 assert.Equal(t, 1, v) 47 48 es.Publish(100) 49 assert.Equal(t, 100, v) 50 } 51 52 func TestEventStream_Subscribe_WithPredicate_IsCalled(t *testing.T) { 53 called := false 54 es := &eventstream.EventStream{} 55 es.SubscribeWithPredicate( 56 func(interface{}) { called = true }, 57 func(m interface{}) bool { return true }, 58 ) 59 es.Publish("") 60 61 assert.True(t, called) 62 } 63 64 func TestEventStream_Subscribe_WithPredicate_IsNotCalled(t *testing.T) { 65 called := false 66 es := &eventstream.EventStream{} 67 es.SubscribeWithPredicate( 68 func(interface{}) { called = true }, 69 func(m interface{}) bool { return false }, 70 ) 71 es.Publish("") 72 73 assert.False(t, called) 74 } 75 76 type Event struct { 77 i int 78 } 79 80 func BenchmarkEventStream(b *testing.B) { 81 es := eventstream.NewEventStream() 82 subs := make([]*eventstream.Subscription, 10) 83 for i := 0; i < b.N; i++ { 84 for j := 0; j < 10; j++ { 85 sub := es.Subscribe(func(evt interface{}) { 86 if e := evt.(*Event); e.i != i { 87 b.Fatalf("expected i to be %d but its value is %d", i, e.i) 88 } 89 }) 90 subs[j] = sub 91 } 92 93 es.Publish(&Event{i: i}) 94 for j := range subs { 95 es.Unsubscribe(subs[j]) 96 if subs[j].IsActive() { 97 b.Fatal("subscription should not be active") 98 } 99 } 100 } 101 }