-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator-key-ptr_test.go
66 lines (56 loc) · 1.41 KB
/
decorator-key-ptr_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
//go:build !race
package examples
import (
"testing"
"github.com/ahuigo/gofnext"
)
func TestCacheFuncKeyPointerAddr(t *testing.T) {
type UserInfo struct {
Name string
Age int
id int
}
// Original function
executeCount := 0
getUserScore := func(user *UserInfo) (int, error) {
executeCount++
// fmt.Println("select score from db where id=", user.id, time.Now())
return 98 + user.id, nil
}
// Cacheable Function
getUserScoreFromDbWithCache := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{
HashKeyPointerAddr: true,
})
// Execute the function multi times in parallel.
parallelCall(func() {
score, _ := getUserScoreFromDbWithCache(&UserInfo{id: 1})
if score != 99 {
t.Errorf("score should be 99, but get %d", score)
}
getUserScoreFromDbWithCache(&UserInfo{id: 2})
}, 5)
if executeCount != 10 {
t.Errorf("executeCount should be 10, but get %d", executeCount)
}
}
func TestCacheFuncKeyPointerCycle(t *testing.T) {
type UserInfo struct {
Name string
Age int
id int
User *UserInfo
}
// Original function
getUserScore := func(user *UserInfo) (int, error) {
return 98 + user.id, nil
}
// Cacheable Function
getUserScoreCached := gofnext.CacheFn1Err(getUserScore, &gofnext.Config{})
// Execute the function multi times in parallel.
u := &UserInfo{id: 1}
u.User = u
score, _ := getUserScoreCached(u)
if score != 99 {
t.Errorf("score should be 99, but get %d", score)
}
}