github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/polkit/pid_start_time_test.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  // +build linux
     3  
     4  /*
     5   * Copyright (C) 2017 Canonical Ltd
     6   *
     7   * This program is free software: you can redistribute it and/or modify
     8   * it under the terms of the GNU General Public License version 3 as
     9   * published by the Free Software Foundation.
    10   *
    11   * This program is distributed in the hope that it will be useful,
    12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14   * GNU General Public License for more details.
    15   *
    16   * You should have received a copy of the GNU General Public License
    17   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    18   *
    19   */
    20  
    21  package polkit
    22  
    23  import (
    24  	"io/ioutil"
    25  	"os"
    26  	"path/filepath"
    27  	"syscall"
    28  	"testing"
    29  
    30  	"gopkg.in/check.v1"
    31  )
    32  
    33  func Test(t *testing.T) { check.TestingT(t) }
    34  
    35  type polkitSuite struct{}
    36  
    37  var _ = check.Suite(&polkitSuite{})
    38  
    39  func (s *polkitSuite) TestGetStartTime(c *check.C) {
    40  	pid := os.Getpid()
    41  
    42  	startTime, err := getStartTimeForPid(int32(pid))
    43  	c.Assert(err, check.IsNil)
    44  	c.Check(startTime, check.Not(check.Equals), uint64(0))
    45  }
    46  
    47  func (s *polkitSuite) TestGetStartTimeBadPid(c *check.C) {
    48  	// Find an unused process ID by checking for errors from Kill.
    49  	pid := 2
    50  	for {
    51  		if err := syscall.Kill(pid, 0); err == syscall.ESRCH {
    52  			break
    53  		}
    54  		pid += 1
    55  	}
    56  
    57  	startTime, err := getStartTimeForPid(int32(pid))
    58  	c.Assert(err, check.ErrorMatches, "open .*: no such file or directory")
    59  	c.Check(startTime, check.Equals, uint64(0))
    60  }
    61  
    62  func (s *polkitSuite) TestProcStatParsing(c *check.C) {
    63  	filename := filepath.Join(c.MkDir(), "stat")
    64  	contents := []byte("18433 (cat) R 9732 18433 9732 34818 18433 4194304 96 0 1 0 0 0 0 0 20 0 1 0 123104764 7602176 182 18446744073709551615 94902526107648 94902526138492 140734457666896 0 0 0 0 0 0 0 0 0 17 5 0 0 0 0 0 94902528236168 94902528237760 94902542680064 140734457672267 140734457672287 140734457672287 140734457675759 0")
    65  	err := ioutil.WriteFile(filename, contents, 0644)
    66  	c.Assert(err, check.IsNil)
    67  
    68  	startTime, err := getStartTimeForProcStatFile(filename)
    69  	c.Assert(err, check.IsNil)
    70  	c.Check(startTime, check.Equals, uint64(123104764))
    71  }