Spaces:
Runtime error
Runtime error
File size: 1,976 Bytes
215df2f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
package task
import (
"sync/atomic"
"testing"
"time"
"github.com/alist-org/alist/v3/pkg/utils"
"github.com/pkg/errors"
)
func TestTask_Manager(t *testing.T) {
tm := NewTaskManager(3, func(id *uint64) {
atomic.AddUint64(id, 1)
})
id := tm.Submit(WithCancelCtx(&Task[uint64]{
Name: "test",
Func: func(task *Task[uint64]) error {
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.state != RUNNING {
t.Errorf("task status not running: %s", task.state)
}
time.Sleep(time.Second)
if task.state != SUCCEEDED {
t.Errorf("task status not finished: %s", task.state)
}
}
func TestTask_Cancel(t *testing.T) {
tm := NewTaskManager(3, func(id *uint64) {
atomic.AddUint64(id, 1)
})
id := tm.Submit(WithCancelCtx(&Task[uint64]{
Name: "test",
Func: func(task *Task[uint64]) error {
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.state != CANCELED {
t.Errorf("task status not canceled: %s", task.state)
}
}
func TestTask_Retry(t *testing.T) {
tm := NewTaskManager(3, func(id *uint64) {
atomic.AddUint64(id, 1)
})
num := 0
id := tm.Submit(WithCancelCtx(&Task[uint64]{
Name: "test",
Func: func(task *Task[uint64]) error {
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.state)
t.Fatal("task error is nil, but expected error")
} else {
t.Logf("task error: %s", task.Error)
}
task.retry()
time.Sleep(time.Millisecond)
if task.Error != nil {
t.Errorf("task error: %+v, but expected nil", task.Error)
}
}
|