generated from atomicgo/template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool_test.go
115 lines (93 loc) · 2.04 KB
/
pool_test.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package pool
import (
"context"
"fmt"
"sync"
"testing"
"time"
)
func TestPoolRun(t *testing.T) {
configs := []Config{
{
MaxWorkers: 2,
},
{
MaxWorkers: 2,
Timeout: time.Millisecond * 10,
},
{}, // Empty config
}
for _, config := range configs {
t.Run(fmt.Sprintf("%+v", config), func(t *testing.T) {
testPool(t, config, 0, true, false)
})
}
}
func TestPoolTimeout(t *testing.T) {
configs := []Config{
{
MaxWorkers: 2,
Timeout: time.Millisecond * 10,
},
}
for _, config := range configs {
t.Run(fmt.Sprintf("%+v", config), func(t *testing.T) {
testPool(t, config, time.Millisecond*100, false, true)
})
}
}
func TestErrorHandling(t *testing.T) {
config := Config{
MaxWorkers: 2,
}
testPool(t, config, 0, true, true)
}
func testPool(t *testing.T, config Config, writeSpeed time.Duration, shouldPass bool, expectsError bool) {
t.Helper()
// Create map with 10 booleans
var m sync.Map
for i := 0; i < 10; i++ {
m.Store(i, false)
}
// Create a new pool
p := New[int](config)
// Set the task handler to process integers
p.SetHandler(func(ctx context.Context, i int) error {
// Simulate write speed
if writeSpeed > 0 {
time.Sleep(writeSpeed)
}
// Set the map value to true
m.Store(i, true)
if expectsError {
return fmt.Errorf("error")
}
return nil
})
var hasErrors bool
// Set error handler
p.SetErrorHandler(func(err error, p *Pool[int]) {
hasErrors = true
})
// Start the pool
p.Start()
// Add map keys to the pool
for i := 0; i < 10; i++ {
p.Add(i)
}
// Close the pool and wait for all tasks to complete
p.Close()
m.Range(func(key, value interface{}) bool {
if !value.(bool) && shouldPass {
t.Errorf("Expected map value to be true, got false")
} else if value.(bool) && !shouldPass {
t.Errorf("Expected map value to be false, got true")
}
return true
})
if expectsError && !hasErrors {
t.Errorf("Expected errors to be true, got false")
} else if !expectsError && hasErrors {
t.Errorf("Expected errors to be false, got true")
}
}