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

     1  package actor
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestOneForOneStrategy_requestRestartPermission(t *testing.T) {
    11  	cases := []struct {
    12  		n              string
    13  		expectedResult bool
    14  		expectedCount  int
    15  		s              oneForOneStrategy
    16  		rs             RestartStatistics
    17  	}{
    18  		{
    19  			n: "no restart if max retries is 0",
    20  
    21  			s:  oneForOneStrategy{maxNrOfRetries: 0},
    22  			rs: RestartStatistics{},
    23  
    24  			expectedResult: true,
    25  			expectedCount:  0,
    26  		},
    27  		{
    28  			n: "restart when duration is 0",
    29  
    30  			s:  oneForOneStrategy{maxNrOfRetries: 1},
    31  			rs: RestartStatistics{},
    32  
    33  			expectedResult: false,
    34  			expectedCount:  1,
    35  		},
    36  		{
    37  			n: "no restart when duration is 0 and exceeds max retries",
    38  
    39  			s:  oneForOneStrategy{maxNrOfRetries: 1},
    40  			rs: RestartStatistics{failureTimes: []time.Time{time.Now().Add(-1 * time.Second)}},
    41  
    42  			expectedResult: true,
    43  			expectedCount:  0,
    44  		},
    45  		{
    46  			n: "restart when duration set and within window",
    47  
    48  			s:  oneForOneStrategy{maxNrOfRetries: 2, withinDuration: 10 * time.Second},
    49  			rs: RestartStatistics{failureTimes: []time.Time{time.Now().Add(-5 * time.Second)}},
    50  
    51  			expectedResult: false,
    52  			expectedCount:  2,
    53  		},
    54  		{
    55  			n: "no restart when duration set, within window and exceeds max retries",
    56  
    57  			s:  oneForOneStrategy{maxNrOfRetries: 1, withinDuration: 10 * time.Second},
    58  			rs: RestartStatistics{failureTimes: []time.Time{time.Now().Add(-5 * time.Second), time.Now().Add(-5 * time.Second)}},
    59  
    60  			expectedResult: true,
    61  			expectedCount:  0,
    62  		},
    63  		{
    64  			n: "restart and FailureCount reset when duration set and outside window",
    65  
    66  			s:  oneForOneStrategy{maxNrOfRetries: 1, withinDuration: 10 * time.Second},
    67  			rs: RestartStatistics{failureTimes: []time.Time{time.Now().Add(-11 * time.Second), time.Now().Add(-11 * time.Second)}},
    68  
    69  			expectedResult: false,
    70  			expectedCount:  1,
    71  		},
    72  	}
    73  
    74  	for _, tc := range cases {
    75  		t.Run(tc.n, func(t *testing.T) {
    76  			s := tc.s
    77  			rs := tc.rs
    78  			actual := s.shouldStop(&rs)
    79  			assert.Equal(t, tc.expectedResult, actual)
    80  			assert.Equal(t, tc.expectedCount, rs.NumberOfFailures(s.withinDuration))
    81  		})
    82  	}
    83  }