-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfuture_test.go
More file actions
112 lines (91 loc) · 2.41 KB
/
future_test.go
File metadata and controls
112 lines (91 loc) · 2.41 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package future
import (
"errors"
"testing"
"time"
"golang.org/x/net/context"
"github.com/stretchr/testify/assert"
)
func TestFutureError(t *testing.T) {
f1 := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return nil, errors.New("test error")
})
value, err := f1.Get()
assert.Error(t, err)
assert.Nil(t, value)
}
func TestFutureAsync(t *testing.T) {
start := time.Now()
f1 := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
f2 := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 43, nil
})
value, err := f1.Get()
assert.Equal(t, 42, value)
assert.NoError(t, err)
value, err = f2.Get()
assert.Equal(t, 43, value)
assert.NoError(t, err)
assert.InDelta(t, 0.1, time.Since(start).Seconds(), 0.01)
}
func TestFutureWithTimeout(t *testing.T) {
start := time.Now()
f := NewFuture(func() (Value, error) {
time.Sleep(1 * time.Second)
return 42, nil
})
value, err := f.GetWithTimeout(100 * time.Millisecond)
assert.Error(t, err)
assert.Equal(t, ErrTimeout, err)
assert.Nil(t, value)
assert.InDelta(t, 0.1, time.Since(start).Seconds(), 0.01)
}
func TestFutureWithTimeoutComplete(t *testing.T) {
start := time.Now()
f := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
value, err := f.GetWithTimeout(1 * time.Second)
assert.Equal(t, 42, value)
assert.NoError(t, err)
assert.InDelta(t, 0.1, time.Since(start).Seconds(), 0.01)
}
func TestFutureWithContext(t *testing.T) {
f := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
ctx := context.Background()
value, err := f.GetWithContext(ctx)
assert.NoError(t, err)
assert.Equal(t, 42, value)
}
func TestFutureWithContextCancel(t *testing.T) {
f := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
ctx, cancel := context.WithCancel(context.Background())
cancel()
value, err := f.GetWithContext(ctx)
assert.Error(t, err)
assert.Equal(t, context.Canceled, err)
assert.Nil(t, value)
}
func TestFutureWithContextTimeout(t *testing.T) {
f := NewFuture(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
ctx, _ := context.WithTimeout(context.Background(), 10*time.Millisecond)
value, err := f.GetWithContext(ctx)
assert.Error(t, err)
assert.Equal(t, context.DeadlineExceeded, err)
assert.Nil(t, value)
}