-
Notifications
You must be signed in to change notification settings - Fork 0
/
cached_task_test.go
125 lines (99 loc) · 2.55 KB
/
cached_task_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
116
117
118
119
120
121
122
123
124
125
package generics_test
import (
"context"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zeroflucs-given/generics"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestExecuteOnce(t *testing.T) {
t.Parallel()
t.Run("simple", func(t *testing.T) {
type XX struct {
X int64
}
counter := atomic.Int32{}
var task = generics.ExecuteOnce[XX](func(ctx context.Context) (*XX, error) {
//_ = <-time.After(5 * time.Second)
counter.Add(1)
return &XX{X: 42}, nil
})
ctx := context.Background()
expected := &XX{X: 42}
ch := make(chan struct{})
go func() {
x1, err := task.Get(ctx)
require.NoError(t, err)
require.Equal(t, expected, x1)
ch <- struct{}{}
}()
x2, err := task.Get(ctx)
require.NoError(t, err)
require.Equal(t, expected, x2)
// Check our counter (i.e. the job) has only been executed once.
require.Equal(t, int32(1), counter.Load())
<-ch
})
t.Run("panic_recovery", func(t *testing.T) {
task := generics.ExecuteOnce[struct{}](func(ctx context.Context) (*struct{}, error) {
panic("something went wrong")
})
ctx := context.Background()
go func() {
_, err := task.Get(ctx)
assert.Error(t, err)
}()
_, err := task.Get(ctx)
assert.Error(t, err)
})
t.Run("context_cancellation", func(t *testing.T) {
taskWait := make(chan struct{})
taskStarted := make(chan struct{})
task := generics.ExecuteOnce[struct{}](func(ctx context.Context) (*struct{}, error) {
taskStarted <- struct{}{}
<-taskWait
return &struct{}{}, nil
})
// Start a blocked task and wait for it to start.
go func() {
_, err := task.Get(context.Background())
assert.NoError(t, err)
}()
<-taskStarted
// Start another task waiting for the first to finish, and cancel it.
ctx1, cancel1 := context.WithCancel(context.Background())
cancel1()
_, err := task.Get(ctx1)
assert.ErrorIs(t, err, context.Canceled)
taskWait <- struct{}{}
})
t.Run("big", func(t *testing.T) {
type XX struct {
X int64
}
task := generics.ExecuteOnce[XX](func(ctx context.Context) (*XX, error) {
<-time.After(5 * time.Second)
return &XX{X: 42}, nil
})
ctx := context.Background()
expected := &XX{X: 42}
// 100,000 = 5s 140ms
// 1,000,000 = 6s 40ms
// 10,000,000 = 25s 100ms
// 100,000,000 = 5 min 24s
wg := sync.WaitGroup{}
wg.Add(1_000_000)
for i := 0; i < 1_000_000; i += 1 {
go func() {
val, err := task.Get(ctx)
assert.NoError(t, err)
assert.Equal(t, expected, val)
wg.Done()
}()
}
wg.Wait()
})
}