generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex_test.go
108 lines (83 loc) 路 2.11 KB
/
mutex_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cosyne_test
import (
"context"
"time"
. "github.com/dogmatiq/cosyne"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("type Mutex", func() {
var (
ctx context.Context
cancel context.CancelFunc
mutex *Mutex
)
BeforeEach(func() {
ctx, cancel = context.WithTimeout(context.Background(), 50*time.Millisecond)
mutex = &Mutex{}
})
AfterEach(func() {
cancel()
})
Describe("func Lock()", func() {
It("blocks calls to Lock()", func() {
err := mutex.Lock(ctx)
Expect(err).ShouldNot(HaveOccurred())
err = mutex.Lock(ctx)
Expect(err).To(Equal(context.DeadlineExceeded))
})
It("causes TryLock() to return false", func() {
err := mutex.Lock(ctx)
Expect(err).ShouldNot(HaveOccurred())
ok := mutex.TryLock()
Expect(ok).To(BeFalse())
})
})
Describe("func TryLock()", func() {
It("blocks calls to Lock()", func() {
ok := mutex.TryLock()
Expect(ok).To(BeTrue())
err := mutex.Lock(ctx)
Expect(err).To(Equal(context.DeadlineExceeded))
})
It("causes TryLock() to return false", func() {
ok := mutex.TryLock()
Expect(ok).To(BeTrue())
ok = mutex.TryLock()
Expect(ok).To(BeFalse())
})
})
Describe("func Unlock()", func() {
It("allows subsequent calls to Lock()", func() {
err := mutex.Lock(ctx)
Expect(err).ShouldNot(HaveOccurred())
mutex.Unlock()
err = mutex.Lock(ctx)
Expect(err).ShouldNot(HaveOccurred())
})
It("allows subsequent calls to TryLock()", func() {
err := mutex.Lock(ctx)
Expect(err).ShouldNot(HaveOccurred())
mutex.Unlock()
ok := mutex.TryLock()
Expect(ok).To(BeTrue())
})
It("unblocks one blocking call to Lock()", func() {
err := mutex.Lock(ctx)
Expect(err).ShouldNot(HaveOccurred())
errors := make(chan error, 2)
fn := func() { errors <- mutex.Lock(ctx) }
go fn()
go fn()
time.Sleep(5 * time.Millisecond)
mutex.Unlock()
Expect(<-errors).ShouldNot(HaveOccurred())
Expect(<-errors).To(Equal(context.DeadlineExceeded))
})
It("panics if the mutex is not locked", func() {
Expect(func() {
mutex.Unlock()
}).To(Panic())
})
})
})