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
|
package pidfile_test
import (
"errors"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/facebookgo/pidfile"
)
// Make a temporary file, remove it, and return it's path with the hopes that
// no one else create a file with that name.
func tempfilename(t *testing.T) string {
file, err := ioutil.TempFile("", "pidfile-test")
if err != nil {
t.Fatal(err)
}
err = file.Close()
if err != nil {
t.Fatal(err)
}
err = os.Remove(file.Name())
if err != nil {
t.Fatal(err)
}
return file.Name()
}
func TestGetSetPath(t *testing.T) {
p := tempfilename(t)
defer os.Remove(p)
pidfile.SetPidfilePath(p)
if a := pidfile.GetPidfilePath(); a != p {
t.Fatalf("was expecting %s but got %s", p, a)
}
}
func TestSimple(t *testing.T) {
p := tempfilename(t)
defer os.Remove(p)
pidfile.SetPidfilePath(p)
if err := pidfile.Write(); err != nil {
t.Fatal(err)
}
pid, err := pidfile.Read()
if err != nil {
t.Fatal(err)
}
if os.Getpid() != pid {
t.Fatalf("was expecting %d but got %d", os.Getpid(), pid)
}
}
func TestPidfileNotConfigured(t *testing.T) {
pidfile.SetPidfilePath("")
err := pidfile.Write()
if err == nil {
t.Fatal("was expecting an error")
}
if !pidfile.IsNotConfigured(err) {
t.Fatalf("was expecting IsNotConfigured error but got: %s", err)
}
_, err = pidfile.Read()
if err == nil {
t.Fatal("was expecting an error")
}
if !pidfile.IsNotConfigured(err) {
t.Fatalf("was expecting IsNotConfigured error but got: %s", err)
}
}
func TestNonIsConfiguredError(t *testing.T) {
err := errors.New("foo")
if pidfile.IsNotConfigured(err) {
t.Fatal("should be false")
}
}
func TestMakesDirectories(t *testing.T) {
dir := tempfilename(t)
defer os.RemoveAll(dir)
p := filepath.Join(dir, "pidfile")
pidfile.SetPidfilePath(p)
if err := pidfile.Write(); err != nil {
t.Fatal(err)
}
pid, err := pidfile.Read()
if err != nil {
t.Fatal(err)
}
if os.Getpid() != pid {
t.Fatalf("was expecting %d but got %d", os.Getpid(), pid)
}
}
|