chore: use testify instead of testing

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
pull/1815/head
Matthieu MOREL 6 days ago
parent 62da883e11
commit 8c1a718a5d

@ -7,6 +7,9 @@ import (
"os"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestInfo_AppleSilicon(t *testing.T) {
@ -15,19 +18,13 @@ func TestInfo_AppleSilicon(t *testing.T) {
}
v, err := Info()
if err != nil {
t.Errorf("cpu info should be implemented on darwin systems")
}
require.NoErrorf(t, err, "cpu info should be implemented on darwin systems")
for _, vv := range v {
if vv.ModelName == "" {
t.Errorf("could not get CPU info: %v", vv)
}
assert.NotEmptyf(t, vv.ModelName, "could not get CPU info: %v", vv)
if vv.Mhz <= 0 && os.Getenv("CI") != "true" {
t.Errorf("could not get frequency of: %s", vv.ModelName)
}
if vv.Mhz > 6000 {
t.Errorf("cpu frequency is absurdly high value: %f MHz", vv.Mhz)
}
assert.LessOrEqualf(t, vv.Mhz, float64(6000), "cpu frequency is absurdly high value: %f MHz", vv.Mhz)
}
}

@ -6,6 +6,9 @@ import (
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -25,17 +28,9 @@ func TestParseDmesgBoot(t *testing.T) {
}
for _, tt := range cpuTests {
v, num, err := parseDmesgBoot(filepath.Join("testdata", "freebsd", tt.file))
if err != nil {
t.Errorf("parseDmesgBoot failed(%s), %v", tt.file, err)
}
if num != tt.cpuNum {
t.Errorf("parseDmesgBoot wrong length(%s), %v", tt.file, err)
}
if v.Cores != tt.cores {
t.Errorf("parseDmesgBoot wrong core(%s), %v", tt.file, err)
}
if !common.StringsContains(v.Flags, "fpu") {
t.Errorf("parseDmesgBoot fail to parse features(%s), %v", tt.file, err)
}
require.NoErrorf(t, err, "parseDmesgBoot failed(%s), %v", tt.file, err)
assert.Equalf(t, num, tt.cpuNum, "parseDmesgBoot wrong length(%s), %v", tt.file, err)
assert.Equalf(t, v.Cores, tt.cores, "parseDmesgBoot wrong core(%s), %v", tt.file, err)
assert.Truef(t, common.StringsContains(v.Flags, "fpu"), "parseDmesgBoot fail to parse features(%s), %v", tt.file, err)
}
}

@ -7,18 +7,17 @@ import (
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTimesEmpty(t *testing.T) {
t.Setenv("HOST_PROC", "testdata/linux/times_empty")
_, err := Times(true)
if err != nil {
t.Error("Times(true) failed")
}
require.NoErrorf(t, err, "Times(true) failed")
_, err = Times(false)
if err != nil {
t.Error("Times(false) failed")
}
assert.NoErrorf(t, err, "Times(false) failed")
}
func TestParseStatLine_424(t *testing.T) {
@ -78,31 +77,19 @@ func TestCountsAgainstLscpu(t *testing.T) {
expectedLogical := expectedPhysical * threadsPerCore
physical, err := Counts(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
logical, err := Counts(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if expectedPhysical != physical {
t.Errorf("expected %v, got %v", expectedPhysical, physical)
}
if expectedLogical != logical {
t.Errorf("expected %v, got %v", expectedLogical, logical)
}
require.NoError(t, err)
assert.Equalf(t, expectedPhysical, physical, "expected %v, got %v", expectedPhysical, physical)
assert.Equalf(t, expectedLogical, logical, "expected %v, got %v", expectedLogical, logical)
}
func TestCountsLogicalAndroid_1037(t *testing.T) { // https://github.com/shirou/gopsutil/issues/1037
t.Setenv("HOST_PROC", "testdata/linux/1037/proc")
count, err := Counts(true)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
expected := 8
if count != expected {
t.Errorf("expected %v, got %v", expected, count)
}
assert.Equalf(t, expected, count, "expected %v, got %v", expected, count)
}

@ -9,6 +9,8 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var timesTests = []struct {
@ -34,13 +36,9 @@ func TestTimesPlan9(t *testing.T) {
t.Setenv("HOST_ROOT", filepath.Join("testdata/plan9", tt.mockedRootFS))
stats, err := Times(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
eps := cmpopts.EquateApprox(0, 0.00000001)
if !cmp.Equal(stats, tt.stats, eps) {
t.Errorf("got: %+v\nwant: %+v", stats, tt.stats)
}
assert.Truef(t, cmp.Equal(stats, tt.stats, eps), "got: %+v\nwant: %+v", stats, tt.stats)
})
}
}

@ -7,6 +7,8 @@ import (
"reflect"
"sort"
"testing"
"github.com/stretchr/testify/require"
)
func TestParseISAInfo(t *testing.T) {
@ -51,20 +53,14 @@ func TestParseISAInfo(t *testing.T) {
for _, tc := range cases {
content, err := os.ReadFile(filepath.Join("testdata", "solaris", tc.filename))
if err != nil {
t.Errorf("cannot read test case: %s", err)
}
require.NoErrorf(t, err, "cannot read test case: %s", err)
sort.Strings(tc.expected)
flags, err := parseISAInfo(string(content))
if err != nil {
t.Fatalf("parseISAInfo: %s", err)
}
require.NoErrorf(t, err, "parseISAInfo: %s", err)
if !reflect.DeepEqual(tc.expected, flags) {
t.Fatalf("Bad flags\nExpected: %v\n Actual: %v", tc.expected, flags)
}
require.Truef(t, reflect.DeepEqual(tc.expected, flags), "Bad flags\nExpected: %v\n Actual: %v", tc.expected, flags)
}
}
@ -140,17 +136,11 @@ func TestParseProcessorInfo(t *testing.T) {
for _, tc := range cases {
content, err := os.ReadFile(filepath.Join("testdata", "solaris", tc.filename))
if err != nil {
t.Errorf("cannot read test case: %s", err)
}
require.NoErrorf(t, err, "cannot read test case: %s", err)
cpus, err := parseProcessorInfo(string(content))
if err != nil {
t.Errorf("cannot parse processor info: %s", err)
}
require.NoErrorf(t, err, "cannot parse processor info: %s", err)
if !reflect.DeepEqual(tc.expected, cpus) {
t.Fatalf("Bad Processor Info\nExpected: %v\n Actual: %v", tc.expected, cpus)
}
require.Truef(t, reflect.DeepEqual(tc.expected, cpus), "Bad Processor Info\nExpected: %v\n Actual: %v", tc.expected, cpus)
}
}

@ -10,6 +10,7 @@ import (
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -23,36 +24,22 @@ func skipIfNotImplementedErr(t *testing.T, err error) {
func TestTimes(t *testing.T) {
v, err := Times(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(v) == 0 {
t.Error("could not get CPUs ", err)
}
require.NoError(t, err)
assert.NotEmptyf(t, v, "could not get CPUs: %s", err)
empty := TimesStat{}
for _, vv := range v {
if vv == empty {
t.Errorf("could not get CPU User: %v", vv)
}
assert.NotEqualf(t, vv, empty, "could not get CPU User: %v", vv)
}
// test sum of per cpu stats is within margin of error for cpu total stats
cpuTotal, err := Times(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(cpuTotal) == 0 {
t.Error("could not get CPUs", err)
}
require.NoError(t, err)
assert.NotEmptyf(t, cpuTotal, "could not get CPUs: %s", err)
perCPU, err := Times(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(perCPU) == 0 {
t.Error("could not get CPUs", err)
}
require.NoError(t, err)
assert.NotEmptyf(t, perCPU, "could not get CPUs: %s", err)
var perCPUUserTimeSum float64
var perCPUSystemTimeSum float64
var perCPUIdleTimeSum float64
@ -81,21 +68,13 @@ func TestTimes(t *testing.T) {
func TestCounts(t *testing.T) {
v, err := Counts(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v == 0 {
t.Errorf("could not get logical CPU counts: %v", v)
}
require.NoError(t, err)
assert.NotZerof(t, v, "could not get logical CPU counts: %v", v)
t.Logf("logical cores: %d", v)
v, err = Counts(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v == 0 {
t.Errorf("could not get physical CPU counts: %v", v)
}
require.NoError(t, err)
assert.NotZerof(t, v, "could not get physical CPU counts: %v", v)
t.Logf("physical cores: %d", v)
}
@ -107,24 +86,16 @@ func TestTimeStat_String(t *testing.T) {
Idle: 300.1,
}
e := `{"cpu":"cpu0","user":100.1,"system":200.1,"idle":300.1,"nice":0.0,"iowait":0.0,"irq":0.0,"softirq":0.0,"steal":0.0,"guest":0.0,"guestNice":0.0}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("CPUTimesStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "CPUTimesStat string is invalid: %v", v)
}
func TestInfo(t *testing.T) {
v, err := Info()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(v) == 0 {
t.Errorf("could not get CPU Info")
}
require.NoError(t, err)
assert.NotEmptyf(t, v, "could not get CPU Info")
for _, vv := range v {
if vv.ModelName == "" {
t.Errorf("could not get CPU Info: %v", vv)
}
assert.NotEmptyf(t, vv.ModelName, "could not get CPU Info: %v", vv)
}
}
@ -136,9 +107,7 @@ func testPercent(t *testing.T, percpu bool) {
testCount = 100
v, err := Percent(time.Millisecond, percpu)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
// Skip CI which CPU num is different
if os.Getenv("CI") != "true" {
if (percpu && len(v) != numcpu) || (!percpu && len(v) != 1) {
@ -150,9 +119,7 @@ func testPercent(t *testing.T, percpu bool) {
duration := time.Duration(10) * time.Microsecond
v, err := Percent(duration, percpu)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
for _, percent := range v {
// Check for slightly greater then 100% to account for any rounding issues.
if percent < 0.0 || percent > 100.0001*float64(numcpu) {
@ -170,9 +137,7 @@ func testPercentLastUsed(t *testing.T, percpu bool) {
testCount = 2
v, err := Percent(time.Millisecond, percpu)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
// Skip CI which CPU num is different
if os.Getenv("CI") != "true" {
if (percpu && len(v) != numcpu) || (!percpu && len(v) != 1) {
@ -183,9 +148,7 @@ func testPercentLastUsed(t *testing.T, percpu bool) {
for i := 0; i < testCount; i++ {
v, err := Percent(0, percpu)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
time.Sleep(1 * time.Millisecond)
for _, percent := range v {
// Check for slightly greater then 100% to account for any rounding issues.

@ -8,6 +8,9 @@ import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -24,12 +27,8 @@ func TestUsage(t *testing.T) {
}
v, err := Usage(path)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v.Path != path {
t.Errorf("error %v", err)
}
require.NoError(t, err)
assert.Equalf(t, v.Path, path, "error %v", err)
}
func TestPartitions(t *testing.T) {
@ -40,31 +39,21 @@ func TestPartitions(t *testing.T) {
}
t.Log(ret)
if len(ret) == 0 {
t.Errorf("ret is empty")
}
assert.NotEmptyf(t, ret, "ret is empty")
for _, disk := range ret {
if disk.Device == "" {
t.Errorf("Could not get device info %v", disk)
}
assert.NotEmptyf(t, disk.Device, "Could not get device info %v", disk)
}
}
func TestIOCounters(t *testing.T) {
ret, err := IOCounters()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(ret) == 0 {
t.Errorf("ret is empty")
}
require.NoError(t, err)
assert.NotEmptyf(t, ret, "ret is empty")
empty := IOCountersStat{}
for part, io := range ret {
t.Log(part, io)
if io == empty {
t.Errorf("io_counter error %v, %v", part, io)
}
assert.NotEqualf(t, io, empty, "io_counter error %v, %v", part, io)
}
}
@ -99,9 +88,7 @@ func TestUsageStat_String(t *testing.T) {
Fstype: "ext4",
}
e := `{"path":"/","fstype":"ext4","total":1000,"free":2000,"used":3000,"usedPercent":50.1,"inodesTotal":4000,"inodesUsed":5000,"inodesFree":6000,"inodesUsedPercent":49.1}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("DiskUsageStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
}
func TestPartitionStat_String(t *testing.T) {
@ -112,9 +99,7 @@ func TestPartitionStat_String(t *testing.T) {
Opts: []string{"ro"},
}
e := `{"device":"sd01","mountpoint":"/","fstype":"ext4","opts":["ro"]}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("DiskUsageStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
}
func TestIOCountersStat_String(t *testing.T) {
@ -127,7 +112,5 @@ func TestIOCountersStat_String(t *testing.T) {
SerialNumber: "SERIAL",
}
e := `{"readCount":100,"mergedReadCount":0,"writeCount":200,"mergedWriteCount":0,"readBytes":300,"writeBytes":400,"readTime":0,"writeTime":0,"iopsInProgress":0,"ioTime":0,"weightedIO":0,"name":"sd01","serialNumber":"SERIAL","label":""}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("DiskUsageStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
}

@ -6,6 +6,9 @@ package docker
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetDockerIDList(t *testing.T) {
@ -47,40 +50,28 @@ func TestCgroupCPU(t *testing.T) {
v, _ := GetDockerIDList()
for _, id := range v {
v, err := CgroupCPUDockerWithContext(context.Background(), id)
if err != nil {
t.Errorf("error %v", err)
}
if v.CPU == "" {
t.Errorf("could not get CgroupCPU %v", v)
}
require.NoError(t, err)
assert.NotEmptyf(t, v.CPU, "could not get CgroupCPU %v", v)
}
}
func TestCgroupCPUInvalidId(t *testing.T) {
_, err := CgroupCPUDockerWithContext(context.Background(), "bad id")
if err == nil {
t.Error("Expected path does not exist error")
}
assert.Errorf(t, err, "Expected path does not exist error")
}
func TestCgroupMem(t *testing.T) {
v, _ := GetDockerIDList()
for _, id := range v {
v, err := CgroupMemDocker(id)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &CgroupMemStat{}
if v == empty {
t.Errorf("Could not CgroupMemStat %v", v)
}
assert.NotSamef(t, v, empty, "Could not CgroupMemStat %v", v)
}
}
func TestCgroupMemInvalidId(t *testing.T) {
_, err := CgroupMemDocker("bad id")
if err == nil {
t.Error("Expected path does not exist error")
}
assert.Errorf(t, err, "Expected path does not exist error")
}

@ -5,6 +5,8 @@ package host
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseUptimeValidInput(t *testing.T) {
@ -21,9 +23,7 @@ func TestParseUptimeValidInput(t *testing.T) {
}
for _, tc := range testCases {
got := parseUptime(tc.input)
if got != tc.expected {
t.Errorf("parseUptime(%q) = %v, want %v", tc.input, got, tc.expected)
}
assert.Equalf(t, tc.expected, got, "parseUptime(%q) = %v, want %v", tc.input, got, tc.expected)
}
}
@ -36,8 +36,6 @@ func TestParseUptimeInvalidInput(t *testing.T) {
for _, tc := range testCases {
got := parseUptime(tc)
if got > 0 {
t.Errorf("parseUptime(%q) expected zero to be returned, received %v", tc, got)
}
assert.LessOrEqualf(t, got, 0, "parseUptime(%q) expected zero to be returned, received %v", tc, got)
}
}

@ -7,6 +7,9 @@ import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/common"
)
@ -14,54 +17,38 @@ func TestGetRedhatishVersion(t *testing.T) {
var ret string
c := []string{"Rawhide"}
ret = getRedhatishVersion(c)
if ret != "rawhide" {
t.Errorf("Could not get version rawhide: %v", ret)
}
assert.Equalf(t, "rawhide", ret, "Could not get version rawhide: %v", ret)
c = []string{"Fedora release 15 (Lovelock)"}
ret = getRedhatishVersion(c)
if ret != "15" {
t.Errorf("Could not get version fedora: %v", ret)
}
assert.Equalf(t, "15", ret, "Could not get version fedora: %v", ret)
c = []string{"Enterprise Linux Server release 5.5 (Carthage)"}
ret = getRedhatishVersion(c)
if ret != "5.5" {
t.Errorf("Could not get version redhat enterprise: %v", ret)
}
assert.Equalf(t, "5.5", ret, "Could not get version redhat enterprise: %v", ret)
c = []string{""}
ret = getRedhatishVersion(c)
if ret != "" {
t.Errorf("Could not get version with no value: %v", ret)
}
assert.Emptyf(t, ret, "Could not get version with no value: %v", ret)
}
func TestGetRedhatishPlatform(t *testing.T) {
var ret string
c := []string{"red hat"}
ret = getRedhatishPlatform(c)
if ret != "redhat" {
t.Errorf("Could not get platform redhat: %v", ret)
}
assert.Equalf(t, "redhat", ret, "Could not get platform redhat: %v", ret)
c = []string{"Fedora release 15 (Lovelock)"}
ret = getRedhatishPlatform(c)
if ret != "fedora" {
t.Errorf("Could not get platform fedora: %v", ret)
}
assert.Equalf(t, "fedora", ret, "Could not get platform fedora: %v", ret)
c = []string{"Enterprise Linux Server release 5.5 (Carthage)"}
ret = getRedhatishPlatform(c)
if ret != "enterprise" {
t.Errorf("Could not get platform redhat enterprise: %v", ret)
}
assert.Equalf(t, "enterprise", ret, "Could not get platform redhat enterprise: %v", ret)
c = []string{""}
ret = getRedhatishPlatform(c)
if ret != "" {
t.Errorf("Could not get platform with no value: %v", ret)
}
assert.Emptyf(t, ret, "Could not get platform with no value: %v", ret)
}
func TestGetlsbStruct(t *testing.T) {
@ -85,21 +72,11 @@ func TestGetlsbStruct(t *testing.T) {
)
v, err := getlsbStruct(ctx)
if err != nil {
t.Errorf("error %v", err)
}
if v.ID != tt.id {
t.Errorf("ID: want %v, got %v", tt.id, v.ID)
}
if v.Release != tt.release {
t.Errorf("Release: want %v, got %v", tt.release, v.Release)
}
if v.Codename != tt.codename {
t.Errorf("Codename: want %v, got %v", tt.codename, v.Codename)
}
if v.Description != tt.description {
t.Errorf("Description: want %v, got %v", tt.description, v.Description)
}
require.NoError(t, err)
assert.Equalf(t, v.ID, tt.id, "ID: want %v, got %v", tt.id, v.ID)
assert.Equalf(t, v.Release, tt.release, "Release: want %v, got %v", tt.release, v.Release)
assert.Equalf(t, v.Codename, tt.codename, "Codename: want %v, got %v", tt.codename, v.Codename)
assert.Equalf(t, v.Description, tt.description, "Description: want %v, got %v", tt.description, v.Description)
t.Log(v)
})

@ -8,6 +8,9 @@ import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -20,28 +23,18 @@ func skipIfNotImplementedErr(t *testing.T, err error) {
func TestHostID(t *testing.T) {
v, err := HostID()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v == "" {
t.Errorf("Could not get host id %v", v)
}
require.NoError(t, err)
assert.NotEmptyf(t, v, "Could not get host id %v", v)
t.Log(v)
}
func TestInfo(t *testing.T) {
v, err := Info()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &InfoStat{}
if v == empty {
t.Errorf("Could not get hostinfo %v", v)
}
if v.Procs == 0 {
t.Errorf("Could not determine the number of host processes")
}
assert.NotSamef(t, v, empty, "Could not get hostinfo %v", v)
assert.NotZerof(t, v.Procs, "Could not determine the number of host processes")
t.Log(v)
}
@ -52,12 +45,8 @@ func TestUptime(t *testing.T) {
v, err := Uptime()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v == 0 {
t.Errorf("Could not get up time %v", v)
}
require.NoError(t, err)
assert.NotZerof(t, v, "Could not get up time %v", v)
}
func TestBootTime(t *testing.T) {
@ -66,42 +55,28 @@ func TestBootTime(t *testing.T) {
}
v, err := BootTime()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v == 0 {
t.Errorf("Could not get boot time %v", v)
}
if v < 946652400 {
t.Errorf("Invalid Boottime, older than 2000-01-01")
}
require.NoError(t, err)
assert.NotZerof(t, v, "Could not get boot time %v", v)
assert.GreaterOrEqualf(t, v, 946652400, "Invalid Boottime, older than 2000-01-01")
t.Logf("first boot time: %d", v)
v2, err := BootTime()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if v != v2 {
t.Errorf("cached boot time is different")
}
require.NoError(t, err)
assert.Equalf(t, v, v2, "cached boot time is different")
t.Logf("second boot time: %d", v2)
}
func TestUsers(t *testing.T) {
v, err := Users()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := UserStat{}
if len(v) == 0 {
t.Skip("Users is empty")
}
for _, u := range v {
if u == empty {
t.Errorf("Could not Users %v", v)
}
assert.NotEqualf(t, u, empty, "Could not Users %v", v)
t.Log(u)
}
}
@ -118,9 +93,7 @@ func TestInfoStat_String(t *testing.T) {
KernelArch: "x86_64",
}
e := `{"hostname":"test","uptime":3000,"bootTime":1447040000,"procs":100,"os":"linux","platform":"ubuntu","platformFamily":"","platformVersion":"","kernelVersion":"","kernelArch":"x86_64","virtualizationSystem":"","virtualizationRole":"","hostId":"edfd25ff-3c9c-b1a4-e660-bd826495ad35"}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("HostInfoStat string is invalid:\ngot %v\nwant %v", v, e)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "HostInfoStat string is invalid:\ngot %v\nwant %v", v, e)
}
func TestUserStat_String(t *testing.T) {
@ -131,23 +104,16 @@ func TestUserStat_String(t *testing.T) {
Started: 100,
}
e := `{"user":"user","terminal":"term","host":"host","started":100}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("UserStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "UserStat string is invalid: %v", v)
}
func TestGuid(t *testing.T) {
id, err := HostID()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Error(err)
}
if id == "" {
t.Error("Host id is empty")
} else {
require.NoError(t, err)
assert.NotEmptyf(t, id, "Host id is empty")
t.Logf("Host id value: %v", id)
}
}
func TestVirtualization(t *testing.T) {
wg := sync.WaitGroup{}
@ -158,9 +124,7 @@ func TestVirtualization(t *testing.T) {
system, role, err := Virtualization()
wg.Done()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("Virtualization() failed, %v", err)
}
assert.NoErrorf(t, err, "Virtualization() failed, %v", err)
if j == 9 {
t.Logf("Virtualization(): %s, %s", system, role)
@ -173,12 +137,8 @@ func TestVirtualization(t *testing.T) {
func TestKernelVersion(t *testing.T) {
version, err := KernelVersion()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("KernelVersion() failed, %v", err)
}
if version == "" {
t.Errorf("KernelVersion() returns empty: %s", version)
}
require.NoErrorf(t, err, "KernelVersion() failed, %v", err)
assert.NotEmptyf(t, version, "KernelVersion() returns empty: %s", version)
t.Logf("KernelVersion(): %s", version)
}
@ -186,12 +146,8 @@ func TestKernelVersion(t *testing.T) {
func TestPlatformInformation(t *testing.T) {
platform, family, version, err := PlatformInformation()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("PlatformInformation() failed, %v", err)
}
if platform == "" {
t.Errorf("PlatformInformation() returns empty: %v", platform)
}
require.NoErrorf(t, err, "PlatformInformation() failed, %v", err)
assert.NotEmptyf(t, platform, "PlatformInformation() returns empty: %v", platform)
t.Logf("PlatformInformation(): %v, %v, %v", platform, family, version)
}

@ -9,118 +9,71 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/common"
)
func TestReadlines(t *testing.T) {
ret, err := ReadLines("common_test.go")
if err != nil {
t.Error(err)
}
if !strings.Contains(ret[1], "package common") {
t.Error("could not read correctly")
}
require.NoError(t, err)
assert.Containsf(t, ret[1], "package common", "could not read correctly")
}
func TestReadLinesOffsetN(t *testing.T) {
ret, err := ReadLinesOffsetN("common_test.go", 3, 1)
if err != nil {
t.Error(err)
}
if !strings.Contains(ret[0], `import (`) {
t.Error("could not read correctly")
}
require.NoError(t, err)
assert.Containsf(t, ret[0], `import (`, "could not read correctly")
}
func TestIntToString(t *testing.T) {
src := []int8{65, 66, 67}
dst := IntToString(src)
if dst != "ABC" {
t.Error("could not convert")
}
assert.Equalf(t, "ABC", IntToString([]int8{65, 66, 67}), "could not convert")
}
func TestByteToString(t *testing.T) {
src := []byte{65, 66, 67}
dst := ByteToString(src)
if dst != "ABC" {
t.Error("could not convert")
}
assert.Equalf(t, "ABC", ByteToString([]byte{65, 66, 67}), "could not convert")
src = []byte{0, 65, 66, 67}
dst = ByteToString(src)
if dst != "ABC" {
t.Error("could not convert")
}
assert.Equalf(t, "ABC", ByteToString([]byte{0, 65, 66, 67}), "could not convert")
}
func TestHexToUint32(t *testing.T) {
if HexToUint32("FFFFFFFF") != 4294967295 {
t.Error("Could not convert")
}
assert.Equalf(t, uint32(4294967295), HexToUint32("FFFFFFFF"), "Could not convert")
}
func TestMustParseInt32(t *testing.T) {
ret := mustParseInt32("11111")
if ret != int32(11111) {
t.Error("could not parse")
}
assert.Equalf(t, int32(11111), mustParseInt32("11111"), "could not parse")
}
func TestMustParseUint64(t *testing.T) {
ret := mustParseUint64("11111")
if ret != uint64(11111) {
t.Error("could not parse")
}
assert.Equalf(t, uint64(11111), mustParseUint64("11111"), "could not parse")
}
func TestMustParseFloat64(t *testing.T) {
ret := mustParseFloat64("11111.11")
if ret != float64(11111.11) {
t.Error("could not parse")
}
ret = mustParseFloat64("11111")
if ret != float64(11111) {
t.Error("could not parse")
}
require.InDeltaf(t, float64(11111.11), mustParseFloat64("11111.11"), 0.01, "could not parse")
require.InDeltaf(t, float64(11111), mustParseFloat64("11111"), 0.01, "could not parse")
}
func TestStringsContains(t *testing.T) {
target, err := ReadLines("common_test.go")
if err != nil {
t.Error(err)
}
if !StringsContains(target, "func TestStringsContains(t *testing.T) {") {
t.Error("cloud not test correctly")
}
require.NoError(t, err)
assert.Truef(t, StringsContains(target, "func TestStringsContains(t *testing.T) {"), "cloud not test correctly")
}
func TestPathExists(t *testing.T) {
if !PathExists("common_test.go") {
t.Error("exists but return not exists")
}
if PathExists("should_not_exists.go") {
t.Error("not exists but return exists")
}
assert.Truef(t, PathExists("common_test.go"), "exists but return not exists")
assert.Falsef(t, PathExists("should_not_exists.go"), "not exists but return exists")
}
func TestPathExistsWithContents(t *testing.T) {
if !PathExistsWithContents("common_test.go") {
t.Error("exists but return not exists")
}
if PathExistsWithContents("should_not_exists.go") {
t.Error("not exists but return exists")
}
assert.Truef(t, PathExistsWithContents("common_test.go"), "exists but return not exists")
assert.Falsef(t, PathExistsWithContents("should_not_exists.go"), "not exists but return exists")
f, err := os.CreateTemp("", "empty_test.txt")
if err != nil {
t.Errorf("CreateTemp failed, %s", err)
}
require.NoErrorf(t, err, "CreateTemp failed, %s", err)
defer os.Remove(f.Name()) // clean up
if PathExistsWithContents(f.Name()) {
t.Error("exists but no content file return true")
}
assert.Falsef(t, PathExistsWithContents(f.Name()), "exists but no content file return true")
}
func TestHostEtc(t *testing.T) {
@ -128,23 +81,17 @@ func TestHostEtc(t *testing.T) {
t.Skip("windows doesn't have etc")
}
p := HostEtcWithContext(context.Background(), "mtab")
if p != "/etc/mtab" {
t.Errorf("invalid HostEtc, %s", p)
}
assert.Equalf(t, "/etc/mtab", p, "invalid HostEtc, %s", p)
}
func TestGetSysctrlEnv(t *testing.T) {
// Append case
env := getSysctrlEnv([]string{"FOO=bar"})
if !reflect.DeepEqual(env, []string{"FOO=bar", "LC_ALL=C"}) {
t.Errorf("unexpected append result from getSysctrlEnv: %q", env)
}
assert.Truef(t, reflect.DeepEqual(env, []string{"FOO=bar", "LC_ALL=C"}), "unexpected append result from getSysctrlEnv: %q", env)
// Replace case
env = getSysctrlEnv([]string{"FOO=bar", "LC_ALL=en_US.UTF-8"})
if !reflect.DeepEqual(env, []string{"FOO=bar", "LC_ALL=C"}) {
t.Errorf("unexpected replace result from getSysctrlEnv: %q", env)
}
assert.Truef(t, reflect.DeepEqual(env, []string{"FOO=bar", "LC_ALL=C"}), "unexpected replace result from getSysctrlEnv: %q", env)
// Test against real env
env = getSysctrlEnv(os.Environ())
@ -154,13 +101,9 @@ func TestGetSysctrlEnv(t *testing.T) {
found = true
continue
}
if strings.HasPrefix(v, "LC_ALL") {
t.Fatalf("unexpected LC_ALL value: %q", v)
}
}
if !found {
t.Errorf("unexpected real result from getSysctrlEnv: %q", env)
require.Falsef(t, strings.HasPrefix(v, "LC_ALL"), "unexpected LC_ALL value: %q", v)
}
assert.Truef(t, found, "unexpected real result from getSysctrlEnv: %q", env)
}
func TestGetEnvDefault(t *testing.T) {
@ -168,9 +111,7 @@ func TestGetEnvDefault(t *testing.T) {
t.Skip("windows doesn't have etc")
}
p := HostEtcWithContext(context.Background(), "mtab")
if p != "/etc/mtab" {
t.Errorf("invalid HostEtc, %s", p)
}
assert.Equalf(t, "/etc/mtab", p, "invalid HostEtc, %s", p)
}
func TestGetEnvWithNoContext(t *testing.T) {
@ -179,9 +120,7 @@ func TestGetEnvWithNoContext(t *testing.T) {
}
t.Setenv("HOST_ETC", "/bar")
p := HostEtcWithContext(context.Background(), "mtab")
if p != "/bar/mtab" {
t.Errorf("invalid HostEtc, %s", p)
}
assert.Equalf(t, "/bar/mtab", p, "invalid HostEtc, %s", p)
}
func TestGetEnvWithContextOverride(t *testing.T) {
@ -191,7 +130,5 @@ func TestGetEnvWithContextOverride(t *testing.T) {
t.Setenv("HOST_ETC", "/bar")
ctx := context.WithValue(context.Background(), common.EnvKey, common.EnvMap{common.HostEtcEnvKey: "/foo"})
p := HostEtcWithContext(ctx, "mtab")
if p != "/foo/mtab" {
t.Errorf("invalid HostEtc, %s", p)
}
assert.Equalf(t, "/foo/mtab", p, "invalid HostEtc, %s", p)
}

@ -6,6 +6,9 @@ import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -18,14 +21,10 @@ func skipIfNotImplementedErr(tb testing.TB, err error) {
func TestAvg(t *testing.T) {
v, err := Avg()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &AvgStat{}
if v == empty {
t.Errorf("error load: %v", v)
}
assert.NotSamef(t, v, empty, "error load: %v", v)
t.Log(v)
}
@ -36,23 +35,17 @@ func TestAvgStat_String(t *testing.T) {
Load15: 30.1,
}
e := `{"load1":10.1,"load5":20.1,"load15":30.1}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("LoadAvgStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "LoadAvgStat string is invalid: %v", v)
t.Log(e)
}
func TestMisc(t *testing.T) {
v, err := Misc()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &MiscStat{}
if v == empty {
t.Errorf("error load: %v", v)
}
assert.NotSamef(t, v, empty, "error load: %v", v)
t.Log(v)
}
@ -65,9 +58,7 @@ func TestMiscStatString(t *testing.T) {
Ctxt: 3,
}
e := `{"procsTotal":4,"procsCreated":5,"procsRunning":1,"procsBlocked":2,"ctxt":3}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("TestMiscString string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "TestMiscString string is invalid: %v", v)
t.Log(e)
}
@ -75,13 +66,9 @@ func BenchmarkLoad(b *testing.B) {
loadAvg := func(tb testing.TB) {
v, err := Avg()
skipIfNotImplementedErr(tb, err)
if err != nil {
tb.Errorf("error %v", err)
}
require.NoErrorf(tb, err, "error %v", err)
empty := &AvgStat{}
if v == empty {
tb.Errorf("error load: %v", v)
}
assert.NotSamef(tb, v, empty, "error load: %v", v)
}
b.Run("FirstCall", func(b *testing.B) {

@ -26,7 +26,7 @@ func TestVirtualMemoryDarwin(t *testing.T) {
assert.Equal(t, uint64(actualTotal), v.Total)
assert.Positive(t, v.Available)
assert.Equal(t, v.Available, v.Free+v.Inactive, "%v", v)
assert.Equalf(t, v.Available, v.Free+v.Inactive, "%v", v)
assert.Positive(t, v.Used)
assert.Less(t, v.Used, v.Total)

@ -18,9 +18,7 @@ func TestExVirtualMemory(t *testing.T) {
ex := NewExLinux()
v, err := ex.VirtualMemory()
if err != nil {
t.Error(err)
}
require.NoError(t, err)
t.Log(v)
}
@ -130,12 +128,8 @@ func TestVirtualMemoryLinux(t *testing.T) {
stat, err := VirtualMemory()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if !reflect.DeepEqual(stat, tt.stat) {
t.Errorf("got: %+v\nwant: %+v", stat, tt.stat)
}
require.NoError(t, err)
assert.Truef(t, reflect.DeepEqual(stat, tt.stat), "got: %+v\nwant: %+v", stat, tt.stat)
})
}
}

@ -6,6 +6,9 @@ package mem
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var virtualMemoryTests = []struct {
@ -32,12 +35,8 @@ func TestVirtualMemoryPlan9(t *testing.T) {
stat, err := VirtualMemory()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if !reflect.DeepEqual(stat, tt.stat) {
t.Errorf("got: %+v\nwant: %+v", stat, tt.stat)
}
require.NoError(t, err)
assert.Truef(t, reflect.DeepEqual(stat, tt.stat), "got: %+v\nwant: %+v", stat, tt.stat)
})
}
}
@ -62,12 +61,8 @@ func TestSwapMemoryPlan9(t *testing.T) {
swap, err := SwapMemory()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if !reflect.DeepEqual(swap, tt.swap) {
t.Errorf("got: %+v\nwant: %+v", swap, tt.swap)
}
require.NoError(t, err)
assert.Truef(t, reflect.DeepEqual(swap, tt.swap), "got: %+v\nwant: %+v", swap, tt.swap)
})
}
}

@ -8,6 +8,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -25,13 +26,9 @@ func TestVirtualMemory(t *testing.T) {
v, err := VirtualMemory()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &VirtualMemoryStat{}
if v == empty {
t.Errorf("error %v", v)
}
assert.NotSamef(t, v, empty, "error %v", v)
t.Log(v)
assert.Positive(t, v.Total)
@ -51,11 +48,11 @@ func TestVirtualMemory(t *testing.T) {
total = v.Used + v.Free + v.Cached + v.Inactive + v.Laundry
totalStr = "used + free + cached + inactive + laundry"
}
assert.Equal(t, v.Total, total,
assert.Equalf(t, v.Total, total,
"Total should be computable (%v): %v", totalStr, v)
assert.True(t, runtime.GOOS == "windows" || v.Free > 0)
assert.True(t, runtime.GOOS == "windows" || v.Available > v.Free,
assert.Truef(t, runtime.GOOS == "windows" || v.Available > v.Free,
"Free should be a subset of Available: %v", v)
inDelta := assert.InDelta
@ -70,13 +67,9 @@ func TestVirtualMemory(t *testing.T) {
func TestSwapMemory(t *testing.T) {
v, err := SwapMemory()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &SwapMemoryStat{}
if v == empty {
t.Errorf("error %v", v)
}
assert.NotSamef(t, v, empty, "error %v", v)
t.Log(v)
}
@ -91,9 +84,7 @@ func TestVirtualMemoryStat_String(t *testing.T) {
}
t.Log(v)
e := `{"total":10,"available":20,"used":30,"usedPercent":30.1,"free":40,"active":0,"inactive":0,"wired":0,"laundry":0,"buffers":0,"cached":0,"writeBack":0,"dirty":0,"writeBackTmp":0,"shared":0,"slab":0,"sreclaimable":0,"sunreclaim":0,"pageTables":0,"swapCached":0,"commitLimit":0,"committedAS":0,"highTotal":0,"highFree":0,"lowTotal":0,"lowFree":0,"swapTotal":0,"swapFree":0,"mapped":0,"vmallocTotal":0,"vmallocUsed":0,"vmallocChunk":0,"hugePagesTotal":0,"hugePagesFree":0,"hugePagesRsvd":0,"hugePagesSurp":0,"hugePageSize":0,"anonHugePages":0}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("VirtualMemoryStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "VirtualMemoryStat string is invalid: %v", v)
}
func TestSwapMemoryStat_String(t *testing.T) {
@ -110,28 +101,20 @@ func TestSwapMemoryStat_String(t *testing.T) {
PgMajFault: 6,
}
e := `{"total":10,"used":30,"free":40,"usedPercent":30.1,"sin":1,"sout":2,"pgIn":3,"pgOut":4,"pgFault":5,"pgMajFault":6}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("SwapMemoryStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "SwapMemoryStat string is invalid: %v", v)
}
func TestSwapDevices(t *testing.T) {
v, err := SwapDevices()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("error calling SwapDevices: %v", err)
}
require.NoErrorf(t, err, "error calling SwapDevices: %v", err)
t.Logf("SwapDevices() -> %+v", v)
if len(v) == 0 {
t.Fatalf("no swap devices found. [this is expected if the host has swap disabled]")
}
require.NotEmptyf(t, v, "no swap devices found. [this is expected if the host has swap disabled]")
for _, device := range v {
if device.Name == "" {
t.Fatalf("deviceName not set in %+v", device)
}
require.NotEmptyf(t, device.Name, "deviceName not set in %+v", device)
if device.FreeBytes == 0 {
t.Logf("[WARNING] free-bytes is zero in %+v. This might be expected", device)
}

@ -79,7 +79,7 @@ func TestParseNetstatOutput(t *testing.T) {
assert.NoError(t, err)
assert.Len(t, nsInterfaces, 8)
for index := range nsInterfaces {
assert.NotNil(t, nsInterfaces[index].stat, "Index %d", index)
assert.NotNilf(t, nsInterfaces[index].stat, "Index %d", index)
}
assert.NotNil(t, nsInterfaces[0].linkID)
@ -110,7 +110,7 @@ func TestParseNetstatTruncated(t *testing.T) {
assert.NoError(t, err)
assert.Len(t, nsInterfaces, 11)
for index := range nsInterfaces {
assert.NotNil(t, nsInterfaces[index].stat, "Index %d", index)
assert.NotNilf(t, nsInterfaces[index].stat, "Index %d", index)
}
const truncatedIface = "utun8"
@ -137,5 +137,5 @@ func TestParseNetstatTruncated(t *testing.T) {
mapUsage := newMapInterfaceNameUsage(nsInterfaces)
assert.True(t, mapUsage.isTruncated())
assert.Len(t, mapUsage.notTruncated(), 3, "en0, gif0 and stf0")
assert.Lenf(t, mapUsage.notTruncated(), 3, "en0, gif0 and stf0")
}

@ -21,7 +21,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
tmpfile, err := os.CreateTemp("", "proc_dev_net")
defer os.Remove(tmpfile.Name()) // clean up
require.NoError(t, err, "Temporary file creation failed: ", err)
require.NoErrorf(t, err, "Temporary file creation failed: %s", err)
cases := [4][2]string{
{"eth0: ", "eth1: "},
@ -31,7 +31,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
}
for _, testCase := range cases {
err = tmpfile.Truncate(0)
require.NoError(t, err, "Temporary file truncating problem: ", err)
require.NoErrorf(t, err, "Temporary file truncating problem: %s", err)
// Parse interface name for assertion
interface0 := strings.TrimSpace(testCase[0])
@ -45,7 +45,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
// Write /proc/net/dev sample output
_, err = tmpfile.Write(proc)
require.NoError(t, err, "Temporary file writing failed: ", err)
require.NoErrorf(t, err, "Temporary file writing failed: %s", err)
counters, err := IOCountersByFile(true, tmpfile.Name())
@ -76,8 +76,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
assert.Equal(t, uint64(1300), counters[1].Fifoout)
}
err = tmpfile.Close()
assert.NoError(t, err, "Temporary file closing failed: ", err)
assert.NoErrorf(t, tmpfile.Close(), "Temporary file closing failed")
}
func TestGetProcInodesAll(t *testing.T) {
@ -180,11 +179,11 @@ func TestDecodeAddress(t *testing.T) {
}
addr, err := decodeAddress(uint32(family), src)
if dst.Error {
assert.Error(t, err, src)
assert.Errorf(t, err, src)
} else {
require.NoError(t, err, src)
assert.Equal(t, dst.IP, addr.IP, src)
assert.Equal(t, dst.Port, int(addr.Port), src)
require.NoErrorf(t, err, src)
assert.Equalf(t, dst.IP, addr.IP, src)
assert.Equalf(t, dst.Port, int(addr.Port), src)
}
}
}
@ -197,7 +196,7 @@ func TestReverse(t *testing.T) {
func TestConntrackStatFileParsing(t *testing.T) {
tmpfile, err := os.CreateTemp("", "proc_net_stat_conntrack")
defer os.Remove(tmpfile.Name())
require.NoError(t, err, "Temporary file creation failed: ", err)
require.NoErrorf(t, err, "Temporary file creation failed: %s", err)
data := []byte(`
entries searched found new invalid ignore delete deleteList insert insertFailed drop earlyDrop icmpError expectNew expectCreate expectDelete searchRestart
@ -246,12 +245,12 @@ entries searched found new invalid ignore delete deleteList insert insertFailed
// Write data to tempfile
_, err = tmpfile.Write(data)
require.NoError(t, err, "Temporary file writing failed: ", err)
require.NoErrorf(t, err, "Temporary file writing failed: %s", err)
// Function under test
stats, err := conntrackStatsFromFile(tmpfile.Name(), true)
require.NoError(t, err)
assert.Len(t, stats, 8, "Expected 8 results")
assert.Lenf(t, stats, 8, "Expected 8 results")
summary := &ConntrackStat{}
for i, exp := range slist.Items() {

@ -8,6 +8,9 @@ import (
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -21,9 +24,7 @@ func TestAddrString(t *testing.T) {
v := Addr{IP: "192.168.0.1", Port: 8000}
s := fmt.Sprintf("%v", v)
if s != `{"ip":"192.168.0.1","port":8000}` {
t.Errorf("Addr string is invalid: %v", v)
}
assert.JSONEqf(t, `{"ip":"192.168.0.1","port":8000}`, s, "Addr string is invalid: %v", v)
}
func TestIOCountersStatString(t *testing.T) {
@ -32,9 +33,7 @@ func TestIOCountersStatString(t *testing.T) {
BytesSent: 100,
}
e := `{"name":"test","bytesSent":100,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("NetIOCountersStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetIOCountersStat string is invalid: %v", v)
}
func TestProtoCountersStatString(t *testing.T) {
@ -47,9 +46,7 @@ func TestProtoCountersStatString(t *testing.T) {
},
}
e := `{"protocol":"tcp","stats":{"ActiveOpens":4000,"MaxConn":-1,"PassiveOpens":3000}}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("NetProtoCountersStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetProtoCountersStat string is invalid: %v", v)
}
func TestConnectionStatString(t *testing.T) {
@ -60,28 +57,18 @@ func TestConnectionStatString(t *testing.T) {
Uids: []int32{10, 10},
}
e := `{"fd":10,"family":10,"type":10,"localaddr":{"ip":"","port":0},"remoteaddr":{"ip":"","port":0},"status":"","uids":[10,10],"pid":0}`
if e != fmt.Sprintf("%v", v) {
t.Errorf("NetConnectionStat string is invalid: %v", v)
}
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetConnectionStat string is invalid: %v", v)
}
func TestIOCountersAll(t *testing.T) {
v, err := IOCounters(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("Could not get NetIOCounters: %v", err)
}
require.NoErrorf(t, err, "Could not get NetIOCounters: %v", err)
per, err := IOCounters(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("Could not get NetIOCounters: %v", err)
}
if len(v) != 1 {
t.Errorf("Could not get NetIOCounters: %v", v)
}
if v[0].Name != "all" {
t.Errorf("Invalid NetIOCounters: %v", v)
}
require.NoErrorf(t, err, "Could not get NetIOCounters: %v", err)
assert.Lenf(t, v, 1, "Could not get NetIOCounters: %v", v)
assert.Equalf(t, "all", v[0].Name, "Invalid NetIOCounters: %v", v)
var pr uint64
for _, p := range per {
pr += p.PacketsRecv
@ -106,16 +93,10 @@ func TestIOCountersAll(t *testing.T) {
func TestIOCountersPerNic(t *testing.T) {
v, err := IOCounters(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("Could not get NetIOCounters: %v", err)
}
if len(v) == 0 {
t.Errorf("Could not get NetIOCounters: %v", v)
}
require.NoErrorf(t, err, "Could not get NetIOCounters: %v", err)
assert.NotEmptyf(t, v, "Could not get NetIOCounters: %v", v)
for _, vv := range v {
if vv.Name == "" {
t.Errorf("Invalid NetIOCounters: %v", vv)
}
assert.NotEmptyf(t, vv.Name, "Invalid NetIOCounters: %v", vv)
}
}
@ -134,74 +115,44 @@ func TestGetNetIOCountersAll(t *testing.T) {
},
}
ret := getIOCountersAll(n)
if len(ret) != 1 {
t.Errorf("invalid return count")
}
if ret[0].Name != "all" {
t.Errorf("invalid return name")
}
if ret[0].BytesRecv != 20 {
t.Errorf("invalid count bytesrecv")
}
if ret[0].Errin != 10 {
t.Errorf("invalid count errin")
}
assert.Lenf(t, ret, 1, "invalid return count")
assert.Equalf(t, "all", ret[0].Name, "invalid return name")
assert.Equalf(t, uint64(20), ret[0].BytesRecv, "invalid count bytesrecv")
assert.Equalf(t, uint64(10), ret[0].Errin, "invalid count errin")
}
func TestInterfaces(t *testing.T) {
v, err := Interfaces()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("Could not get NetInterfaceStat: %v", err)
}
if len(v) == 0 {
t.Errorf("Could not get NetInterfaceStat: %v", err)
}
require.NoErrorf(t, err, "Could not get NetInterfaceStat: %v", err)
assert.NotEmptyf(t, v, "Could not get NetInterfaceStat: %v", err)
for _, vv := range v {
if vv.Name == "" {
t.Errorf("Invalid NetInterface: %v", vv)
}
assert.NotEmptyf(t, vv.Name, "Invalid NetInterface: %v", vv)
}
}
func TestProtoCountersStatsAll(t *testing.T) {
v, err := ProtoCounters(nil)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("Could not get NetProtoCounters: %v", err)
}
if len(v) == 0 {
t.Fatalf("Could not get NetProtoCounters: %v", err)
}
require.NoErrorf(t, err, "Could not get NetProtoCounters: %v", err)
require.NotEmptyf(t, v, "Could not get NetProtoCounters: %v", err)
for _, vv := range v {
if vv.Protocol == "" {
t.Errorf("Invalid NetProtoCountersStat: %v", vv)
}
if len(vv.Stats) == 0 {
t.Errorf("Invalid NetProtoCountersStat: %v", vv)
}
assert.NotEmptyf(t, vv.Protocol, "Invalid NetProtoCountersStat: %v", vv)
assert.NotEmptyf(t, vv.Stats, "Invalid NetProtoCountersStat: %v", vv)
}
}
func TestProtoCountersStats(t *testing.T) {
v, err := ProtoCounters([]string{"tcp", "ip"})
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("Could not get NetProtoCounters: %v", err)
}
if len(v) == 0 {
t.Fatalf("Could not get NetProtoCounters: %v", err)
}
if len(v) != 2 {
t.Fatalf("Go incorrect number of NetProtoCounters: %v", err)
}
require.NoErrorf(t, err, "Could not get NetProtoCounters: %v", err)
require.NotEmptyf(t, v, "Could not get NetProtoCounters: %v", err)
require.Lenf(t, v, 2, "Go incorrect number of NetProtoCounters: %v", err)
for _, vv := range v {
if vv.Protocol != "tcp" && vv.Protocol != "ip" {
t.Errorf("Invalid NetProtoCountersStat: %v", vv)
}
if len(vv.Stats) == 0 {
t.Errorf("Invalid NetProtoCountersStat: %v", vv)
}
assert.NotEmptyf(t, vv.Stats, "Invalid NetProtoCountersStat: %v", vv)
}
}
@ -212,16 +163,10 @@ func TestConnections(t *testing.T) {
v, err := Connections("inet")
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("could not get NetConnections: %v", err)
}
if len(v) == 0 {
t.Errorf("could not get NetConnections: %v", v)
}
require.NoErrorf(t, err, "could not get NetConnections: %v", err)
assert.NotEmptyf(t, v, "could not get NetConnections: %v", v)
for _, vv := range v {
if vv.Family == 0 {
t.Errorf("invalid NetConnections: %v", vv)
}
assert.NotZerof(t, vv.Family, "invalid NetConnections: %v", vv)
}
}
@ -239,16 +184,10 @@ func TestFilterCounters(t *testing.T) {
v, err := FilterCounters()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("could not get NetConnections: %v", err)
}
if len(v) == 0 {
t.Errorf("could not get NetConnections: %v", v)
}
require.NoErrorf(t, err, "could not get NetConnections: %v", err)
assert.NotEmptyf(t, v, "could not get NetConnections: %v", v)
for _, vv := range v {
if vv.ConnTrackMax == 0 {
t.Errorf("nf_connTrackMax needs to be greater than zero: %v", vv)
}
assert.NotZerof(t, vv.ConnTrackMax, "nf_connTrackMax needs to be greater than zero: %v", vv)
}
}
@ -263,13 +202,9 @@ func TestInterfaceStatString(t *testing.T) {
}
s := fmt.Sprintf("%v", v)
if s != `{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]}` {
t.Errorf("InterfaceStat string is invalid: %v", s)
}
assert.JSONEqf(t, `{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]}`, s, "InterfaceStat string is invalid: %v", s)
list := InterfaceStatList{v, v}
s = fmt.Sprintf("%v", list)
if s != `[{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]},{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]}]` {
t.Errorf("InterfaceStatList string is invalid: %v", s)
}
assert.JSONEqf(t, `[{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]},{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]}]`, s, "InterfaceStatList string is invalid: %v", s)
}

@ -47,7 +47,7 @@ func TestSplitProcStat(t *testing.T) {
for _, idx := range consideredFields {
expected := strconv.Itoa(idx)
parsed := parsedStatLine[idx]
assert.Equal(
assert.Equalf(
t, expected, parsed,
"field %d (index from 1 as in man proc) must be %q but %q is received",
idx, expected, parsed,
@ -59,9 +59,7 @@ func TestSplitProcStat(t *testing.T) {
func TestSplitProcStat_fromFile(t *testing.T) {
pids, err := os.ReadDir("testdata/linux/")
if err != nil {
t.Error(err)
}
require.NoError(t, err)
t.Setenv("HOST_PROC", "testdata/linux")
for _, pid := range pids {
pid, err := strconv.ParseInt(pid.Name(), 0, 32)
@ -95,9 +93,7 @@ func TestSplitProcStat_fromFile(t *testing.T) {
func TestFillFromCommWithContext(t *testing.T) {
pids, err := os.ReadDir("testdata/linux/")
if err != nil {
t.Error(err)
}
require.NoError(t, err)
t.Setenv("HOST_PROC", "testdata/linux")
for _, pid := range pids {
pid, err := strconv.ParseInt(pid.Name(), 0, 32)
@ -108,17 +104,13 @@ func TestFillFromCommWithContext(t *testing.T) {
continue
}
p, _ := NewProcess(int32(pid))
if err := p.fillFromCommWithContext(context.Background()); err != nil {
t.Error(err)
}
assert.NoError(t, p.fillFromCommWithContext(context.Background()))
}
}
func TestFillFromStatusWithContext(t *testing.T) {
pids, err := os.ReadDir("testdata/linux/")
if err != nil {
t.Error(err)
}
require.NoError(t, err)
t.Setenv("HOST_PROC", "testdata/linux")
for _, pid := range pids {
pid, err := strconv.ParseInt(pid.Name(), 0, 32)
@ -129,9 +121,7 @@ func TestFillFromStatusWithContext(t *testing.T) {
continue
}
p, _ := NewProcess(int32(pid))
if err := p.fillFromStatus(); err != nil {
t.Error(err)
}
assert.NoError(t, p.fillFromStatus())
}
}
@ -155,9 +145,7 @@ func Benchmark_fillFromStatusWithContext(b *testing.B) {
func TestFillFromTIDStatWithContext_lx_brandz(t *testing.T) {
pids, err := os.ReadDir("testdata/lx_brandz/")
if err != nil {
t.Error(err)
}
require.NoError(t, err)
t.Setenv("HOST_PROC", "testdata/lx_brandz")
for _, pid := range pids {
pid, err := strconv.ParseInt(pid.Name(), 0, 32)
@ -169,9 +157,7 @@ func TestFillFromTIDStatWithContext_lx_brandz(t *testing.T) {
}
p, _ := NewProcess(int32(pid))
_, _, cpuTimes, _, _, _, _, err := p.fillFromTIDStat(-1)
if err != nil {
t.Error(err)
}
require.NoError(t, err)
assert.Zero(t, cpuTimes.Iowait)
}
}

@ -7,6 +7,7 @@ import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"golang.org/x/sys/unix"
)
@ -14,8 +15,5 @@ func Test_SendSignal(t *testing.T) {
checkPid := os.Getpid()
p, _ := NewProcess(int32(checkPid))
err := p.SendSignal(unix.SIGCONT)
if err != nil {
t.Errorf("send signal %v", err)
}
assert.NoErrorf(t, p.SendSignal(unix.SIGCONT), "send signal")
}

@ -6,6 +6,8 @@ package process
import (
"sync"
"testing"
"github.com/stretchr/testify/require"
)
func TestPpid_Race(t *testing.T) {
@ -18,9 +20,7 @@ func TestPpid_Race(t *testing.T) {
ppid, err := p.Ppid()
wg.Done()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("Ppid() failed, %v", err)
}
require.NoError(t, err, "Ppid() failed, %v", err)
if j == 9 {
t.Logf("Ppid(): %d", ppid)

@ -42,12 +42,8 @@ func testGetProcess() Process {
func TestPids(t *testing.T) {
ret, err := Pids()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(ret) == 0 {
t.Errorf("could not get pids %v", ret)
}
require.NoError(t, err)
assert.NotEmptyf(t, ret, "could not get pids %v", ret)
}
func TestPid_exists(t *testing.T) {
@ -55,13 +51,9 @@ func TestPid_exists(t *testing.T) {
ret, err := PidExists(int32(checkPid))
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
if !ret {
t.Errorf("could not get process exists: %v", ret)
}
assert.Truef(t, ret, "could not get process exists: %v", ret)
}
func TestNewProcess(t *testing.T) {
@ -69,14 +61,10 @@ func TestNewProcess(t *testing.T) {
ret, err := NewProcess(int32(checkPid))
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
empty := &Process{}
if runtime.GOOS != "windows" { // Windows pid is 0
if empty == ret {
t.Errorf("error %v", ret)
}
assert.NotSamef(t, empty, ret, "error %v", ret)
}
}
@ -85,35 +73,23 @@ func TestMemoryMaps(t *testing.T) {
ret, err := NewProcess(int32(checkPid))
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
// ungrouped memory maps
mmaps, err := ret.MemoryMaps(false)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("memory map get error %v", err)
}
require.NoErrorf(t, err, "memory map get error %v", err)
empty := MemoryMapsStat{}
for _, m := range *mmaps {
if m == empty {
t.Errorf("memory map get error %v", m)
}
assert.NotEqualf(t, m, empty, "memory map get error %v", m)
}
// grouped memory maps
mmaps, err = ret.MemoryMaps(true)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("memory map get error %v", err)
}
if len(*mmaps) != 1 {
t.Errorf("grouped memory maps length (%v) is not equal to 1", len(*mmaps))
}
if (*mmaps)[0] == empty {
t.Errorf("memory map is empty")
}
require.NoErrorf(t, err, "memory map get error %v", err)
assert.Lenf(t, *mmaps, 1, "grouped memory maps length (%v) is not equal to 1", len(*mmaps))
assert.NotEqualf(t, (*mmaps)[0], empty, "memory map is empty")
}
func TestMemoryInfo(t *testing.T) {
@ -121,9 +97,7 @@ func TestMemoryInfo(t *testing.T) {
v, err := p.MemoryInfo()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting memory info error %v", err)
}
require.NoErrorf(t, err, "getting memory info error %v", err)
empty := MemoryInfoStat{}
if v == nil || *v == empty {
t.Errorf("could not get memory info %v", v)
@ -135,12 +109,8 @@ func TestCmdLine(t *testing.T) {
v, err := p.Cmdline()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting cmdline error %v", err)
}
if !strings.Contains(v, "process.test") {
t.Errorf("invalid cmd line %v", v)
}
require.NoErrorf(t, err, "getting cmdline error %v", err)
assert.Containsf(t, v, "process.test", "invalid cmd line %v", v)
}
func TestCmdLineSlice(t *testing.T) {
@ -148,12 +118,8 @@ func TestCmdLineSlice(t *testing.T) {
v, err := p.CmdlineSlice()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("getting cmdline slice error %v", err)
}
if !reflect.DeepEqual(v, os.Args) {
t.Errorf("returned cmdline slice not as expected:\nexp: %v\ngot: %v", os.Args, v)
}
require.NoErrorf(t, err, "getting cmdline slice error %v", err)
assert.Truef(t, reflect.DeepEqual(v, os.Args), "returned cmdline slice not as expected:\nexp: %v\ngot: %v", os.Args, v)
}
func TestPpid(t *testing.T) {
@ -161,16 +127,10 @@ func TestPpid(t *testing.T) {
v, err := p.Ppid()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting ppid error %v", err)
}
if v == 0 {
t.Errorf("return value is 0 %v", v)
}
require.NoErrorf(t, err, "getting ppid error %v", err)
assert.NotZerof(t, v, "return value is 0 %v", v)
expected := os.Getppid()
if v != int32(expected) {
t.Errorf("return value is %v, expected %v", v, expected)
}
assert.Equalf(t, int32(expected), v, "return value is %v, expected %v", v, expected)
}
func TestStatus(t *testing.T) {
@ -178,12 +138,8 @@ func TestStatus(t *testing.T) {
v, err := p.Status()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting status error %v", err)
}
if len(v) == 0 {
t.Errorf("could not get state")
}
require.NoErrorf(t, err, "getting status error %v", err)
assert.NotEmptyf(t, v, "could not get state")
if v[0] != Running && v[0] != Sleep {
t.Errorf("got wrong state, %v", v)
}
@ -194,9 +150,7 @@ func TestTerminal(t *testing.T) {
_, err := p.Terminal()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting terminal error %v", err)
}
assert.NoErrorf(t, err, "getting terminal error %v", err)
}
func TestIOCounters(t *testing.T) {
@ -204,14 +158,9 @@ func TestIOCounters(t *testing.T) {
v, err := p.IOCounters()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting iocounter error %v", err)
return
}
require.NoErrorf(t, err, "getting iocounter error %v", err)
empty := &IOCountersStat{}
if v == empty {
t.Errorf("error %v", v)
}
assert.NotSamef(t, v, empty, "error %v", v)
}
func TestNumCtx(t *testing.T) {
@ -219,10 +168,7 @@ func TestNumCtx(t *testing.T) {
_, err := p.NumCtxSwitches()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting numctx error %v", err)
return
}
assert.NoErrorf(t, err, "getting numctx error %v", err)
}
func TestNice(t *testing.T) {
@ -235,9 +181,7 @@ func TestNice(t *testing.T) {
n, err := p.Nice()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting nice error %v", err)
}
require.NoErrorf(t, err, "getting nice error %v", err)
if runtime.GOOS != "windows" && n != 0 && n != 20 && n != 8 {
t.Errorf("invalid nice: %d", n)
}
@ -248,15 +192,10 @@ func TestGroups(t *testing.T) {
v, err := p.Groups()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting groups error %v", err)
}
require.NoErrorf(t, err, "getting groups error %v", err)
if len(v) == 0 {
t.Skip("Groups is empty")
}
if v[0] < 0 {
t.Errorf("invalid Groups: %v", v)
}
}
func TestNumThread(t *testing.T) {
@ -264,12 +203,8 @@ func TestNumThread(t *testing.T) {
n, err := p.NumThreads()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting NumThread error %v", err)
}
if n < 0 {
t.Errorf("invalid NumThread: %d", n)
}
require.NoErrorf(t, err, "getting NumThread error %v", err)
assert.GreaterOrEqualf(t, n, int32(0), "invalid NumThread: %d", n)
}
func TestThreads(t *testing.T) {
@ -277,21 +212,13 @@ func TestThreads(t *testing.T) {
n, err := p.NumThreads()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting NumThread error %v", err)
}
if n < 0 {
t.Errorf("invalid NumThread: %d", n)
}
require.NoErrorf(t, err, "getting NumThread error %v", err)
assert.GreaterOrEqualf(t, n, int32(0), "invalid NumThread: %d", n)
ts, err := p.Threads()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting Threads error %v", err)
}
if len(ts) != int(n) {
t.Errorf("unexpected number of threads: %v vs %v", len(ts), n)
}
require.NoErrorf(t, err, "getting Threads error %v", err)
assert.Equalf(t, len(ts), int(n), "unexpected number of threads: %v vs %v", len(ts), n)
}
func TestName(t *testing.T) {
@ -299,40 +226,28 @@ func TestName(t *testing.T) {
n, err := p.Name()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting name error %v", err)
}
if !strings.Contains(n, "process.test") {
t.Errorf("invalid Name %s", n)
}
require.NoErrorf(t, err, "getting name error %v", err)
assert.Containsf(t, n, "process.test", "invalid Name %s", n)
}
// #nosec G204
func TestLong_Name_With_Spaces(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("unable to create temp dir %v", err)
}
require.NoErrorf(t, err, "unable to create temp dir %v", err)
defer os.RemoveAll(tmpdir) // clean up
tmpfilepath := filepath.Join(tmpdir, "loooong name with spaces.go")
tmpfile, err := os.Create(tmpfilepath)
if err != nil {
t.Fatalf("unable to create temp file %v", err)
}
require.NoErrorf(t, err, "unable to create temp file %v", err)
tmpfilecontent := []byte("package main\nimport(\n\"time\"\n)\nfunc main(){\nfor range time.Tick(time.Second) {}\n}")
if _, err := tmpfile.Write(tmpfilecontent); err != nil {
tmpfile.Close()
t.Fatalf("unable to write temp file %v", err)
}
if err := tmpfile.Close(); err != nil {
t.Fatalf("unable to close temp file %v", err)
}
require.NoErrorf(t, tmpfile.Close(), "unable to close temp file")
err = exec.Command("go", "build", "-o", tmpfile.Name()+".exe", tmpfile.Name()).Run()
if err != nil {
t.Fatalf("unable to build temp file %v", err)
}
require.NoErrorf(t, err, "unable to build temp file %v", err)
cmd := exec.Command(tmpfile.Name() + ".exe")
@ -344,42 +259,30 @@ func TestLong_Name_With_Spaces(t *testing.T) {
n, err := p.Name()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("getting name error %v", err)
}
require.NoErrorf(t, err, "getting name error %v", err)
basename := filepath.Base(tmpfile.Name() + ".exe")
if basename != n {
t.Fatalf("%s != %s", basename, n)
}
require.Equalf(t, basename, n, "%s != %s", basename, n)
cmd.Process.Kill()
}
// #nosec G204
func TestLong_Name(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("unable to create temp dir %v", err)
}
require.NoErrorf(t, err, "unable to create temp dir %v", err)
defer os.RemoveAll(tmpdir) // clean up
tmpfilepath := filepath.Join(tmpdir, "looooooooooooooooooooong.go")
tmpfile, err := os.Create(tmpfilepath)
if err != nil {
t.Fatalf("unable to create temp file %v", err)
}
require.NoErrorf(t, err, "unable to create temp file %v", err)
tmpfilecontent := []byte("package main\nimport(\n\"time\"\n)\nfunc main(){\nfor range time.Tick(time.Second) {}\n}")
if _, err := tmpfile.Write(tmpfilecontent); err != nil {
tmpfile.Close()
t.Fatalf("unable to write temp file %v", err)
}
if err := tmpfile.Close(); err != nil {
t.Fatalf("unable to close temp file %v", err)
}
require.NoErrorf(t, tmpfile.Close(), "unable to close temp file")
err = exec.Command("go", "build", "-o", tmpfile.Name()+".exe", tmpfile.Name()).Run()
if err != nil {
t.Fatalf("unable to build temp file %v", err)
}
require.NoErrorf(t, err, "unable to build temp file %v", err)
cmd := exec.Command(tmpfile.Name() + ".exe")
@ -391,13 +294,9 @@ func TestLong_Name(t *testing.T) {
n, err := p.Name()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("getting name error %v", err)
}
require.NoErrorf(t, err, "getting name error %v", err)
basename := filepath.Base(tmpfile.Name() + ".exe")
if basename != n {
t.Fatalf("%s != %s", basename, n)
}
require.Equalf(t, basename, n, "%s != %s", basename, n)
cmd.Process.Kill()
}
@ -414,26 +313,18 @@ func TestName_Against_Python(t *testing.T) {
}
tmpdir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("unable to create temp dir %v", err)
}
require.NoErrorf(t, err, "unable to create temp dir %v", err)
defer os.RemoveAll(tmpdir) // clean up
tmpfilepath := filepath.Join(tmpdir, "looooooooooooooooooooong.py")
tmpfile, err := os.Create(tmpfilepath)
if err != nil {
t.Fatalf("unable to create temp file %v", err)
}
require.NoErrorf(t, err, "unable to create temp file %v", err)
tmpfilecontent := []byte("#!" + py3Path + "\nimport psutil, time\nprint(psutil.Process().name(), flush=True)\nwhile True:\n\ttime.sleep(1)")
if _, err := tmpfile.Write(tmpfilecontent); err != nil {
tmpfile.Close()
t.Fatalf("unable to write temp file %v", err)
}
if err := tmpfile.Chmod(0o744); err != nil {
t.Fatalf("unable to chmod u+x temp file %v", err)
}
if err := tmpfile.Close(); err != nil {
t.Fatalf("unable to close temp file %v", err)
}
require.NoErrorf(t, tmpfile.Chmod(0o744), "unable to chmod u+x temp file")
require.NoErrorf(t, tmpfile.Close(), "unable to close temp file")
cmd := exec.Command(tmpfilepath)
outPipe, _ := cmd.StdoutPipe()
scanner := bufio.NewScanner(outPipe)
@ -444,17 +335,11 @@ func TestName_Against_Python(t *testing.T) {
t.Logf("pyName %s", pyName)
p, err := NewProcess(int32(cmd.Process.Pid))
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("getting process error %v", err)
}
require.NoErrorf(t, err, "getting process error %v", err)
name, err := p.Name()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("getting name error %v", err)
}
if pyName != name {
t.Fatalf("psutil and gopsutil process.Name() results differ: expected %s, got %s", pyName, name)
}
require.NoErrorf(t, err, "getting name error %v", err)
require.Equalf(t, pyName, name, "psutil and gopsutil process.Name() results differ: expected %s, got %s", pyName, name)
}
func TestExe(t *testing.T) {
@ -462,33 +347,23 @@ func TestExe(t *testing.T) {
n, err := p.Exe()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting Exe error %v", err)
}
if !strings.Contains(n, "process.test") {
t.Errorf("invalid Exe %s", n)
}
require.NoErrorf(t, err, "getting Exe error %v", err)
assert.Containsf(t, n, "process.test", "invalid Exe %s", n)
}
func TestCpuPercent(t *testing.T) {
p := testGetProcess()
_, err := p.Percent(0)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
duration := time.Duration(1000) * time.Microsecond
time.Sleep(duration)
percent, err := p.Percent(0)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
numcpu := runtime.NumCPU()
// if percent < 0.0 || percent > 100.0*float64(numcpu) { // TODO
if percent < 0.0 {
t.Fatalf("CPUPercent value is invalid: %f, %d", percent, numcpu)
}
require.GreaterOrEqualf(t, percent, 0.0, "CPUPercent value is invalid: %f, %d", percent, numcpu)
}
func TestCpuPercentLoop(t *testing.T) {
@ -499,13 +374,9 @@ func TestCpuPercentLoop(t *testing.T) {
duration := time.Duration(100) * time.Microsecond
percent, err := p.Percent(duration)
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
// if percent < 0.0 || percent > 100.0*float64(numcpu) { // TODO
if percent < 0.0 {
t.Fatalf("CPUPercent value is invalid: %f, %d", percent, numcpu)
}
require.GreaterOrEqualf(t, percent, 0.0, "CPUPercent value is invalid: %f, %d", percent, numcpu)
}
}
@ -518,20 +389,14 @@ func TestCreateTime(t *testing.T) {
c, err := p.CreateTime()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
require.NoError(t, err)
if c < 1420000000 {
t.Errorf("process created time is wrong.")
}
assert.GreaterOrEqualf(t, c, 1420000000, "process created time is wrong.")
gotElapsed := time.Since(time.Unix(int64(c/1000), 0))
maxElapsed := time.Duration(20 * time.Second)
if gotElapsed >= maxElapsed {
t.Errorf("this process has not been running for %v", gotElapsed)
}
assert.Lessf(t, gotElapsed, maxElapsed, "this process has not been running for %v", gotElapsed)
}
func TestParent(t *testing.T) {
@ -539,36 +404,24 @@ func TestParent(t *testing.T) {
c, err := p.Parent()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("error %v", err)
}
if c == nil {
t.Fatalf("could not get parent")
}
if c.Pid == 0 {
t.Fatalf("wrong parent pid")
}
require.NoError(t, err)
require.NotNilf(t, c, "could not get parent")
require.NotZerof(t, c.Pid, "wrong parent pid")
}
func TestConnections(t *testing.T) {
p := testGetProcess()
addr, err := net.ResolveTCPAddr("tcp", "localhost:0") // dynamically get a random open port from OS
if err != nil {
t.Fatalf("unable to resolve localhost: %v", err)
}
require.NoErrorf(t, err, "unable to resolve localhost: %v", err)
l, err := net.ListenTCP(addr.Network(), addr)
if err != nil {
t.Fatalf("unable to listen on %v: %v", addr, err)
}
require.NoErrorf(t, err, "unable to listen on %v: %v", addr, err)
defer l.Close()
tcpServerAddr := l.Addr().String()
tcpServerAddrIP := strings.Split(tcpServerAddr, ":")[0]
tcpServerAddrPort, err := strconv.ParseUint(strings.Split(tcpServerAddr, ":")[1], 10, 32)
if err != nil {
t.Fatalf("unable to parse tcpServerAddr port: %v", err)
}
require.NoErrorf(t, err, "unable to parse tcpServerAddr port: %v", err)
serverEstablished := make(chan struct{})
go func() { // TCP listening goroutine
@ -586,9 +439,7 @@ func TestConnections(t *testing.T) {
}()
conn, err := net.Dial("tcp", tcpServerAddr)
if err != nil {
t.Fatalf("unable to dial %v: %v", tcpServerAddr, err)
}
require.NoErrorf(t, err, "unable to dial %v: %v", tcpServerAddr, err)
defer conn.Close()
// Rarely the call to net.Dial returns before the server connection is
@ -597,19 +448,13 @@ func TestConnections(t *testing.T) {
c, err := p.Connections()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("error %v", err)
}
if len(c) == 0 {
t.Fatal("no connections found")
}
require.NoError(t, err)
require.NotEmptyf(t, c, "no connections found")
serverConnections := 0
for _, connection := range c {
if connection.Laddr.IP == tcpServerAddrIP && connection.Laddr.Port == uint32(tcpServerAddrPort) && connection.Raddr.Port != 0 {
if connection.Status != "ESTABLISHED" {
t.Fatalf("expected server connection to be ESTABLISHED, have %+v", connection)
}
require.Equalf(t, "ESTABLISHED", connection.Status, "expected server connection to be ESTABLISHED, have %+v", connection)
serverConnections++
}
}
@ -617,20 +462,14 @@ func TestConnections(t *testing.T) {
clientConnections := 0
for _, connection := range c {
if connection.Raddr.IP == tcpServerAddrIP && connection.Raddr.Port == uint32(tcpServerAddrPort) {
if connection.Status != "ESTABLISHED" {
t.Fatalf("expected client connection to be ESTABLISHED, have %+v", connection)
}
require.Equalf(t, "ESTABLISHED", connection.Status, "expected client connection to be ESTABLISHED, have %+v", connection)
clientConnections++
}
}
if serverConnections != 1 { // two established connections, one for the server, the other for the client
t.Fatalf("expected 1 server connection, have %d.\nDetails: %+v", serverConnections, c)
}
if clientConnections != 1 { // two established connections, one for the server, the other for the client
t.Fatalf("expected 1 server connection, have %d.\nDetails: %+v", clientConnections, c)
}
// two established connections, one for the server, the other for the client
require.Equalf(t, 1, serverConnections, "expected 1 server connection, have %d.\nDetails: %+v", serverConnections, c)
// two established connections, one for the server, the other for the client
require.Equalf(t, 1, clientConnections, "expected 1 server connection, have %d.\nDetails: %+v", clientConnections, c)
}
func TestChildren(t *testing.T) {
@ -647,12 +486,8 @@ func TestChildren(t *testing.T) {
c, err := p.Children()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("error %v", err)
}
if len(c) == 0 {
t.Fatalf("children is empty")
}
require.NoError(t, err)
require.NotEmptyf(t, c, "children is empty")
found := false
for _, child := range c {
if child.Pid == int32(cmd.Process.Pid) {
@ -660,9 +495,7 @@ func TestChildren(t *testing.T) {
break
}
}
if !found {
t.Errorf("could not find child %d", cmd.Process.Pid)
}
assert.Truef(t, found, "could not find child %d", cmd.Process.Pid)
}
func TestUsername(t *testing.T) {
@ -706,8 +539,8 @@ func TestCPUTimes(t *testing.T) {
measuredElapsed := cpuTimes1.Total() - cpuTimes0.Total()
message := fmt.Sprintf("Measured %fs != spun time of %fs\ncpuTimes0=%v\ncpuTimes1=%v",
measuredElapsed, spinSeconds, cpuTimes0, cpuTimes1)
assert.Greater(t, measuredElapsed, float64(spinSeconds)/5, message)
assert.Less(t, measuredElapsed, float64(spinSeconds)*5, message)
assert.Greaterf(t, measuredElapsed, float64(spinSeconds)/5, message)
assert.Lessf(t, measuredElapsed, float64(spinSeconds)*5, message)
}
func TestOpenFiles(t *testing.T) {
@ -763,49 +596,33 @@ func TestIsRunning(t *testing.T) {
require.NoError(t, err)
running, err := p.IsRunning()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("IsRunning error: %v", err)
}
if !running {
t.Fatalf("process should be found running")
}
require.NoErrorf(t, err, "IsRunning error: %v", err)
require.Truef(t, running, "process should be found running")
cmd.Wait()
running, err = p.IsRunning()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("IsRunning error: %v", err)
}
if running {
t.Fatalf("process should NOT be found running")
}
require.NoErrorf(t, err, "IsRunning error: %v", err)
require.Falsef(t, running, "process should NOT be found running")
}
// #nosec G204
func TestEnviron(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatalf("unable to create temp dir %v", err)
}
require.NoErrorf(t, err, "unable to create temp dir %v", err)
defer os.RemoveAll(tmpdir) // clean up
tmpfilepath := filepath.Join(tmpdir, "test.go")
tmpfile, err := os.Create(tmpfilepath)
if err != nil {
t.Fatalf("unable to create temp file %v", err)
}
require.NoErrorf(t, err, "unable to create temp file %v", err)
tmpfilecontent := []byte("package main\nimport(\n\"time\"\n)\nfunc main(){\nfor range time.Tick(time.Second) {}\n}")
if _, err := tmpfile.Write(tmpfilecontent); err != nil {
tmpfile.Close()
t.Fatalf("unable to write temp file %v", err)
}
if err := tmpfile.Close(); err != nil {
t.Fatalf("unable to close temp file %v", err)
}
require.NoErrorf(t, tmpfile.Close(), "unable to close temp file")
err = exec.Command("go", "build", "-o", tmpfile.Name()+".exe", tmpfile.Name()).Run()
if err != nil {
t.Fatalf("unable to build temp file %v", err)
}
require.NoErrorf(t, err, "unable to build temp file %v", err)
cmd := exec.Command(tmpfile.Name() + ".exe")
@ -820,9 +637,7 @@ func TestEnviron(t *testing.T) {
envs, err := p.Environ()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("getting environ error %v", err)
}
require.NoErrorf(t, err, "getting environ error %v", err)
var envvarFound bool
for _, envvar := range envs {
if envvar == "testkey=envvalue" {
@ -830,9 +645,7 @@ func TestEnviron(t *testing.T) {
break
}
}
if !envvarFound {
t.Error("environment variable not found")
}
assert.Truef(t, envvarFound, "environment variable not found")
}
func TestCwd(t *testing.T) {
@ -842,9 +655,7 @@ func TestCwd(t *testing.T) {
process, _ := NewProcess(int32(myPid))
pidCwd, err := process.Cwd()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Fatalf("getting cwd error %v", err)
}
require.NoErrorf(t, err, "getting cwd error %v", err)
pidCwd = strings.TrimSuffix(pidCwd, string(os.PathSeparator))
assert.Equal(t, currentWorkingDirectory, pidCwd)

@ -8,6 +8,9 @@ import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common"
)
@ -19,9 +22,7 @@ func TestTemperatureStat_String(t *testing.T) {
Critical: 0.1,
}
s := `{"sensorKey":"CPU","temperature":1.1,"sensorHigh":30.1,"sensorCritical":0.1}`
if s != fmt.Sprintf("%v", v) {
t.Errorf("TemperatureStat string is invalid, %v", fmt.Sprintf("%v", v))
}
assert.Equalf(t, s, fmt.Sprintf("%v", v), "TemperatureStat string is invalid, %v", fmt.Sprintf("%v", v))
}
func skipIfNotImplementedErr(t *testing.T, err error) {
@ -36,11 +37,7 @@ func TestTemperatures(t *testing.T) {
}
v, err := SensorsTemperatures()
skipIfNotImplementedErr(t, err)
if err != nil {
t.Errorf("error %v", err)
}
if len(v) == 0 {
t.Errorf("Could not get temperature %v", v)
}
require.NoError(t, err)
assert.NotEmptyf(t, v, "Could not get temperature %v", v)
t.Log(v)
}

Loading…
Cancel
Save