Skip to content

Commit

Permalink
add tests for pidfile
Browse files Browse the repository at this point in the history
  • Loading branch information
Songmu committed Feb 21, 2017
1 parent bc8bba7 commit 27cac77
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 3 deletions.
8 changes: 5 additions & 3 deletions pidfile/pidfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@ func Create(pidfile string) error {
}

// Remove pidfile
func Remove(pidfile string) {
func Remove(pidfile string) error {
if pidfile == "" {
return
return nil
}
if err := os.Remove(pidfile); err != nil {
err := os.Remove(pidfile)
if err != nil {
logger.Errorf("Failed to remove the pidfile: %s: %s", pidfile, err)
}
return err
}
61 changes: 61 additions & 0 deletions pidfile/pidfile_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// +build !windows

package pidfile

import (
"io/ioutil"
"os"
"path/filepath"
"strconv"
"testing"
)

func TestCreate(t *testing.T) {
err := Create("")
if err != nil {
t.Errorf("err should be nil but: %v", err)
}

dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("failed to create tempdir")
}
defer os.RemoveAll(dir)
pidfile := filepath.Join(dir, "pidfile")
err = Create(pidfile)
if err != nil {
t.Errorf("err should be nil but: %v", err)
}
pidString, _ := ioutil.ReadFile(pidfile)
pid, _ := strconv.Atoi(string(pidString))
if pid != os.Getpid() {
t.Errorf("contents of pidfile does not match pid. content: %d, pid: %d", pid, os.Getpid())
}

err = Create(pidfile)
if err == nil {
t.Errorf("Successfully overwriting the pidfile unintentionally")
}
}

func TestRemove(t *testing.T) {
err := Remove("")
if err != nil {
t.Errorf("err should be nil but: %v", err)
}
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("failed to create tempdir")
}
defer os.RemoveAll(dir)
pidfile := filepath.Join(dir, "pidfile")
err = Create(pidfile)
if err != nil {
t.Errorf("err should be nil but: %v", err)
}

err = Remove(pidfile)
if err != nil {
t.Errorf("err should be nil but: %v", err)
}
}

0 comments on commit 27cac77

Please sign in to comment.