forked from gomods/athens
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwith_singleflight_test.go
64 lines (56 loc) · 1.42 KB
/
with_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
package stash
import (
"context"
"fmt"
"sync"
"testing"
"time"
"golang.org/x/sync/errgroup"
)
// TestSingleFlight will ensure that 5 concurrent requests will all get the first request's
// response. We can ensure that because only the first response does not return an error
// and therefore all 5 responses should have no error.
func TestSingleFlight(t *testing.T) {
ms := &mockSFStasher{}
s := WithSingleflight(ms)
var eg errgroup.Group
for i := 0; i < 5; i++ {
eg.Go(func() error {
_, err := s.Stash(context.Background(), "mod", "ver")
return err
})
}
err := eg.Wait()
if err != nil {
t.Fatal(err)
}
for i := 0; i < 5; i++ {
eg.Go(func() error {
_, err := s.Stash(context.Background(), "mod", "ver")
return err
})
}
err = eg.Wait()
if err == nil {
t.Fatal("expected second error to return")
}
}
// mockSFStasher mocks a Stash request that
// will always return a different result after the
// first one. This way we can prove that a second
// request did not get a second result, but the first
// one, provided the request came in at the right time.
type mockSFStasher struct {
mu sync.Mutex
num int
}
func (ms *mockSFStasher) Stash(ctx context.Context, mod, ver string) (string, error) {
time.Sleep(time.Millisecond * 100) // allow for second requests to come in.
ms.mu.Lock()
defer ms.mu.Unlock()
if ms.num == 0 {
ms.num++
return "", nil
}
return "", fmt.Errorf("second time error")
}