-
Notifications
You must be signed in to change notification settings - Fork 5
/
promise_test.go
87 lines (73 loc) · 1.94 KB
/
promise_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
package future
import (
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestPromise(t *testing.T) {
p := NewPromise(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
value, err := p.Get()
assert.Equal(t, 42, value)
assert.NoError(t, err)
}
func TestPromiseThen(t *testing.T) {
p := NewPromise(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
value, err := p.Then(func(value Value) (Value, error) {
time.Sleep(1 * time.Second)
return value.(int) + 3, nil
}).Get()
assert.Equal(t, 45, value)
assert.NoError(t, err)
}
func TestPromiseErrorThen(t *testing.T) {
p := NewPromise(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return nil, errors.New("error!")
})
value, err := p.Then(func(value Value) (Value, error) {
time.Sleep(100 * time.Millisecond)
return value.(int) + 3, nil
}).Get()
assert.Nil(t, value)
assert.Error(t, err)
}
func TestPromiseChain(t *testing.T) {
value, err := NewPromise(func() (Value, error) {
time.Sleep(10 * time.Millisecond)
return 20, nil
}).Then(func(value Value) (Value, error) {
time.Sleep(10 * time.Millisecond)
return value.(int) - 10, nil
}).Then(func(value Value) (Value, error) {
time.Sleep(10 * time.Millisecond)
return value.(int) * 3, nil
}).Then(func(value Value) (Value, error) {
time.Sleep(10 * time.Millisecond)
return value.(int) / 5, nil
}).Get()
assert.Equal(t, 6, value)
assert.NoError(t, err)
}
func TestPromiseChainDelay(t *testing.T) {
start := time.Now()
p1 := NewPromise(func() (Value, error) {
time.Sleep(100 * time.Millisecond)
return 42, nil
})
p2 := p1.Then(func(value Value) (Value, error) {
time.Sleep(100 * time.Millisecond)
return value.(int) + 3, nil
})
assert.InDelta(t, 0.0, time.Since(start).Seconds(), 0.01)
value, err := p2.Get()
assert.Equal(t, 45, value)
assert.NoError(t, err)
assert.InDelta(t, 0.2, time.Since(start).Seconds(), 0.05)
}