-
Notifications
You must be signed in to change notification settings - Fork 11
/
priority_lock_test.go
66 lines (58 loc) · 1.42 KB
/
priority_lock_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
package async
import (
"strconv"
"strings"
"testing"
"time"
"github.com/reugn/async/internal/assert"
)
func TestPriorityLock(t *testing.T) {
p := NewPriorityLock(5)
var b strings.Builder
p.Lock() // acquire first to make the result predictable
go func() {
time.Sleep(time.Millisecond)
p.Unlock()
}()
for i := 0; i < 10; i++ {
for j := 5; j > 0; j-- {
go func(n int) {
p.LockP(n)
time.Sleep(time.Microsecond)
b.WriteString(strconv.Itoa(n))
p.Unlock()
}(j)
}
}
time.Sleep(20 * time.Millisecond)
p.Lock()
result := b.String()
p.Unlock()
var expected strings.Builder
for i := 5; i > 0; i-- {
expected.WriteString(strings.Repeat(strconv.Itoa(i), 10))
}
assert.Equal(t, result, expected.String())
}
func TestPriorityLock_LockRange(t *testing.T) {
p := NewPriorityLock(2)
var b strings.Builder
p.LockP(-1)
b.WriteRune('1')
p.Unlock()
p.LockP(2048)
b.WriteRune('1')
p.Unlock()
assert.Equal(t, b.String(), "11")
}
func TestPriorityLock_Panic(t *testing.T) {
p := NewPriorityLock(2)
p.Lock()
time.Sleep(time.Nanosecond) // to silence empty critical section warning
p.Unlock()
assert.PanicMsgContains(t, func() { p.Unlock() }, "unlock of unlocked PriorityLock")
}
func TestPriorityLock_Validation(t *testing.T) {
assert.PanicMsgContains(t, func() { NewPriorityLock(-1) }, "nonpositive maximum priority")
assert.PanicMsgContains(t, func() { NewPriorityLock(2048) }, "exceeds hard limit")
}