-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore_test.go
111 lines (81 loc) · 1.77 KB
/
semaphore_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
109
110
111
package semaphore
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNew(t *testing.T) {
rs := New(5)
assert.Equal(t, 0, rs.Len())
assert.Equal(t, 5, rs.Cap())
}
func TestResize(t *testing.T) {
a := assert.New(t)
t.Run("Basic", func(t *testing.T) {
rs := New(5)
a.Equal(5, rs.Cap())
rs.Resize(1)
a.Equal(1, rs.Cap())
})
t.Run("ResizeUpWhileActive", func(t *testing.T) {
rs := New(1)
fmt.Println(rs.String())
err := rs.Acquire(context.Background())
a.NoError(err)
fmt.Println(rs.String())
go func() {
time.Sleep(3 * time.Second)
rs.Resize(2)
}()
err = rs.Acquire(context.Background())
a.NoError(err)
defer fmt.Println(rs.String())
})
t.Run("ResizeDownWhileActive", func(t *testing.T) {
rs := New(2)
fmt.Println(rs.String())
err := rs.Acquire(context.Background())
a.NoError(err)
err = rs.Acquire(context.Background())
a.NoError(err)
fmt.Println(rs.String())
rs.Resize(1)
fmt.Println(rs.String())
a.Equal(2, rs.Len())
a.Equal(1, rs.Cap())
rs.Release()
a.Equal(1, rs.Len())
a.Equal(1, rs.Cap())
fmt.Println(rs.String())
})
}
func TestAcquire(t *testing.T) {
a := assert.New(t)
t.Run("Basic", func(t *testing.T) {
r := New(1)
a.NoError(r.Acquire(context.Background()))
})
t.Run("Block", func(t *testing.T) {
r := New(1)
a.NoError(r.Acquire(context.Background()))
go func() {
time.Sleep(3 * time.Second)
r.Release()
}()
a.NoError(r.Acquire(context.Background()))
})
t.Run("Cancel", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
r := New(1)
a.NoError(r.Acquire(ctx))
go func() {
time.Sleep(3 * time.Second)
cancel()
}()
err := r.Acquire(ctx)
a.Error(err)
a.ErrorIs(err, context.Canceled)
})
}