-
Notifications
You must be signed in to change notification settings - Fork 0
/
memo_test.go
85 lines (69 loc) · 1.48 KB
/
memo_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
package memo
import (
"errors"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestMemo(t *testing.T) {
f := Memo(func() interface{} {
return fmt.Sprintf("Pesco %s", time.Now().Format("15:04:05"))
}, time.Second)
now := fmt.Sprintf("Pesco %s", time.Now().Format("15:04:05"))
assert.Equal(t, now, f())
time.Sleep(3 * time.Second)
assert.Equal(t, now, f()) // cached value and trigger refresh
time.Sleep(250 * time.Millisecond)
assert.NotEqual(t, now, f()) // refreshed value
}
func TestMemoX(t *testing.T) {
v := 0
f := MemoX(func() (interface{}, error) {
v = v + 1
if v >= 3 && v <= 7 {
return v, errors.New("Raising exception!")
}
return v, nil
}, 10*time.Millisecond)
p := -1
for i := 0; i < 20; i++ {
p = f().(int)
time.Sleep(50 * time.Millisecond)
}
assert.Equal(t, v, 20)
assert.Equal(t, p, 19)
}
func TestMemoX2(t *testing.T) {
f := MemoX(func() (interface{}, error) {
return nil, errors.New("Raising exception!")
}, 10*time.Millisecond)
p := f()
assert.Equal(t, errors.New("Raising exception!"), p)
}
func TestStampede(t *testing.T) {
v := 0
f := Memo(func() interface{} {
v = v + 1
return v
}, time.Second)
t0 := time.Now()
c := 0
o := 0
for time.Now().Sub(t0) < 10*time.Second {
c = c + 1
o = f().(int)
}
assert.Less(t, o, c)
assert.Equal(t, 10, o)
}
func BenchmarkMemo(b *testing.B) {
v := 0
f := Memo(func() interface{} {
v = v + 1
return v
}, time.Second)
for n := 0; n < b.N; n++ {
f()
}
}