-
Notifications
You must be signed in to change notification settings - Fork 8
/
chan_test.go
60 lines (45 loc) · 1.2 KB
/
chan_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
package lock
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/suite"
)
type chanSuite struct {
suite.Suite
}
func (s *chanSuite) SetupSuite() {}
func (s *chanSuite) TearDownSuite() {}
func (s *chanSuite) SetupTest() {}
func (s *chanSuite) TearDownTest() {}
func TestChanSuite(t *testing.T) {
suite.Run(t, new(chanSuite))
}
func (s *chanSuite) TestChanTryLock() {
chanMut := NewChanMutex()
// write lock then write lock
s.Require().True(chanMut.TryLock())
s.Require().False(chanMut.TryLock())
chanMut.Unlock()
}
func (s *chanSuite) TestChanTryLockWithTimeout() {
chanMut := NewChanMutex()
// write lock then write lock
s.Require().True(chanMut.TryLockWithTimeout(50 * time.Millisecond))
s.Require().False(chanMut.TryLockWithTimeout(50 * time.Millisecond))
chanMut.Unlock()
}
func (s *chanSuite) TestChanLockRacing() {
chanMut := NewChanMutex()
count := int32(0) // default value
// write lock then write lock
chanMut.Lock()
go func() {
time.Sleep(50 * time.Millisecond)
s.Require().Equal(int32(1), atomic.AddInt32(&count, 1)) // A
chanMut.Unlock()
}()
chanMut.Lock()
s.Require().Equal(int32(2), atomic.AddInt32(&count, 1)) // add 1 after A
chanMut.Unlock()
}