-
Notifications
You must be signed in to change notification settings - Fork 0
/
ordered_test.go
73 lines (62 loc) · 1.56 KB
/
ordered_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
// Copyright (c) technicianted. All rights reserved.
// Licensed under the MIT License.
package scattergather
import (
"context"
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestSGSimple(t *testing.T) {
sg := NewOrderedScatterGather[int](4, 0, 0)
defer sg.Drain()
sg.AddWork(context.Background(), func() int {
time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
return 1
})
sg.AddWork(context.Background(), func() int {
time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
return 2
})
sg.AddWork(context.Background(), func() int {
time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
return 3
})
for i := 1; i <= 3; i++ {
r := <-sg.OutputChannel()
assert.Equal(t, i, r)
}
}
func TestSGDrainWithOngoingWork(t *testing.T) {
sg := NewOrderedScatterGather[int](4, 0, 0)
sg.AddWork(context.Background(), func() int {
time.Sleep(200 * time.Millisecond)
return 1
})
doneChan := make(chan struct{})
st := time.Now()
go func() {
sg.Drain()
assert.InDelta(t, 200*time.Millisecond, time.Since(st), float64(10*time.Millisecond))
close(doneChan)
}()
<-sg.OutputChannel()
<-doneChan
}
func TestSGDrainWithUnreadWork(t *testing.T) {
sg := NewOrderedScatterGather[int](4, 0, 0)
sg.AddWork(context.Background(), func() int {
return 1
})
doneChan := make(chan struct{})
st := time.Now()
go func() {
sg.Drain()
assert.InDelta(t, 200*time.Millisecond, time.Since(st), float64(10*time.Millisecond))
close(doneChan)
}()
time.Sleep(200 * time.Millisecond)
<-sg.OutputChannel()
<-doneChan
}