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

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

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

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

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

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

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

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

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

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

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

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

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

@ -26,7 +26,7 @@ func TestVirtualMemoryDarwin(t *testing.T) {
assert.Equal(t, uint64(actualTotal), v.Total) assert.Equal(t, uint64(actualTotal), v.Total)
assert.Positive(t, v.Available) 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.Positive(t, v.Used)
assert.Less(t, v.Used, v.Total) assert.Less(t, v.Used, v.Total)

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

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

@ -8,6 +8,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common" "github.com/shirou/gopsutil/v4/internal/common"
) )
@ -25,13 +26,9 @@ func TestVirtualMemory(t *testing.T) {
v, err := VirtualMemory() v, err := VirtualMemory()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoError(t, err)
t.Errorf("error %v", err)
}
empty := &VirtualMemoryStat{} empty := &VirtualMemoryStat{}
if v == empty { assert.NotSamef(t, v, empty, "error %v", v)
t.Errorf("error %v", v)
}
t.Log(v) t.Log(v)
assert.Positive(t, v.Total) 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 total = v.Used + v.Free + v.Cached + v.Inactive + v.Laundry
totalStr = "used + free + cached + inactive + 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) "Total should be computable (%v): %v", totalStr, v)
assert.True(t, runtime.GOOS == "windows" || v.Free > 0) 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) "Free should be a subset of Available: %v", v)
inDelta := assert.InDelta inDelta := assert.InDelta
@ -70,13 +67,9 @@ func TestVirtualMemory(t *testing.T) {
func TestSwapMemory(t *testing.T) { func TestSwapMemory(t *testing.T) {
v, err := SwapMemory() v, err := SwapMemory()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoError(t, err)
t.Errorf("error %v", err)
}
empty := &SwapMemoryStat{} empty := &SwapMemoryStat{}
if v == empty { assert.NotSamef(t, v, empty, "error %v", v)
t.Errorf("error %v", v)
}
t.Log(v) t.Log(v)
} }
@ -91,9 +84,7 @@ func TestVirtualMemoryStat_String(t *testing.T) {
} }
t.Log(v) 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}` 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) { assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "VirtualMemoryStat string is invalid: %v", v)
t.Errorf("VirtualMemoryStat string is invalid: %v", v)
}
} }
func TestSwapMemoryStat_String(t *testing.T) { func TestSwapMemoryStat_String(t *testing.T) {
@ -110,28 +101,20 @@ func TestSwapMemoryStat_String(t *testing.T) {
PgMajFault: 6, PgMajFault: 6,
} }
e := `{"total":10,"used":30,"free":40,"usedPercent":30.1,"sin":1,"sout":2,"pgIn":3,"pgOut":4,"pgFault":5,"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) { assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "SwapMemoryStat string is invalid: %v", v)
t.Errorf("SwapMemoryStat string is invalid: %v", v)
}
} }
func TestSwapDevices(t *testing.T) { func TestSwapDevices(t *testing.T) {
v, err := SwapDevices() v, err := SwapDevices()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "error calling SwapDevices: %v", err)
t.Fatalf("error calling SwapDevices: %v", err)
}
t.Logf("SwapDevices() -> %+v", v) t.Logf("SwapDevices() -> %+v", v)
if len(v) == 0 { require.NotEmptyf(t, v, "no swap devices found. [this is expected if the host has swap disabled]")
t.Fatalf("no swap devices found. [this is expected if the host has swap disabled]")
}
for _, device := range v { for _, device := range v {
if device.Name == "" { require.NotEmptyf(t, device.Name, "deviceName not set in %+v", device)
t.Fatalf("deviceName not set in %+v", device)
}
if device.FreeBytes == 0 { if device.FreeBytes == 0 {
t.Logf("[WARNING] free-bytes is zero in %+v. This might be expected", device) 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.NoError(t, err)
assert.Len(t, nsInterfaces, 8) assert.Len(t, nsInterfaces, 8)
for index := range nsInterfaces { 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) assert.NotNil(t, nsInterfaces[0].linkID)
@ -110,7 +110,7 @@ func TestParseNetstatTruncated(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Len(t, nsInterfaces, 11) assert.Len(t, nsInterfaces, 11)
for index := range nsInterfaces { 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" const truncatedIface = "utun8"
@ -137,5 +137,5 @@ func TestParseNetstatTruncated(t *testing.T) {
mapUsage := newMapInterfaceNameUsage(nsInterfaces) mapUsage := newMapInterfaceNameUsage(nsInterfaces)
assert.True(t, mapUsage.isTruncated()) 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") tmpfile, err := os.CreateTemp("", "proc_dev_net")
defer os.Remove(tmpfile.Name()) // clean up 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{ cases := [4][2]string{
{"eth0: ", "eth1: "}, {"eth0: ", "eth1: "},
@ -31,7 +31,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
} }
for _, testCase := range cases { for _, testCase := range cases {
err = tmpfile.Truncate(0) 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 // Parse interface name for assertion
interface0 := strings.TrimSpace(testCase[0]) interface0 := strings.TrimSpace(testCase[0])
@ -45,7 +45,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
// Write /proc/net/dev sample output // Write /proc/net/dev sample output
_, err = tmpfile.Write(proc) _, 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()) counters, err := IOCountersByFile(true, tmpfile.Name())
@ -76,8 +76,7 @@ func TestIOCountersByFileParsing(t *testing.T) {
assert.Equal(t, uint64(1300), counters[1].Fifoout) assert.Equal(t, uint64(1300), counters[1].Fifoout)
} }
err = tmpfile.Close() assert.NoErrorf(t, tmpfile.Close(), "Temporary file closing failed")
assert.NoError(t, err, "Temporary file closing failed: ", err)
} }
func TestGetProcInodesAll(t *testing.T) { func TestGetProcInodesAll(t *testing.T) {
@ -180,11 +179,11 @@ func TestDecodeAddress(t *testing.T) {
} }
addr, err := decodeAddress(uint32(family), src) addr, err := decodeAddress(uint32(family), src)
if dst.Error { if dst.Error {
assert.Error(t, err, src) assert.Errorf(t, err, src)
} else { } else {
require.NoError(t, err, src) require.NoErrorf(t, err, src)
assert.Equal(t, dst.IP, addr.IP, src) assert.Equalf(t, dst.IP, addr.IP, src)
assert.Equal(t, dst.Port, int(addr.Port), src) assert.Equalf(t, dst.Port, int(addr.Port), src)
} }
} }
} }
@ -197,7 +196,7 @@ func TestReverse(t *testing.T) {
func TestConntrackStatFileParsing(t *testing.T) { func TestConntrackStatFileParsing(t *testing.T) {
tmpfile, err := os.CreateTemp("", "proc_net_stat_conntrack") tmpfile, err := os.CreateTemp("", "proc_net_stat_conntrack")
defer os.Remove(tmpfile.Name()) 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(` data := []byte(`
entries searched found new invalid ignore delete deleteList insert insertFailed drop earlyDrop icmpError expectNew expectCreate expectDelete searchRestart 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 // Write data to tempfile
_, err = tmpfile.Write(data) _, 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 // Function under test
stats, err := conntrackStatsFromFile(tmpfile.Name(), true) stats, err := conntrackStatsFromFile(tmpfile.Name(), true)
require.NoError(t, err) require.NoError(t, err)
assert.Len(t, stats, 8, "Expected 8 results") assert.Lenf(t, stats, 8, "Expected 8 results")
summary := &ConntrackStat{} summary := &ConntrackStat{}
for i, exp := range slist.Items() { for i, exp := range slist.Items() {

@ -8,6 +8,9 @@ import (
"runtime" "runtime"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/shirou/gopsutil/v4/internal/common" "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} v := Addr{IP: "192.168.0.1", Port: 8000}
s := fmt.Sprintf("%v", v) s := fmt.Sprintf("%v", v)
if s != `{"ip":"192.168.0.1","port":8000}` { assert.JSONEqf(t, `{"ip":"192.168.0.1","port":8000}`, s, "Addr string is invalid: %v", v)
t.Errorf("Addr string is invalid: %v", v)
}
} }
func TestIOCountersStatString(t *testing.T) { func TestIOCountersStatString(t *testing.T) {
@ -32,9 +33,7 @@ func TestIOCountersStatString(t *testing.T) {
BytesSent: 100, 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}` 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) { assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetIOCountersStat string is invalid: %v", v)
t.Errorf("NetIOCountersStat string is invalid: %v", v)
}
} }
func TestProtoCountersStatString(t *testing.T) { func TestProtoCountersStatString(t *testing.T) {
@ -47,9 +46,7 @@ func TestProtoCountersStatString(t *testing.T) {
}, },
} }
e := `{"protocol":"tcp","stats":{"ActiveOpens":4000,"MaxConn":-1,"PassiveOpens":3000}}` e := `{"protocol":"tcp","stats":{"ActiveOpens":4000,"MaxConn":-1,"PassiveOpens":3000}}`
if e != fmt.Sprintf("%v", v) { assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetProtoCountersStat string is invalid: %v", v)
t.Errorf("NetProtoCountersStat string is invalid: %v", v)
}
} }
func TestConnectionStatString(t *testing.T) { func TestConnectionStatString(t *testing.T) {
@ -60,28 +57,18 @@ func TestConnectionStatString(t *testing.T) {
Uids: []int32{10, 10}, 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}` 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) { assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetConnectionStat string is invalid: %v", v)
t.Errorf("NetConnectionStat string is invalid: %v", v)
}
} }
func TestIOCountersAll(t *testing.T) { func TestIOCountersAll(t *testing.T) {
v, err := IOCounters(false) v, err := IOCounters(false)
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "Could not get NetIOCounters: %v", err)
t.Errorf("Could not get NetIOCounters: %v", err)
}
per, err := IOCounters(true) per, err := IOCounters(true)
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "Could not get NetIOCounters: %v", err)
t.Errorf("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)
if len(v) != 1 {
t.Errorf("Could not get NetIOCounters: %v", v)
}
if v[0].Name != "all" {
t.Errorf("Invalid NetIOCounters: %v", v)
}
var pr uint64 var pr uint64
for _, p := range per { for _, p := range per {
pr += p.PacketsRecv pr += p.PacketsRecv
@ -106,16 +93,10 @@ func TestIOCountersAll(t *testing.T) {
func TestIOCountersPerNic(t *testing.T) { func TestIOCountersPerNic(t *testing.T) {
v, err := IOCounters(true) v, err := IOCounters(true)
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "Could not get NetIOCounters: %v", err)
t.Errorf("Could not get NetIOCounters: %v", err) assert.NotEmptyf(t, v, "Could not get NetIOCounters: %v", v)
}
if len(v) == 0 {
t.Errorf("Could not get NetIOCounters: %v", v)
}
for _, vv := range v { for _, vv := range v {
if vv.Name == "" { assert.NotEmptyf(t, vv.Name, "Invalid NetIOCounters: %v", vv)
t.Errorf("Invalid NetIOCounters: %v", vv)
}
} }
} }
@ -134,74 +115,44 @@ func TestGetNetIOCountersAll(t *testing.T) {
}, },
} }
ret := getIOCountersAll(n) ret := getIOCountersAll(n)
if len(ret) != 1 { assert.Lenf(t, ret, 1, "invalid return count")
t.Errorf("invalid return count") assert.Equalf(t, "all", ret[0].Name, "invalid return name")
} assert.Equalf(t, uint64(20), ret[0].BytesRecv, "invalid count bytesrecv")
if ret[0].Name != "all" { assert.Equalf(t, uint64(10), ret[0].Errin, "invalid count errin")
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")
}
} }
func TestInterfaces(t *testing.T) { func TestInterfaces(t *testing.T) {
v, err := Interfaces() v, err := Interfaces()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "Could not get NetInterfaceStat: %v", err)
t.Errorf("Could not get NetInterfaceStat: %v", err) assert.NotEmptyf(t, v, "Could not get NetInterfaceStat: %v", err)
}
if len(v) == 0 {
t.Errorf("Could not get NetInterfaceStat: %v", err)
}
for _, vv := range v { for _, vv := range v {
if vv.Name == "" { assert.NotEmptyf(t, vv.Name, "Invalid NetInterface: %v", vv)
t.Errorf("Invalid NetInterface: %v", vv)
}
} }
} }
func TestProtoCountersStatsAll(t *testing.T) { func TestProtoCountersStatsAll(t *testing.T) {
v, err := ProtoCounters(nil) v, err := ProtoCounters(nil)
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "Could not get NetProtoCounters: %v", err)
t.Fatalf("Could not get NetProtoCounters: %v", err) require.NotEmptyf(t, v, "Could not get NetProtoCounters: %v", err)
}
if len(v) == 0 {
t.Fatalf("Could not get NetProtoCounters: %v", err)
}
for _, vv := range v { for _, vv := range v {
if vv.Protocol == "" { assert.NotEmptyf(t, vv.Protocol, "Invalid NetProtoCountersStat: %v", vv)
t.Errorf("Invalid NetProtoCountersStat: %v", vv) assert.NotEmptyf(t, vv.Stats, "Invalid NetProtoCountersStat: %v", vv)
}
if len(vv.Stats) == 0 {
t.Errorf("Invalid NetProtoCountersStat: %v", vv)
}
} }
} }
func TestProtoCountersStats(t *testing.T) { func TestProtoCountersStats(t *testing.T) {
v, err := ProtoCounters([]string{"tcp", "ip"}) v, err := ProtoCounters([]string{"tcp", "ip"})
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "Could not get NetProtoCounters: %v", err)
t.Fatalf("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)
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)
}
for _, vv := range v { for _, vv := range v {
if vv.Protocol != "tcp" && vv.Protocol != "ip" { if vv.Protocol != "tcp" && vv.Protocol != "ip" {
t.Errorf("Invalid NetProtoCountersStat: %v", vv) t.Errorf("Invalid NetProtoCountersStat: %v", vv)
} }
if len(vv.Stats) == 0 { assert.NotEmptyf(t, vv.Stats, "Invalid NetProtoCountersStat: %v", vv)
t.Errorf("Invalid NetProtoCountersStat: %v", vv)
}
} }
} }
@ -212,16 +163,10 @@ func TestConnections(t *testing.T) {
v, err := Connections("inet") v, err := Connections("inet")
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "could not get NetConnections: %v", err)
t.Errorf("could not get NetConnections: %v", err) assert.NotEmptyf(t, v, "could not get NetConnections: %v", v)
}
if len(v) == 0 {
t.Errorf("could not get NetConnections: %v", v)
}
for _, vv := range v { for _, vv := range v {
if vv.Family == 0 { assert.NotZerof(t, vv.Family, "invalid NetConnections: %v", vv)
t.Errorf("invalid NetConnections: %v", vv)
}
} }
} }
@ -239,16 +184,10 @@ func TestFilterCounters(t *testing.T) {
v, err := FilterCounters() v, err := FilterCounters()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)
if err != nil { require.NoErrorf(t, err, "could not get NetConnections: %v", err)
t.Errorf("could not get NetConnections: %v", err) assert.NotEmptyf(t, v, "could not get NetConnections: %v", v)
}
if len(v) == 0 {
t.Errorf("could not get NetConnections: %v", v)
}
for _, vv := range v { for _, vv := range v {
if vv.ConnTrackMax == 0 { assert.NotZerof(t, vv.ConnTrackMax, "nf_connTrackMax needs to be greater than zero: %v", vv)
t.Errorf("nf_connTrackMax needs to be greater than zero: %v", vv)
}
} }
} }
@ -263,13 +202,9 @@ func TestInterfaceStatString(t *testing.T) {
} }
s := fmt.Sprintf("%v", v) 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"}]}` { 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)
t.Errorf("InterfaceStat string is invalid: %v", s)
}
list := InterfaceStatList{v, v} list := InterfaceStatList{v, v}
s = fmt.Sprintf("%v", list) 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"}]}]` { 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)
t.Errorf("InterfaceStatList string is invalid: %v", s)
}
} }

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

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

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

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

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

Loading…
Cancel
Save