-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_pool_test.go
More file actions
89 lines (73 loc) · 1.74 KB
/
worker_pool_test.go
File metadata and controls
89 lines (73 loc) · 1.74 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
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"context"
"net"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestWorkerPool(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var (
processed atomic.Int32
wg sync.WaitGroup
handlerWg sync.WaitGroup
)
maxWorkers := 2
queueSize := 5
wp := NewWorkerPool(ctx, maxWorkers, queueSize, &wg)
handler := func(conn net.Conn) {
defer handlerWg.Done()
processed.Add(1)
time.Sleep(10 * time.Millisecond) // Simulate work
}
// Submit jobs
for i := range 10 {
handlerWg.Add(1)
job := Job{Conn: nil, Handler: handler}
if !wp.Submit(job) {
t.Errorf("Failed to submit job %d", i)
handlerWg.Done()
}
}
handlerWg.Wait()
if processed.Load() != 10 {
t.Errorf("Expected 10 processed jobs, got %d", processed.Load())
}
cancel() // Shutdown WorkerPool
wg.Wait()
}
func TestWorkerPoolBackPressure(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
maxWorkers := 1
queueSize := 1
wp := NewWorkerPool(ctx, maxWorkers, queueSize, &wg)
handler := func(conn net.Conn) {
time.Sleep(50 * time.Millisecond) // Block the worker
}
// First job: occupies the worker
wp.Submit(Job{Conn: nil, Handler: handler})
// Second job: occupies the queue (size 1)
wp.Submit(Job{Conn: nil, Handler: handler})
// Third job: should block until one is done
start := time.Now()
done := make(chan bool)
go func() {
wp.Submit(Job{Conn: nil, Handler: handler})
done <- true
}()
select {
case <-done:
if time.Since(start) < 20*time.Millisecond {
t.Error("Submit should have blocked due to full queue")
}
case <-time.After(200 * time.Millisecond):
t.Error("Submit blocked too long or hung")
}
cancel()
wg.Wait()
}