-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleflight_test.go
More file actions
104 lines (87 loc) · 2.33 KB
/
singleflight_test.go
File metadata and controls
104 lines (87 loc) · 2.33 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright (c) 2023 Bruno Marques Venceslau de Souza. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package singleflight_test
import (
"errors"
"testing"
"github.com/brunomvsouza/singleflight"
)
func TestGroup_Do(t *testing.T) {
t.Run("success", func(t *testing.T) {
var g singleflight.Group[string, string]
v, err, _ := g.Do("key", func() (string, error) {
return "value", nil
})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if v != "value" {
t.Errorf("got %s, want %s", v, "value")
}
})
t.Run("error", func(t *testing.T) {
expectedErr := errors.New("test error")
var g singleflight.Group[string, string]
v, err, _ := g.Do("key", func() (string, error) {
return "", expectedErr
})
if err != expectedErr {
t.Errorf("got error %v, want %v", err, expectedErr)
}
if v != "" {
t.Errorf("got value %s, want empty string", v)
}
})
}
func TestGroup_DoChan(t *testing.T) {
t.Run("single call", func(t *testing.T) {
var g singleflight.Group[string, int]
ch := g.DoChan("key", func() (int, error) {
return 42, nil
})
res := <-ch
if got, want := res.Val, 42; got != want {
t.Errorf("DoChan = %v; want %v", got, want)
}
if res.Err != nil {
t.Errorf("DoChan error = %v", res.Err)
}
if res.Shared {
t.Errorf("DoChan shared = true; want false")
}
})
t.Run("concurrent calls", func(t *testing.T) {
var g singleflight.Group[string, int]
block := make(chan struct{})
unblock := make(chan struct{})
ch1 := g.DoChan("key", func() (int, error) {
close(block)
<-unblock
return 42, nil
})
<-block
ch2 := g.DoChan("key", func() (int, error) {
t.Error("second call should not be executed")
return 0, nil
})
close(unblock)
res1 := <-ch1
if got, want := res1.Val, 42; got != want {
t.Errorf("first DoChan = %v; want %v", got, want)
}
if !res1.Shared {
t.Errorf("first DoChan shared = false; want true")
}
res2 := <-ch2
if got, want := res2.Val, 42; got != want {
t.Errorf("second DoChan = %v; want %v", got, want)
}
if !res2.Shared {
t.Errorf("second DoChan shared = false; want true")
}
})
}