-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsingleflight_test.go
83 lines (68 loc) · 1.83 KB
/
singleflight_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
package psadm
import (
"context"
"log"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/aws/aws-sdk-go-v2/service/ssm/types"
"github.com/patrickmn/go-cache"
"github.com/stretchr/testify/assert"
gomock "go.uber.org/mock/gomock"
)
func TestSingleflightCient(t *testing.T) {
assert := assert.New(t)
mockctrl := gomock.NewController(t)
mockSSM := NewMockssmClient(mockctrl)
client := &Client{SSM: mockSSM}
ch := make(chan struct{})
mockSSM.EXPECT().GetParameter(gomock.Any(), gomock.Any()).
// make sure the client only call the underlying client once
Times(1).
DoAndReturn(func(_ context.Context, _ *ssm.GetParameterInput, _ ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) {
log.Print("ssm client is waiting for goroutines launched...")
<-ch
log.Print("ssm client is going to return a result")
return &ssm.GetParameterOutput{
Parameter: &types.Parameter{
Value: aws.String("value"),
},
}, nil
})
c := cache.New(time.Minute, 10*time.Minute)
sfc := client.SingleflightClientWithCache(c)
// launch 10 goroutines
const numG = 10
var launched int
var wg sync.WaitGroup
wg.Add(numG)
cond := sync.NewCond(&sync.Mutex{})
for i := 0; i < numG; i++ {
log.Print("Launching goroutine...")
go func() {
defer wg.Done()
cond.L.Lock()
launched++
cond.L.Unlock()
// let the main goroutine check launched again
cond.Signal()
actual, err := sfc.GetParameter(context.TODO(), "key")
assert.NoError(err)
assert.Equal("value", actual)
}()
}
log.Print("Waiting for goroutines launched...")
cond.L.Lock()
for launched != numG {
cond.Wait()
}
cond.L.Unlock()
log.Print("Goroutines launched")
close(ch)
wg.Wait()
cvalue, found := c.Get("GetParameter/key")
assert.True(found)
assert.Equal("value", cvalue)
}