github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/behaviorlogic_test.go (about)

     1  package actor
     2  
     3  import (
     4  	"strconv"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestBehavior_Len(t *testing.T) {
    11  	var bs Behavior
    12  
    13  	assert.Len(t, bs, 0)
    14  	bs.push(func(Context) {})
    15  	bs.push(func(Context) {})
    16  	assert.Len(t, bs, 2)
    17  }
    18  
    19  func TestBehavior_Push(t *testing.T) {
    20  	var bs Behavior
    21  
    22  	assert.Len(t, bs, 0)
    23  	bs.push(func(Context) {})
    24  	assert.Len(t, bs, 1)
    25  	bs.push(func(Context) {})
    26  	assert.Len(t, bs, 2)
    27  }
    28  
    29  func TestBehavior_Clear(t *testing.T) {
    30  	var bs Behavior
    31  
    32  	bs.push(func(Context) {})
    33  	bs.push(func(Context) {})
    34  	assert.Len(t, bs, 2)
    35  	bs.clear()
    36  	assert.Len(t, bs, 0)
    37  }
    38  
    39  func TestBehavior_Peek(t *testing.T) {
    40  	called := 0
    41  	fn1 := ReceiveFunc(func(Context) { called = 1 })
    42  	fn2 := ReceiveFunc(func(Context) { called = 2 })
    43  
    44  	cases := []struct {
    45  		items    []ReceiveFunc
    46  		expected int
    47  	}{
    48  		{[]ReceiveFunc{fn1, fn2}, 2},
    49  		{[]ReceiveFunc{fn2, fn1}, 1},
    50  	}
    51  
    52  	for _, tc := range cases {
    53  		t.Run("", func(t *testing.T) {
    54  			var bs Behavior
    55  			for _, fn := range tc.items {
    56  				bs.push(fn)
    57  			}
    58  			a, _ := bs.peek()
    59  			a(nil)
    60  			assert.Equal(t, tc.expected, called)
    61  		})
    62  	}
    63  }
    64  
    65  func TestBehaviorStack_Pop_ExpectedOrder(t *testing.T) {
    66  	called := 0
    67  	fn1 := ReceiveFunc(func(Context) { called = 1 })
    68  	fn2 := ReceiveFunc(func(Context) { called = 2 })
    69  
    70  	cases := []struct {
    71  		items    []ReceiveFunc
    72  		expected []int
    73  	}{
    74  		{[]ReceiveFunc{fn1, fn2}, []int{2, 1}},
    75  		{[]ReceiveFunc{fn2, fn1}, []int{1, 2}},
    76  	}
    77  
    78  	for i, tc := range cases {
    79  		t.Run("order "+strconv.Itoa(i), func(t *testing.T) {
    80  			var bs Behavior
    81  			for _, fn := range tc.items {
    82  				bs.push(fn)
    83  			}
    84  
    85  			for _, e := range tc.expected {
    86  				a, _ := bs.pop()
    87  				a(nil)
    88  				assert.Equal(t, e, called)
    89  				called = 0
    90  			}
    91  		})
    92  	}
    93  }