forked from sevlyar/go-daemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock_file_test.go
98 lines (86 loc) · 2.13 KB
/
lock_file_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
package daemon
import (
"fmt"
"io/ioutil"
"os"
"runtime"
"testing"
)
var (
filename = os.TempDir() + "/test.lock"
fileperm os.FileMode = 0644
invalidname = "/x/y/unknown"
)
func TestCreatePidFile(test *testing.T) {
if _, err := CreatePidFile(invalidname, fileperm); err == nil {
test.Fatal("CreatePidFile(): Error was not detected on invalid name")
}
lock, err := CreatePidFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
defer lock.Remove()
data, err := ioutil.ReadFile(filename)
if err != nil {
test.Fatal(err)
}
if string(data) != fmt.Sprint(os.Getpid()) {
test.Fatal("pids not equal")
}
file, err := os.OpenFile(filename, os.O_RDONLY, fileperm)
if err != nil {
test.Fatal(err)
}
if err = NewLockFile(file).WritePid(); err == nil {
test.Fatal("WritePid(): Error was not detected on invalid permissions")
}
}
func TestNewLockFile(test *testing.T) {
lock := NewLockFile(os.NewFile(1001, ""))
err := lock.Remove()
if err == nil {
test.Fatal("Remove(): Error was not detected on invalid fd")
}
err = lock.WritePid()
if err == nil {
test.Fatal("WritePid(): Error was not detected on invalid fd")
}
}
func TestReadPid(test *testing.T) {
lock, err := CreatePidFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
defer lock.Remove()
pid, err := lock.ReadPid()
if err != nil {
test.Fatal("ReadPid(): Unable read pid from file:", err)
}
if pid != os.Getpid() {
test.Fatal("Pid not equal real pid")
}
}
func TestLockFileLock(test *testing.T) {
lock1, err := OpenLockFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
if err := lock1.Lock(); err != nil {
test.Fatal(err)
}
defer lock1.Remove()
lock2, err := OpenLockFile(filename, fileperm)
if err != nil {
test.Fatal(err)
}
if runtime.GOOS == "solaris" {
// Solaris does not see a double lock attempt by the same process as failure.
if err := lock2.Lock(); err != nil {
test.Fatal("To lock file more than once must be unavailable.")
}
} else {
if err := lock2.Lock(); err != nil && err != ErrWouldBlock {
test.Fatal("To lock file more than once must be unavailable.")
}
}
}