cycle-scheduler/scheduler_test.go
2024-11-16 11:00:46 +01:00

94 lines
1.8 KiB
Go

package scheduler
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestScheduler(t *testing.T) {
ctx := context.Background()
var buf int
s := NewSchedulerCycle(ctx, 1)
taskID := s.Delay(func(ctx context.Context) (any, error) {
time.Sleep(50 * time.Millisecond)
buf += 1
return nil, nil
}, WithExecInterval(2*time.Millisecond))
assert.NotEmpty(t, taskID)
assert.False(t, s.TasksDone())
time.Sleep(2 * time.Millisecond)
details := s.GetTaskDetails(taskID)
assert.Equal(t, "running", details.State)
assert.LessOrEqual(t, details.ElapsedTime, 50*time.Millisecond)
time.Sleep(50 * time.Millisecond)
assert.True(t, s.TasksDone())
}
func TestSchedulerLoad(t *testing.T) {
ctx := context.Background()
s := NewSchedulerCycle(ctx, 1)
for i := 0; i < 500; i++ {
s.Delay(func(ctx context.Context) (any, error) {
time.Sleep(1 * time.Millisecond)
return nil, nil
}, WithExecInterval(1*time.Millisecond))
}
assert.Eventually(t, func() bool {
return s.TasksDone()
}, time.Second, 250*time.Millisecond)
}
func TestSchedulerExecInterval(t *testing.T) {
ctx := context.Background()
s := NewSchedulerCycle(ctx, 1)
s.Delay(
func(ctx context.Context) (any, error) {
return nil, ErrJobNotCompletedYet
},
WithMaxDuration(50*time.Millisecond),
WithExecInterval(2*time.Millisecond),
)
time.Sleep(100 * time.Millisecond)
assert.True(t, s.TasksDone())
}
func TestSchedulerContextDone(t *testing.T) {
ctx, fnCancel := context.WithCancel(context.Background())
s := NewSchedulerCycle(ctx, 1)
for i := 0; i < 250; i++ {
s.Delay(
func(ctx context.Context) (any, error) {
return nil, ErrJobNotCompletedYet
},
WithMaxDuration(100*time.Millisecond),
WithExecInterval(2*time.Millisecond),
)
}
go func() {
time.Sleep(50 * time.Millisecond)
fnCancel()
}()
<-s.Done()
}