forked from abiosoft/semaphore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore_test.go
85 lines (79 loc) · 1.57 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
package semaphore
import (
"context"
"sync"
"testing"
"time"
)
func TestLen(t *testing.T) {
s := New(10)
defer s.Drain()
if l := s.Len(); l != 10 {
t.Errorf("wrong Len: %d", l)
}
}
func TestAcquireContextBusy(t *testing.T) {
s := New(1)
defer s.Drain()
s.Acquire()
ch := make(chan struct{}, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
ok := s.AcquireContext(ctx)
if ok {
t.Errorf("should not have acquired a resource, but did")
}
ch <- struct{}{}
}()
<-ch
}
func TestAcquireContextNotBusy(t *testing.T) {
s := New(2)
defer s.Drain()
s.Acquire()
// ugh this is a mess haha
var wg sync.WaitGroup
wg.Add(1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
ok := s.AcquireContext(ctx)
if !ok {
t.Errorf("should have acquired a resource, but did not")
}
wg.Done()
}()
wg.Wait()
}
func TestAcquireContextBecomesAvailableBeforeTimeout(t *testing.T) {
s := New(1)
defer s.Drain()
s.Acquire()
go func() {
time.Sleep(5 * time.Millisecond)
s.Release()
}()
ok := s.AcquireContext(context.Background())
if !ok {
t.Errorf("should have acquired a resource, but did not")
}
}
func TestSimultaneousAcquire(t *testing.T) {
s := New(2)
defer s.Drain()
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
s.Acquire()
time.Sleep(50 * time.Nanosecond)
s.Release()
wg.Done()
}(i)
}
wg.Wait()
if avail := s.Available(); avail != 2 {
t.Errorf("expected 2 available, got %d", avail)
}
}