-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_test.go
More file actions
77 lines (74 loc) · 1.59 KB
/
worker_test.go
File metadata and controls
77 lines (74 loc) · 1.59 KB
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
package gopool
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNewWorker(t *testing.T) {
cases := map[string]struct {
args any
callback CallbackFunc
taskFunc TaskFunc
expectval any
timeout time.Duration
}{
"success": {
args: 1,
taskFunc: func(args any) (any, error) {
a := args.(int) + args.(int)
return a, nil
},
callback: func(result any) (any, error) {
return result, nil
},
expectval: 2,
timeout: 5 * time.Second,
},
"timeout": {
args: 2,
taskFunc: func(args any) (any, error) {
time.Sleep(10 * time.Second)
return nil, TimecoutError
},
callback: func(result any) (any, error) {
return nil, nil
},
timeout: 5 * time.Second,
},
"no_timeout": {
args: 3,
taskFunc: func(args any) (any, error) {
time.Sleep(12 * time.Second)
return nil, TimecoutError
},
callback: func(result any) (any, error) {
return nil, nil
},
},
}
var workId int = 1
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
task := NewTask(tc.taskFunc, tc.callback, tc.args)
worker := NewWorker(workId, task)
workId++
err := worker.Run(true, tc.timeout)
if err != nil {
if errors.Is(err, TimecoutError) {
t.Log(TimecoutError.Error())
} else if errors.Is(err, context.DeadlineExceeded) {
t.Log(context.DeadlineExceeded.Error())
} else if os.IsTimeout(err) {
t.Log("IsTimeoutError:" + err.Error())
} else {
assert.NoError(t, err)
}
} else {
assert.Equal(t, tc.expectval, task.GetResult())
}
})
}
}