2022-06-17 14:09:20 +00:00
|
|
|
package task
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/alist-org/alist/v3/pkg/utils"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestTask_Manager(t *testing.T) {
|
|
|
|
tm := NewTaskManager()
|
2022-06-18 12:38:14 +00:00
|
|
|
id := tm.Submit("test", func(task *Task) error {
|
2022-06-17 14:09:20 +00:00
|
|
|
time.Sleep(time.Millisecond * 500)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
task, ok := tm.Get(id)
|
|
|
|
if !ok {
|
|
|
|
t.Fatal("task not found")
|
|
|
|
}
|
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
if task.Status != RUNNING {
|
|
|
|
t.Errorf("task status not running: %s", task.Status)
|
|
|
|
}
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
if task.Status != FINISHED {
|
|
|
|
t.Errorf("task status not finished: %s", task.Status)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestTask_Cancel(t *testing.T) {
|
|
|
|
tm := NewTaskManager()
|
2022-06-18 12:38:14 +00:00
|
|
|
id := tm.Submit("test", func(task *Task) error {
|
2022-06-17 14:09:20 +00:00
|
|
|
for {
|
|
|
|
if utils.IsCanceled(task.Ctx) {
|
|
|
|
return nil
|
|
|
|
} else {
|
|
|
|
t.Logf("task is running")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
task, ok := tm.Get(id)
|
|
|
|
if !ok {
|
|
|
|
t.Fatal("task not found")
|
|
|
|
}
|
|
|
|
time.Sleep(time.Microsecond * 50)
|
|
|
|
task.Cancel()
|
|
|
|
time.Sleep(time.Millisecond)
|
|
|
|
if task.Status != CANCELED {
|
|
|
|
t.Errorf("task status not canceled: %s", task.Status)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestTask_Retry(t *testing.T) {
|
|
|
|
tm := NewTaskManager()
|
|
|
|
num := 0
|
2022-06-18 12:38:14 +00:00
|
|
|
id := tm.Submit("test", func(task *Task) error {
|
2022-06-17 14:09:20 +00:00
|
|
|
num++
|
|
|
|
if num&1 == 1 {
|
|
|
|
return errors.New("test error")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
task, ok := tm.Get(id)
|
|
|
|
if !ok {
|
|
|
|
t.Fatal("task not found")
|
|
|
|
}
|
|
|
|
time.Sleep(time.Millisecond)
|
|
|
|
if task.Error == nil {
|
|
|
|
t.Error(task.Status)
|
|
|
|
t.Fatal("task error is nil, but expected error")
|
|
|
|
} else {
|
|
|
|
t.Logf("task error: %s", task.Error)
|
|
|
|
}
|
2022-06-18 12:38:14 +00:00
|
|
|
task.retry()
|
2022-06-17 14:09:20 +00:00
|
|
|
time.Sleep(time.Millisecond)
|
|
|
|
if task.Error != nil {
|
|
|
|
t.Errorf("task error: %+v, but expected nil", task.Error)
|
|
|
|
}
|
|
|
|
}
|