github.com/lingyao2333/mo-zero@v1.4.1/core/logx/limitedexecutor_test.go (about)

     1  package logx
     2  
     3  import (
     4  	"sync/atomic"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/lingyao2333/mo-zero/core/timex"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestLimitedExecutor_logOrDiscard(t *testing.T) {
    13  	tests := []struct {
    14  		name      string
    15  		threshold time.Duration
    16  		lastTime  time.Duration
    17  		discarded uint32
    18  		executed  bool
    19  	}{
    20  		{
    21  			name:     "nil executor",
    22  			executed: true,
    23  		},
    24  		{
    25  			name:      "regular",
    26  			threshold: time.Hour,
    27  			lastTime:  timex.Now(),
    28  			discarded: 10,
    29  			executed:  false,
    30  		},
    31  		{
    32  			name:      "slow",
    33  			threshold: time.Duration(1),
    34  			lastTime:  -1000,
    35  			discarded: 10,
    36  			executed:  true,
    37  		},
    38  	}
    39  
    40  	for _, test := range tests {
    41  		test := test
    42  		t.Run(test.name, func(t *testing.T) {
    43  			t.Parallel()
    44  
    45  			executor := newLimitedExecutor(0)
    46  			executor.threshold = test.threshold
    47  			executor.discarded = test.discarded
    48  			executor.lastTime.Set(test.lastTime)
    49  
    50  			var run int32
    51  			executor.logOrDiscard(func() {
    52  				atomic.AddInt32(&run, 1)
    53  			})
    54  			if test.executed {
    55  				assert.Equal(t, int32(1), atomic.LoadInt32(&run))
    56  			} else {
    57  				assert.Equal(t, int32(0), atomic.LoadInt32(&run))
    58  				assert.Equal(t, test.discarded+1, atomic.LoadUint32(&executor.discarded))
    59  			}
    60  		})
    61  	}
    62  }