2020-08-20 13:57:17 +00:00
|
|
|
package lockfile_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
2020-09-08 14:24:27 +00:00
|
|
|
"kdelsd/lockfile"
|
2020-08-20 13:57:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
func tmpFile() string {
|
|
|
|
tf, err := ioutil.TempFile("", "lockfile_test*")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return tf.Name()
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestNotLockedUnlockPanics(t *testing.T) {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r == nil {
|
|
|
|
t.Errorf("Unlock() did not panic")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
tf := tmpFile()
|
|
|
|
defer os.Remove(tf)
|
|
|
|
|
|
|
|
|
|
|
|
err := lockfile.New(tf).Unlock()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestSecondLockFails(t *testing.T) {
|
|
|
|
tf := tmpFile()
|
|
|
|
defer os.Remove(tf)
|
|
|
|
|
|
|
|
fl1 := lockfile.New(tf)
|
|
|
|
err := fl1.Lock()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
defer fl1.Unlock()
|
|
|
|
|
|
|
|
fl2 := lockfile.New(tf)
|
|
|
|
err = fl2.Lock()
|
|
|
|
if err == nil {
|
|
|
|
t.Errorf("Second Lock() did not fail")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestLockUnlock(t *testing.T) {
|
|
|
|
tf := tmpFile()
|
|
|
|
defer os.Remove(tf)
|
|
|
|
|
|
|
|
fl := lockfile.New(tf)
|
|
|
|
err := fl.Lock()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
err = fl.Unlock()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if _, err := os.Stat(tf); !os.IsNotExist(err) {
|
|
|
|
t.Errorf("Lockfile %s still exists", tf)
|
|
|
|
}
|
|
|
|
}
|