-
Notifications
You must be signed in to change notification settings - Fork 1
/
filelock_test.go
118 lines (97 loc) · 2.52 KB
/
filelock_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
112
113
114
115
116
117
118
package filelock
import (
"sync"
"testing"
"time"
)
func TestRepeatedObtainAndReleaseLock(t *testing.T) {
count := 100
for i := 0; i < count; i++ {
lock := FileLock{Path: "/tmp/.test.lock", Timeout: time.Second * 1}
err := lock.Lock()
if err != nil {
t.Error()
}
if err = lock.Unlock(); err != nil {
t.Error()
}
}
}
func TestObtainAndReleaseLockConcurrent(t *testing.T) {
count := 50
var wg sync.WaitGroup
wg.Add(count)
startTime := time.Now()
lockTime := time.Millisecond * 5
for i := 0; i < count; i++ {
go func() {
lock := FileLock{Path: "/tmp/.test1.lock", Timeout: time.Second * 1}
err := lock.Lock()
if err != nil {
t.Error()
}
time.Sleep(lockTime)
if err = lock.Unlock(); err != nil {
t.Error()
}
wg.Done()
}()
}
wg.Wait()
// Each goroutine held the lock for lockTime, so the
// test duration should be at least lockTime * count
duration := time.Since(startTime)
if int(duration/lockTime) < count {
t.Error()
}
}
func TestObtainLockTimeout(t *testing.T) {
lock := FileLock{Path: "/tmp/.test2.lock", Timeout: time.Second * 1}
if err := lock.Lock(); err != nil {
t.Error()
}
defer lock.Unlock()
lock2 := FileLock{Path: "/tmp/.test2.lock", Timeout: time.Millisecond * 10}
err := lock2.Lock()
if err != ErrLockTimeout {
t.Error()
}
}
func TestObtainLockTimeoutReleasesEventuallyObtainedLock(t *testing.T) {
lock := FileLock{Path: "/tmp/.test3.lock", Timeout: time.Second * 1}
if err := lock.Lock(); err != nil {
t.Error()
}
lock2 := FileLock{Path: "/tmp/.test3.lock", Timeout: time.Millisecond * 10}
if err := lock2.Lock(); err != ErrLockTimeout {
t.Error()
}
// Release the first lock, this causes the
// second lock to be obtained by the blocking goroutine,
// and then be released straight away.
if err := lock.Unlock(); err != nil {
t.Error()
}
// Given that the first lock has been released, and
// the second lock timed out and should have been released
// as soon as it was obtained by the still-blocking goroutine,
// a new lock should succeed.
lock3 := FileLock{Path: "/tmp/.test3.lock", Timeout: time.Millisecond * 10}
if err := lock3.Lock(); err != nil {
t.Error()
}
lock3.Unlock()
}
func TestLockFilePermissionDenied(t *testing.T) {
lock := FileLock{Path: "/.test.lock", Timeout: time.Second * 1}
if err := lock.Lock(); err == nil {
t.Error()
}
}
func TestUnlockWhenNotLocked(t *testing.T) {
lock := FileLock{Path: "/tmp/test.lock", Timeout: time.Second * 1}
err := lock.Unlock()
if err != ErrNotLocked {
t.Error()
}
}