github.com/elfadel/cilium@v1.6.12/pkg/pidfile/pidfile_test.go (about) 1 // Copyright 2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // +build !privileged_tests 16 17 package pidfile 18 19 import ( 20 "fmt" 21 "io/ioutil" 22 "os" 23 "os/exec" 24 "testing" 25 26 "github.com/cilium/cilium/pkg/checker" 27 28 . "gopkg.in/check.v1" 29 ) 30 31 const ( 32 path = "/tmp/cilium-test-pidfile" 33 ) 34 35 // Hook up gocheck into the "go test" runner. 36 func Test(t *testing.T) { 37 TestingT(t) 38 } 39 40 type PidfileTestSuite struct{} 41 42 var _ = Suite(&PidfileTestSuite{}) 43 44 func (s *PidfileTestSuite) TestWrite(c *C) { 45 err := Write(path) 46 c.Assert(err, IsNil) 47 defer Remove(path) 48 49 content, err := ioutil.ReadFile(path) 50 c.Assert(err, IsNil) 51 c.Assert(content, checker.DeepEquals, []byte(fmt.Sprintf("%d\n", os.Getpid()))) 52 } 53 54 func (s *PidfileTestSuite) TestKill(c *C) { 55 cmd := exec.Command("sleep", "inf") 56 err := cmd.Start() 57 c.Assert(err, IsNil) 58 59 err = write(path, cmd.Process.Pid) 60 c.Assert(err, IsNil) 61 defer Remove(path) 62 63 pid, err := Kill(path) 64 c.Assert(err, IsNil) 65 c.Assert(pid, Not(Equals), 0) 66 67 err = cmd.Wait() 68 c.Assert(err, ErrorMatches, "signal: killed") 69 } 70 71 func (s *PidfileTestSuite) TestKillAlreadyFinished(c *C) { 72 cmd := exec.Command("sleep", "0") 73 err := cmd.Start() 74 c.Assert(err, IsNil) 75 76 err = write(path, cmd.Process.Pid) 77 c.Assert(err, IsNil) 78 defer Remove(path) 79 80 err = cmd.Wait() 81 c.Assert(err, IsNil) 82 83 pid, err := Kill(path) 84 c.Assert(err, IsNil) 85 c.Assert(pid, Equals, 0) 86 } 87 88 func (s *PidfileTestSuite) TestKillPidfileNotExist(c *C) { 89 _, err := Kill("/tmp/cilium-foo-bar-some-not-existing-file") 90 c.Assert(err, IsNil) 91 } 92 93 func (s *PidfileTestSuite) TestKillPidfilePermissionDenied(c *C) { 94 err := ioutil.WriteFile(path, []byte("foobar\n"), 0000) 95 c.Assert(err, IsNil) 96 defer Remove(path) 97 98 _, err = Kill(path) 99 c.Assert(err, ErrorMatches, ".* permission denied") 100 } 101 102 func (s *PidfileTestSuite) TestKillFailedParsePid(c *C) { 103 err := ioutil.WriteFile(path, []byte("foobar\n"), 0644) 104 c.Assert(err, IsNil) 105 defer Remove(path) 106 107 _, err = Kill(path) 108 c.Assert(err, ErrorMatches, "failed to parse pid .*") 109 }