-
Notifications
You must be signed in to change notification settings - Fork 0
/
safeonce_test.go
92 lines (76 loc) · 1.53 KB
/
safeonce_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
86
87
88
89
90
91
92
package safeonce_test
import (
"fmt"
"testing"
. "github.com/koofr/safeonce"
)
type one int
func (o *one) Increment() {
*o++
}
func run(t *testing.T, safeOnce *SafeOnce, o *one, c chan bool) {
safeOnce.Do(func() error { o.Increment(); return nil })
if v := *o; v != 1 {
t.Errorf("once failed inside run: %d is not 1", v)
}
c <- true
}
func TestOnce(t *testing.T) {
o := new(one)
safeOnce := new(SafeOnce)
c := make(chan bool)
const N = 10
for i := 0; i < N; i++ {
go run(t, safeOnce, o, c)
}
for i := 0; i < N; i++ {
<-c
}
if *o != 1 {
t.Errorf("safeOnce failed outside run: %d is not 1", *o)
}
}
func TestSafeOncePanic(t *testing.T) {
var safeOnce SafeOnce
func() {
defer func() {
if r := recover(); r == nil {
t.Fatalf("SafeOnce.Do did not panic")
}
}()
err := safeOnce.Do(func() error {
panic("failed")
return nil
})
if err != nil {
t.Fatalf("SafeOnce.Do error should be nil")
}
}()
err := safeOnce.Do(func() error {
t.Fatalf("SafeOnce.Do called twice")
return nil
})
if err != nil {
t.Fatalf("SafeOnce.Do error should be nil")
}
}
func TestSafeOnceError(t *testing.T) {
var safeOnce SafeOnce
err := safeOnce.Do(func() error {
return fmt.Errorf("SafeOnce.Do error")
})
if err == nil {
t.Fatalf("SafeOnce.Do error should not be nil")
}
calledTwice := false
err = safeOnce.Do(func() error {
calledTwice = true
return nil
})
if !calledTwice {
t.Fatalf("SafeOnce.Do should be called twice")
}
if err != nil {
t.Fatalf("SafeOnce.Do error should be nil")
}
}