github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/client/stats/cpu_test.go (about) 1 package stats 2 3 import ( 4 "math" 5 "os" 6 "testing" 7 "time" 8 9 "github.com/hashicorp/nomad/ci" 10 shelpers "github.com/hashicorp/nomad/helper/stats" 11 "github.com/hashicorp/nomad/helper/testlog" 12 "github.com/stretchr/testify/assert" 13 ) 14 15 func TestCpuStatsPercent(t *testing.T) { 16 ci.Parallel(t) 17 18 cs := NewCpuStats() 19 cs.Percent(79.7) 20 time.Sleep(1 * time.Second) 21 percent := cs.Percent(80.69) 22 expectedPercent := 98.00 23 if percent < expectedPercent && percent > (expectedPercent+1.00) { 24 t.Fatalf("expected: %v, actual: %v", expectedPercent, percent) 25 } 26 } 27 28 func TestHostStats_CPU(t *testing.T) { 29 ci.Parallel(t) 30 31 assert := assert.New(t) 32 assert.Nil(shelpers.Init()) 33 34 logger := testlog.HCLogger(t) 35 cwd, err := os.Getwd() 36 assert.Nil(err) 37 hs := NewHostStatsCollector(logger, cwd, nil) 38 39 // Collect twice so we can calculate percents we need to generate some work 40 // so that the cpu values change 41 assert.Nil(hs.Collect()) 42 total := 0 43 for i := 1; i < 1000000000; i++ { 44 total *= i 45 total = total % i 46 } 47 assert.Nil(hs.Collect()) 48 stats := hs.Stats() 49 50 assert.NotZero(stats.CPUTicksConsumed) 51 assert.NotZero(len(stats.CPU)) 52 53 for _, cpu := range stats.CPU { 54 assert.False(math.IsNaN(cpu.Idle)) 55 assert.False(math.IsNaN(cpu.Total)) 56 assert.False(math.IsNaN(cpu.System)) 57 assert.False(math.IsNaN(cpu.User)) 58 59 assert.False(math.IsInf(cpu.Idle, 0)) 60 assert.False(math.IsInf(cpu.Total, 0)) 61 assert.False(math.IsInf(cpu.System, 0)) 62 assert.False(math.IsInf(cpu.User, 0)) 63 } 64 }