generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonce_test.go
80 lines (68 loc) · 1.68 KB
/
once_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
package cosyne_test
import (
"context"
"errors"
"time"
. "github.com/dogmatiq/cosyne"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("type Once", func() {
var (
ctx context.Context
cancel context.CancelFunc
once *Once
)
BeforeEach(func() {
ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
once = &Once{}
})
AfterEach(func() {
cancel()
})
Describe("func Do()", func() {
It("does not call the function again after success", func() {
called := false
err := once.Do(ctx, func(ctx context.Context) error {
called = true
return nil
})
Expect(err).ShouldNot(HaveOccurred())
Expect(called).To(BeTrue())
err = once.Do(ctx, func(ctx context.Context) error {
Fail("unexpected call")
return nil
})
Expect(err).ShouldNot(HaveOccurred())
})
It("calls the function again after an error returns", func() {
err := once.Do(ctx, func(ctx context.Context) error {
return errors.New("<error>")
})
Expect(err).To(MatchError("<error>"))
called := false
err = once.Do(ctx, func(ctx context.Context) error {
called = true
return nil
})
Expect(err).ShouldNot(HaveOccurred())
Expect(called).To(BeTrue())
})
It("blocks conccurent calls to Do()", func() {
otherCtx, cancel := context.WithCancel(context.Background())
defer cancel()
barrier := make(chan struct{})
go once.Do(otherCtx, func(ctx context.Context) error {
close(barrier)
<-ctx.Done()
return nil
})
<-barrier
err := once.Do(ctx, func(context.Context) error {
Fail("unexpected call")
return nil
})
Expect(err).To(Equal(context.DeadlineExceeded))
})
})
})