github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/behavior_test.go (about) 1 package actor 2 3 import ( 4 "testing" 5 ) 6 7 type BehaviorMessage struct{} 8 9 type EchoSetBehaviorActor struct { 10 behavior Behavior 11 } 12 13 func NewEchoBehaviorActor() Actor { 14 state := &EchoSetBehaviorActor{ 15 behavior: NewBehavior(), 16 } 17 state.behavior.Become(state.one) 18 19 return state 20 } 21 22 func (state *EchoSetBehaviorActor) Receive(context Context) { 23 state.behavior.Receive(context) 24 } 25 26 func (state *EchoSetBehaviorActor) one(context Context) { 27 if _, ok := context.Message().(BehaviorMessage); ok { 28 state.behavior.Become(state.other) 29 } 30 } 31 32 func (EchoSetBehaviorActor) other(context Context) { 33 if _, ok := context.Message().(EchoRequest); ok { 34 context.Respond(EchoResponse{}) 35 } 36 } 37 38 func TestActorCanSetBehavior(t *testing.T) { 39 pid := rootContext.Spawn(PropsFromProducer(NewEchoBehaviorActor)) 40 defer rootContext.Stop(pid) 41 rootContext.Send(pid, BehaviorMessage{}) 42 fut := rootContext.RequestFuture(pid, EchoRequest{}, testTimeout) 43 assertFutureSuccess(fut, t) 44 } 45 46 type PopBehaviorMessage struct{} 47 48 func NewEchoUnbecomeActor() Actor { 49 state := &EchoSetBehaviorActor{ 50 behavior: NewBehavior(), 51 } 52 state.behavior.Become(state.one) 53 54 return state 55 } 56 57 func TestActorCanPopBehavior(t *testing.T) { 58 a := rootContext.Spawn(PropsFromProducer(NewEchoUnbecomeActor)) 59 rootContext.Send(a, BehaviorMessage{}) 60 rootContext.Send(a, PopBehaviorMessage{}) 61 fut := rootContext.RequestFuture(a, EchoRequest{}, testTimeout) 62 assertFutureSuccess(fut, t) 63 }