-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfuture_test.go
137 lines (124 loc) · 2.42 KB
/
future_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
126
127
128
129
130
131
132
133
134
135
136
137
package future
import (
"errors"
"runtime"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var errFoo = errors.New("foo")
func TestPromiseAndFuture(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
p.Set(1, errFoo)
val, err := f.Get()
assert.Equal(t, val, 1)
assert.Equal(t, err, errFoo)
assert.Equal(t, 2, f.GetOrDefault(2))
}
func TestPromiseAndFutureConcurrency(t *testing.T) {
n := runtime.NumCPU() - 1
ch := make(chan struct{}, n)
p := NewPromise[int]()
go func() {
for i := 0; i < n; i++ {
ch <- struct{}{}
}
time.Sleep(1 * time.Second)
p.Set(1, errFoo)
}()
wg := sync.WaitGroup{}
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-ch
f := p.Future()
val, err := f.Get()
assert.Equal(t, val, 1)
assert.Equal(t, err, errFoo)
}()
}
wg.Wait()
}
func TestPromiseSetTwice(t *testing.T) {
p := NewPromise[int]()
p.Set(1, nil)
assert.Panics(t, func() {
p.Set(1, nil)
})
}
func TestPromiseSetSafetyTwice(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
p.SetSafety(1, nil)
p.SetSafety(2, nil)
val, err := f.Get()
assert.Equal(t, 1, val)
assert.NoError(t, err)
}
func TestFutureSubscribe(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
val1 := 0
val2 := 0
f.Subscribe(func(val int, err error) {
val1 = val + 1
})
f.Subscribe(func(val int, err error) {
val2 = val + 2
})
p.Set(1, nil)
assert.Equal(t, val1, 2)
assert.Equal(t, val2, 3)
}
func TestPromiseFreeAndFutureDone(t *testing.T) {
p := NewPromise[int]()
f := p.Future()
assert.True(t, p.Free())
assert.False(t, f.Done())
p.Set(1, nil)
assert.False(t, p.Free())
assert.True(t, f.Done())
}
func Benchmark(b *testing.B) {
b.Run("Promise", func(b *testing.B) {
for i := 0; i < b.N; i++ {
p := NewPromise[int]()
f := p.Future()
go func() {
p.Set(1, nil)
}()
_, _ = f.Get()
}
})
b.Run("WaitGroup", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var val int
var err error
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
val, err = 0, nil
wg.Done()
}()
wg.Wait()
_, _ = val, err
}
})
// channel does not support multi-consumers. This is used to compare the performance of a single consumer.
b.Run("Channel", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var val int
var err error
ch := make(chan struct{})
go func() {
val, err = 0, nil
ch <- struct{}{}
}()
<-ch
_, _ = val, err
}
})
}