complete test for command pool

Signed-off-by: andrewmatilde <davis6813585853062@outlook.com>
This commit is contained in:
andrewmatilde 2023-02-08 14:23:38 +08:00
parent 0ab6238923
commit c0e3d3c529
2 changed files with 65 additions and 1 deletions

View File

@ -38,8 +38,9 @@ func NewCommandPools(ctx context.Context, deadline *time.Time, size int) *Comman
var cancel context.CancelFunc
if deadline != nil {
ctx2, cancel = context.WithDeadline(ctx, *deadline)
} else {
ctx2, cancel = context.WithCancel(ctx)
}
ctx2, cancel = context.WithCancel(ctx)
return &CommandPools{
cancel: cancel,
pools: tunny.NewFunc(size, func(payload interface{}) interface{} {

63
pkg/utils/pool_test.go Normal file
View File

@ -0,0 +1,63 @@
package utils
import (
"context"
"math"
"testing"
"time"
"github.com/pingcap/log"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
)
var GlobalErrors []error
func TestCommandPools_Cancel(t *testing.T) {
now := time.Now()
cmdPools := NewCommandPools(context.Background(), nil, 1)
cmdPools.Start("sleep", []string{"10s"}, func(output []byte, err error) {
if err != nil {
log.Error(string(output), zap.Error(err))
GlobalErrors = append(GlobalErrors, err)
}
log.Info(string(output))
})
cmdPools.Close()
assert.Less(t, time.Since(now).Seconds(), 10.0)
assert.Equal(t, 1, len(GlobalErrors))
GlobalErrors = []error{}
}
func TestCommandPools_Deadline(t *testing.T) {
now := time.Now()
deadline := time.Now().Add(time.Millisecond * 50)
cmdPools := NewCommandPools(context.Background(), &deadline, 1)
cmdPools.Start("sleep", []string{"10s"}, func(output []byte, err error) {
if err != nil {
log.Error(string(output), zap.Error(err))
GlobalErrors = append(GlobalErrors, err)
}
log.Info(string(output))
})
cmdPools.Wait()
assert.Less(t, math.Abs(float64(time.Since(now).Milliseconds()-50)), 10.0)
assert.Equal(t, 1, len(GlobalErrors))
GlobalErrors = []error{}
}
func TestCommandPools_Normal(t *testing.T) {
now := time.Now()
cmdPools := NewCommandPools(context.Background(), nil, 1)
cmdPools.Start("sleep", []string{"1s"}, func(output []byte, err error) {
if err != nil {
log.Error(string(output), zap.Error(err))
GlobalErrors = append(GlobalErrors, err)
}
log.Info(string(output))
})
cmdPools.Wait()
assert.Less(t, time.Since(now).Seconds(), 2.0)
assert.Equal(t, 0, len(GlobalErrors))
GlobalErrors = []error{}
}